dynstat commited on
Commit
0a084aa
·
verified ·
1 Parent(s): 2de9405

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -5
app.py CHANGED
@@ -1,14 +1,79 @@
1
- from fastapi import FastAPI
2
- import os
3
- app = FastAPI()
 
 
 
 
 
 
 
 
4
 
5
  # Retrieve the Telegram bot token from environment variables
6
  TELEGRAM_BOT_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN')
7
  # Retrieve the secret token for webhook security from environment variables
8
  SECRET_TOKEN = os.environ.get('SECRET_TOKEN')
9
 
 
 
 
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  @app.get("/")
13
- def greet_json():
14
- return {"hello":"testing"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Request, Response # Import FastAPI classes for creating the web app and handling requests/responses
2
+ # from async_tgvoicebot import handle_message # Import the asynchronous function to handle incoming Telegram messages
3
+ import aiohttp # Import aiohttp for making asynchronous HTTP requests
4
+ import os # Import os module to access environment variables
5
+ import logging
6
+
7
+ app = FastAPI() # Initialize a FastAPI application instance
8
+
9
+ # Configure logging
10
+ logging.basicConfig(level=logging.INFO)
11
+ logger = logging.getLogger(__name__)
12
 
13
  # Retrieve the Telegram bot token from environment variables
14
  TELEGRAM_BOT_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN')
15
  # Retrieve the secret token for webhook security from environment variables
16
  SECRET_TOKEN = os.environ.get('SECRET_TOKEN')
17
 
18
+ print(TELEGRAM_BOT_TOKEN)
19
+ print(SECRET_TOKEN)
20
+
21
 
22
+ @app.post("/webhook")
23
+ async def webhook(request: Request):
24
+ """
25
+ Endpoint to receive webhook updates from Telegram.
26
+ Only processes the update if the secret token matches (if provided).
27
+ """
28
+ try:
29
+ # Check if a secret token is set for additional security
30
+ if SECRET_TOKEN:
31
+ # Compare the secret token in the request headers with the expected SECRET_TOKEN
32
+ if request.headers.get('X-Telegram-Bot-Api-Secret-Token') != SECRET_TOKEN:
33
+ # If tokens do not match, respond with 403 Forbidden status
34
+ return Response(status_code=403)
35
+
36
+ # Parse the incoming JSON payload from the request
37
+ update = await request.json()
38
+ # Create an asynchronous HTTP session
39
+ async with aiohttp.ClientSession() as session:
40
+ # Call the handle_message function with the current session and the message part of the update
41
+ # await handle_message(session, update.get('message', {}))
42
+ pass
43
+ # Respond to Telegram that the update was received and processed successfully
44
+ logger.info("Received webhook request")
45
+ return {"status": "ok"}
46
+ except Exception as e:
47
+ logger.error(f"Error processing webhook: {e}")
48
+ return Response(status_code=500)
49
 
50
  @app.get("/")
51
+ async def root():
52
+ """
53
+ Root endpoint to confirm that the Telegram Bot is running.
54
+ """
55
+ # Return a simple JSON message indicating the bot's status
56
+ return {"message": "Telegram Bot is running"}
57
+
58
+ # Endpoint to set webhook
59
+ @app.get("/set_webhook")
60
+ async def set_webhook():
61
+ """
62
+ Endpoint to set the Telegram webhook to the specified URL.
63
+ This should be called after deploying the bot to ensure Telegram sends updates to the correct endpoint.
64
+ """
65
+ # Construct the webhook URL using the SPACE_ID environment variable
66
+ webhook_url = f"https://{os.environ.get('SPACE_ID')}.hf.space/webhook"
67
+ # Telegram API URL to set the webhook
68
+ set_webhook_url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/setWebhook"
69
+ # Payload containing the webhook URL and the secret token for security
70
+ payload = {
71
+ "url": webhook_url,
72
+ "secret_token": SECRET_TOKEN
73
+ }
74
+ # Create an asynchronous HTTP session
75
+ async with aiohttp.ClientSession() as session:
76
+ # Send a POST request to Telegram's setWebhook API with the payload
77
+ async with session.post(set_webhook_url, json=payload) as response:
78
+ # Await and return the JSON response from Telegram confirming the webhook setup
79
+ return await response.json()