File size: 2,045 Bytes
77f3809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import os
import requests
from flask import Flask, request, jsonify

app = Flask(__name__)

# Get your Telegram Bot Token from environment variables
TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")

if not TELEGRAM_BOT_TOKEN:
    raise ValueError("TELEGRAM_BOT_TOKEN environment variable not set.")

TELEGRAM_API_URL = f"https://api.telegram.org/bot{2051251535:TEST:OTk5MDA4ODgxLTAwNQ}/"

def send_message(chat_id, text):
    """Sends a message back to the Telegram chat."""
    payload = {
        "chat_id": chat_id,
        "text": text
    }
    try:
        response = requests.post(TELEGRAM_API_URL + "sendMessage", json=payload)
        response.raise_for_status() # Raise an exception for HTTP errors
        print(f"Message sent: {response.json()}")
    except requests.exceptions.RequestException as e:
        print(f"Error sending message: {e}")

@app.route("/", methods=["POST"])
def telegram_webhook():
    """Receives incoming updates from Telegram via webhook."""
    try:
        update = request.get_json()
        print(f"Received update: {update}")

        if not update:
            return jsonify({"status": "no data"}), 200

        message = update.get("message")
        if message:
            chat_id = message["chat"]["id"]
            text = message.get("text")

            if text:
                # --- Your Bot's Logic Here ---
                response_text = f"Hello from Hugging Face Space! You said: '{text}'"
                send_message(chat_id, response_text)
            else:
                send_message(chat_id, "I only understand text messages for now.")
        return jsonify({"status": "ok"}), 200

    except Exception as e:
        print(f"Error processing webhook: {e}")
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route("/", methods=["GET"])
def health_check():
    """A simple health check for the Space."""
    return "Telegram Bot Space is running!", 200

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))