dynstat commited on
Commit
3756173
·
verified ·
1 Parent(s): b06b3f5

Update app.py

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