Telebottest / app. py
Apex-X's picture
Create app. py
77f3809 verified
raw
history blame
2.05 kB
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)))