Apex-X commited on
Commit
77f3809
·
verified ·
1 Parent(s): 13d8dcd

Create app. py

Browse files
Files changed (1) hide show
  1. app. py +61 -0
app. py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ from flask import Flask, request, jsonify
4
+
5
+ app = Flask(__name__)
6
+
7
+ # Get your Telegram Bot Token from environment variables
8
+ TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
9
+
10
+ if not TELEGRAM_BOT_TOKEN:
11
+ raise ValueError("TELEGRAM_BOT_TOKEN environment variable not set.")
12
+
13
+ TELEGRAM_API_URL = f"https://api.telegram.org/bot{2051251535:TEST:OTk5MDA4ODgxLTAwNQ}/"
14
+
15
+ def send_message(chat_id, text):
16
+ """Sends a message back to the Telegram chat."""
17
+ payload = {
18
+ "chat_id": chat_id,
19
+ "text": text
20
+ }
21
+ try:
22
+ response = requests.post(TELEGRAM_API_URL + "sendMessage", json=payload)
23
+ response.raise_for_status() # Raise an exception for HTTP errors
24
+ print(f"Message sent: {response.json()}")
25
+ except requests.exceptions.RequestException as e:
26
+ print(f"Error sending message: {e}")
27
+
28
+ @app.route("/", methods=["POST"])
29
+ def telegram_webhook():
30
+ """Receives incoming updates from Telegram via webhook."""
31
+ try:
32
+ update = request.get_json()
33
+ print(f"Received update: {update}")
34
+
35
+ if not update:
36
+ return jsonify({"status": "no data"}), 200
37
+
38
+ message = update.get("message")
39
+ if message:
40
+ chat_id = message["chat"]["id"]
41
+ text = message.get("text")
42
+
43
+ if text:
44
+ # --- Your Bot's Logic Here ---
45
+ response_text = f"Hello from Hugging Face Space! You said: '{text}'"
46
+ send_message(chat_id, response_text)
47
+ else:
48
+ send_message(chat_id, "I only understand text messages for now.")
49
+ return jsonify({"status": "ok"}), 200
50
+
51
+ except Exception as e:
52
+ print(f"Error processing webhook: {e}")
53
+ return jsonify({"status": "error", "message": str(e)}), 500
54
+
55
+ @app.route("/", methods=["GET"])
56
+ def health_check():
57
+ """A simple health check for the Space."""
58
+ return "Telegram Bot Space is running!", 200
59
+
60
+ if __name__ == "__main__":
61
+ app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))