shoaibrza9999 commited on
Commit
88bd027
·
verified ·
1 Parent(s): c6b39f0

Create to.py

Browse files
Files changed (1) hide show
  1. to.py +66 -0
to.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ from fastapi import FastAPI, Request
4
+ from pydantic import BaseModel
5
+ import logging
6
+
7
+ # --- Configuration ---
8
+ # Your bot token is stored as a secret in Hugging Face Space Settings
9
+ # Access it via os.environ
10
+ BOT_TOKEN = os.environ.get("BOT_TOKEN", "8103639461:AAF_F1lLwqKWUWUIuR-erBVzsODz1W37DYM")
11
+ BASE_URL = f"https://api.telegram.org/bot{BOT_TOKEN}"
12
+
13
+ # --- Set up FastAPI ---
14
+ app = FastAPI()
15
+ logging.basicConfig(level=logging.INFO)
16
+
17
+ # Pydantic model to parse the incoming Telegram data
18
+ class Update(BaseModel):
19
+ update_id: int
20
+ message: dict | None = None
21
+ edited_message: dict | None = None
22
+
23
+ @app.get("/")
24
+ def home():
25
+ """A simple health check endpoint."""
26
+ return {"status": "ok", "message": "Echo Bot Webhook is running."}
27
+
28
+ @app.post("/webhook/")
29
+ async def webhook(update: Update):
30
+ """Handles the incoming Telegram message from the webhook."""
31
+
32
+ # Check for a message object
33
+ message = update.message
34
+ if not message:
35
+ return {"status": "ok", "message": "No text message to process."}
36
+
37
+ # Extract chat_id and text
38
+ chat_id = message['chat']['id']
39
+ text = message.get('text', 'No text found.')
40
+
41
+ # Simple Echo Logic: Send the received text back
42
+ response_text = f"You said: {text}"
43
+
44
+ # Call the Telegram API to send the message back
45
+ payload = {
46
+ 'chat_id': chat_id,
47
+ 'text': response_text
48
+ }
49
+
50
+ try:
51
+ # NOTE: Outbound requests to api.telegram.org from free Spaces can sometimes be blocked.
52
+ # This is the primary hurdle for this simple setup.
53
+ # If it fails, you may need an intermediary service (proxy).
54
+ resp = requests.post(f"{BASE_URL}/sendMessage", json=payload)
55
+ resp.raise_for_status()
56
+ logging.info(f"Message sent to chat {chat_id}")
57
+ except requests.exceptions.RequestException as e:
58
+ logging.error(f"Failed to send message to Telegram: {e}")
59
+
60
+ return {"status": "ok", "message": "Processing finished"}
61
+
62
+ # NOTE: You must manually set the webhook URL after deployment.
63
+ # Use this URL: [YOUR_SPACE_URL]/webhook/
64
+ # Example: https://YOUR-HF-ACCOUNT/YOUR-SPACE-NAME.hf.space/webhook/
65
+ # Send the command:
66
+ # https://api.telegram.org/bot<BOT_TOKEN>/setWebhook?url=<YOUR_SPACE_URL>/webhook/