Dulanitha commited on
Commit
4c6c86f
·
verified ·
1 Parent(s): 379d347

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -13
app.py CHANGED
@@ -5,15 +5,16 @@ from fastapi import FastAPI, Request
5
  from telegram import Update, Bot, InlineKeyboardButton, InlineKeyboardMarkup
6
  from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ConversationHandler, MessageHandler, filters, ContextTypes
7
 
8
- # ========== CONFIG ==========
9
  TELEGRAM_TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
10
  HF_TOKEN = os.environ["HF_TOKEN"]
11
  HF_USERNAME = os.environ["HF_USERNAME"]
12
  GITHUB_REPO = os.environ["GITHUB_REPO"]
13
 
 
14
  SELECT_BOT, SESSION_ID, CONFIRM = range(3)
15
 
16
- # ========== HANDLERS ==========
17
  async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
18
  keyboard = [[InlineKeyboardButton("Asitha MD", callback_data="asitha")]]
19
  await update.message.reply_text(
@@ -28,14 +29,15 @@ async def bot_selected(update: Update, context: ContextTypes.DEFAULT_TYPE):
28
  context.user_data['bot_type'] = query.data
29
  await query.edit_message_text(
30
  "✅ Asitha MD තෝරාගත්තා.\n\n"
31
- "දැන් ඔබගේ WhatsApp Session ID එක (Base64 string) එවන්න:"
 
32
  )
33
  return SESSION_ID
34
 
35
  async def get_session(update: Update, context: ContextTypes.DEFAULT_TYPE):
36
  session = update.message.text.strip()
37
  if len(session) < 20:
38
- await update.message.reply_text("❌ Session ID වැරදියි. නැවත උත්සාහ කරන්න:")
39
  return SESSION_ID
40
  context.user_data['session_id'] = session
41
  keyboard = [
@@ -101,7 +103,7 @@ async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE):
101
  await update.message.reply_text("Deploy අවලංගු කළා.")
102
  return ConversationHandler.END
103
 
104
- def conv_handler():
105
  return ConversationHandler(
106
  entry_points=[CommandHandler("start", start)],
107
  states={
@@ -109,24 +111,39 @@ def conv_handler():
109
  SESSION_ID: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_session)],
110
  CONFIRM: [CallbackQueryHandler(confirm_deploy)],
111
  },
112
- fallbacks=[CommandHandler("cancel", cancel)]
 
 
113
  )
114
 
115
- # ========== FASTAPI WEBHOOK ==========
116
  telegram_app = None
117
- bot = Bot(TELEGRAM_TOKEN)
118
 
119
  @asynccontextmanager
120
  async def lifespan(app: FastAPI):
121
- global telegram_app
 
122
  telegram_app = Application.builder().token(TELEGRAM_TOKEN).build()
123
- telegram_app.add_handler(conv_handler())
 
 
 
 
124
  await telegram_app.initialize()
 
125
  space_id = os.environ.get("SPACE_ID", "").replace("/", "-")
126
- webhook_url = f"https://{space_id}.hf.space/webhook" if space_id else "https://localhost/webhook"
 
 
 
 
127
  await telegram_app.bot.set_webhook(webhook_url)
128
  print(f"✅ Webhook set to {webhook_url}")
129
- yield
 
 
 
130
  await telegram_app.bot.delete_webhook()
131
  await telegram_app.shutdown()
132
 
@@ -134,11 +151,13 @@ app = FastAPI(lifespan=lifespan)
134
 
135
  @app.get("/")
136
  async def root():
137
- return {"status": "alive", "message": "Bot is running"}
138
 
139
  @app.post("/webhook")
140
  async def webhook(request: Request):
 
141
  data = await request.json()
 
142
  update = Update.de_json(data, bot)
143
  await telegram_app.process_update(update)
144
  return {"ok": True}
 
5
  from telegram import Update, Bot, InlineKeyboardButton, InlineKeyboardMarkup
6
  from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ConversationHandler, MessageHandler, filters, ContextTypes
7
 
8
+ # ========== CONFIGURATION ==========
9
  TELEGRAM_TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
10
  HF_TOKEN = os.environ["HF_TOKEN"]
11
  HF_USERNAME = os.environ["HF_USERNAME"]
12
  GITHUB_REPO = os.environ["GITHUB_REPO"]
13
 
14
+ # Conversation states
15
  SELECT_BOT, SESSION_ID, CONFIRM = range(3)
16
 
17
+ # ========== TELEGRAM HANDLERS ==========
18
  async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
19
  keyboard = [[InlineKeyboardButton("Asitha MD", callback_data="asitha")]]
20
  await update.message.reply_text(
 
29
  context.user_data['bot_type'] = query.data
30
  await query.edit_message_text(
31
  "✅ Asitha MD තෝරාගත්තා.\n\n"
32
+ "දැන් ඔබගේ WhatsApp Session ID එක (Base64 string) එවන්න:\n"
33
+ "(ඔබ කලින් ලබාගත් session base64 string එක)"
34
  )
35
  return SESSION_ID
36
 
37
  async def get_session(update: Update, context: ContextTypes.DEFAULT_TYPE):
38
  session = update.message.text.strip()
39
  if len(session) < 20:
40
+ await update.message.reply_text("❌ Session ID එක වැරදියි. නැවත උත්සාහ කරන්න:")
41
  return SESSION_ID
42
  context.user_data['session_id'] = session
43
  keyboard = [
 
103
  await update.message.reply_text("Deploy අවලංගු කළා.")
104
  return ConversationHandler.END
105
 
106
+ def get_conversation_handler():
107
  return ConversationHandler(
108
  entry_points=[CommandHandler("start", start)],
109
  states={
 
111
  SESSION_ID: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_session)],
112
  CONFIRM: [CallbackQueryHandler(confirm_deploy)],
113
  },
114
+ fallbacks=[CommandHandler("cancel", cancel)],
115
+ per_message=False,
116
+ per_chat=True
117
  )
118
 
119
+ # ========== FASTAPI WEBHOOK SETUP (නිවැරදි කළ කොටස) ==========
120
  telegram_app = None
121
+ bot = None # මුලින් None, පසුව initialize කරන්නෙමු
122
 
123
  @asynccontextmanager
124
  async def lifespan(app: FastAPI):
125
+ global telegram_app, bot
126
+ # 1. Application එක build කරන්න
127
  telegram_app = Application.builder().token(TELEGRAM_TOKEN).build()
128
+ # 2. Bot instance එක Application එකෙන් ලබාගන්න
129
+ bot = telegram_app.bot
130
+ # 3. Handlers add කරන්න
131
+ telegram_app.add_handler(get_conversation_handler())
132
+ # 4. සම්පූර්ණ initialization
133
  await telegram_app.initialize()
134
+ # 5. Webhook URL එක set කරන්න
135
  space_id = os.environ.get("SPACE_ID", "").replace("/", "-")
136
+ if space_id:
137
+ webhook_url = f"https://{space_id}.hf.space/webhook"
138
+ else:
139
+ # fallback (local test සඳහා)
140
+ webhook_url = "https://localhost/webhook"
141
  await telegram_app.bot.set_webhook(webhook_url)
142
  print(f"✅ Webhook set to {webhook_url}")
143
+
144
+ yield # FastAPI server මෙතැනින් දිව යයි
145
+
146
+ # Shutdown: webhook ඉවත් කරන්න
147
  await telegram_app.bot.delete_webhook()
148
  await telegram_app.shutdown()
149
 
 
151
 
152
  @app.get("/")
153
  async def root():
154
+ return {"status": "alive", "message": "Telegram Bot is running with webhook"}
155
 
156
  @app.post("/webhook")
157
  async def webhook(request: Request):
158
+ global telegram_app, bot
159
  data = await request.json()
160
+ # දැන් bot සහ telegram_app යන දෙකම හරියට initialize වී ඇත
161
  update = Update.de_json(data, bot)
162
  await telegram_app.process_update(update)
163
  return {"ok": True}