import telebot from fastapi import FastAPI, Request, HTTPException import uvicorn from pydantic import BaseModel # Your bot token is needed internally to send messages via Telegram's API. TOKEN = "6655373829:AAGduLdLyNx7zUtxH73Sp3Z1vHKS35tV9WU" # Your externally configured webhook URL (set up previously via BotFather or API call) WEBHOOK_URL = "https://astraos-testing.hf.space/webhook" # Initialize the TeleBot instance bot = telebot.TeleBot(TOKEN, parse_mode="HTML") # Create a FastAPI app instance app = FastAPI() # --- Models for request validation --- class MessageRequest(BaseModel): chat_id: int text: str # --- Endpoints --- @app.post("/webhook") async def telegram_webhook(request: Request): """ This endpoint receives incoming update payloads from Telegram. Telegram sends updates as JSON via a POST request to this URL. """ try: json_data = await request.json() except Exception as e: raise HTTPException(status_code=400, detail="Invalid JSON payload") update = telebot.types.Update.de_json(json_data) # Process the update (this will call any message handlers you've set up) bot.process_new_updates([update]) # Acknowledge receipt of the update return {"status": "ok"} @app.get("/") def home(): """ A simple endpoint to verify that your bot’s webhook server is running. """ return {"message": "Bot is running via webhook"} @app.post("/send_message") async def send_message(msg: MessageRequest): """ This endpoint allows you to send a message from your bot to a user. You provide a JSON payload with 'chat_id' and 'text'. For example, you can POST: { "chat_id": 123456789, "text": "Hello from webhook-only mode!" } The message is sent by calling the Telegram Bot API internally. """ try: sent_message = bot.send_message(msg.chat_id, msg.text) return {"status": "sent", "message_id": sent_message.message_id} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) # --- Example Message Handler --- @bot.message_handler(commands=["start"]) def start_command(message): """ When a user sends /start to your bot via Telegram (received via webhook), this handler sends a welcome message. """ bot.reply_to(message, "Hello! I'm running via FastAPI webhook and ready to send messages!") # --- Running the App --- if __name__ == "__main__": # We run the FastAPI app using uvicorn. Since your webhook is already set up on Telegram, # you only need to start the server to receive updates. uvicorn.run(app, host="0.0.0.0", port=7860)