File size: 1,110 Bytes
e92fbac
 
135fdce
 
 
e92fbac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135fdce
e92fbac
 
 
 
 
 
 
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
from fastapi import FastAPI, Request
import httpx

app = FastAPI()

# Your bot token
BOT_TOKEN = "7337693933:AAGKjpcWREFw5u4U_efy0UkRbq692QxC87k"
TELEGRAM_API_URL = f"https://api.telegram.org/bot{BOT_TOKEN}"

@app.post("/webhook")
async def telegram_webhook(request: Request):
    data = await request.json()
    
    # Extract chat ID and message text
    chat_id = data.get("message", {}).get("chat", {}).get("id")
    message_text = data.get("message", {}).get("text", "").lower()

    # Respond to "hi"
    if message_text == "hi":
        await send_message(chat_id, "Hi!")

    return {"status": "ok"}

async def send_message(chat_id: int, text: str):
    url = f"{TELEGRAM_API_URL}/sendMessage"
    payload = {"chat_id": chat_id, "text": text}
    async with httpx.AsyncClient() as client:
        await client.post(url, json=payload)

@app.get("/")
def root():
    # Default welcome message for visitors
    return {
        "message": "Welcome to the Telegram Bot API!",
        "instructions": "Set up your Telegram bot by setting the webhook to this URL.",
        "status": "Bot is running!"
    }