Danielrahmai1991's picture
Update app.py
5a373ff verified
# توکن ربات خودت رو بذار اینجا
BOT_TOKEN = "7523067447:AAEvCK2qTFz3zAxfkyn6xOmioky2naTVRm4"
from fastapi import FastAPI, Request
from telegram import Update, Bot
from telegram.ext import (
ApplicationBuilder,
ContextTypes,
MessageHandler,
filters,
)
from contextlib import asynccontextmanager
import os
# توکن ربات
# BOT_TOKEN = os.getenv("BOT_TOKEN", "PASTE_YOUR_BOT_TOKEN_HERE")
bot = Bot(BOT_TOKEN)
# مسیر ذخیره فایل‌ها
os.makedirs("downloads", exist_ok=True)
# اپلیکیشن FastAPI
app = FastAPI()
# متغیر global برای telegram app
telegram_app = None
# ✅ هندلر پیام متنی
async def handle_text(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.message.from_user
text = update.message.text
with open("downloads/messages.txt", "a", encoding="utf-8") as f:
f.write(f"{user.username or user.id}: {text}\n")
await update.message.reply_text("✅ پیام متنی ذخیره شد!")
# ✅ هندلر تصویر
async def handle_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
photo = update.message.photo[-1]
file = await context.bot.get_file(photo.file_id)
path = f"downloads/photo_{update.message.message_id}.jpg"
await file.download_to_drive(path)
await update.message.reply_text("✅ تصویر ذخیره شد!")
# ✅ Lifespan مدرن برای FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
global telegram_app
telegram_app = ApplicationBuilder().token(BOT_TOKEN).build()
telegram_app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_text))
telegram_app.add_handler(MessageHandler(filters.PHOTO, handle_photo))
# ست‌کردن آدرس webhook
webhook_url = "https://YOUR-USERNAME-YOUR-SPACENAME.hf.space/webhook"
await telegram_app.bot.set_webhook(webhook_url)
yield
await telegram_app.bot.delete_webhook()
# 🔁 ثبت lifespan به FastAPI
app.router.lifespan_context = lifespan
# ✅ روت برای دریافت پیام تلگرام
@app.post("/webhook")
async def telegram_webhook(request: Request):
global telegram_app
data = await request.json()
update = Update.de_json(data, bot)
await telegram_app.update_queue.put(update)
return {"status": "ok"}