barnamemaker commited on
Commit
55581e2
·
verified ·
1 Parent(s): ea3bc58

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -21
app.py CHANGED
@@ -43,7 +43,7 @@ async def cleanup_task():
43
  os.remove(path)
44
  logger.info(f"Cleaned up old file: {f}")
45
  except Exception as e:
46
- logger.warning(f"Could not remove {f}: {e}")
47
 
48
  # --- منوی دکمه‌ها ---
49
  def get_menu():
@@ -168,7 +168,6 @@ async def handle_text(update: Update, context: ContextTypes.DEFAULT_TYPE):
168
  elif text == "❓ راهنما": await update.message.reply_text(HELP_TEXT, reply_markup=get_menu())
169
 
170
  # --- تنظیمات اتصال اصلی (Webhook) ---
171
- # افزایش تایم‌اوت‌ها به ۴۰ ثانیه برای جلوگیری از خطای اتصال در سرور ابری
172
  ptb_app = Application.builder().token(TOKEN).connect_timeout(40.0).read_timeout(40.0).build()
173
  ptb_app.add_handler(CommandHandler("start", start))
174
  ptb_app.add_handler(MessageHandler(filters.Document.PDF, handle_document))
@@ -176,26 +175,36 @@ ptb_app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_text)
176
 
177
  @asynccontextmanager
178
  async def lifespan(app: FastAPI):
179
- # تنظیم Webhook با مدیریت خطا تا سرور متوقف نشود
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  try:
181
- logger.info("⏳ در حال تنظیم Webhook...")
182
- await ptb_app.bot.set_webhook(
183
- url=f"{SPACE_URL}/webhook",
184
- drop_pending_updates=True,
185
- connect_timeout=40.0,
186
- read_timeout=40.0
187
- )
188
- logger.info("✅ Webhook با موفقیت ثبت شد!")
189
- except Exception as e:
190
- logger.error(f"❌ خطا در تنظیم Webhook: {e}")
191
-
192
- async with ptb_app:
193
- await ptb_app.start()
194
- task = asyncio.create_task(cleanup_task())
195
- yield
196
- # خاموش کردن امن
197
- task.cancel()
198
  await ptb_app.stop()
 
 
 
199
 
200
  app_web = FastAPI(lifespan=lifespan)
201
 
@@ -221,4 +230,4 @@ async def get_file(filename: str):
221
  if __name__ == "__main__":
222
  if not TOKEN:
223
  raise RuntimeError("TOKEN is missing!")
224
- uvicorn.run(app_web, host="0.0.0.0", port=7860)
 
43
  os.remove(path)
44
  logger.info(f"Cleaned up old file: {f}")
45
  except Exception as e:
46
+ pass
47
 
48
  # --- منوی دکمه‌ها ---
49
  def get_menu():
 
168
  elif text == "❓ راهنما": await update.message.reply_text(HELP_TEXT, reply_markup=get_menu())
169
 
170
  # --- تنظیمات اتصال اصلی (Webhook) ---
 
171
  ptb_app = Application.builder().token(TOKEN).connect_timeout(40.0).read_timeout(40.0).build()
172
  ptb_app.add_handler(CommandHandler("start", start))
173
  ptb_app.add_handler(MessageHandler(filters.Document.PDF, handle_document))
 
175
 
176
  @asynccontextmanager
177
  async def lifespan(app: FastAPI):
178
+ # این تابع در پس‌زمینه اجرا می‌شود تا سرور وب منتظر نماند
179
+ async def setup_telegram():
180
+ await asyncio.sleep(3) # صبر می‌کنیم تا سرور وب کاملاً بالا بیاید
181
+ try:
182
+ logger.info("⏳ در حال راه‌اندازی ربات در پس‌زمینه...")
183
+ await ptb_app.initialize()
184
+ await ptb_app.bot.set_webhook(
185
+ url=f"{SPACE_URL}/webhook",
186
+ drop_pending_updates=True,
187
+ connect_timeout=60.0,
188
+ read_timeout=60.0
189
+ )
190
+ await ptb_app.start()
191
+ logger.info("✅ Webhook با موفقیت ثبت شد و ربات آماده است!")
192
+ asyncio.create_task(cleanup_task())
193
+ except Exception as e:
194
+ logger.error(f"❌ خطا در تنظیم Webhook: {e}")
195
+
196
+ # استارت تسک در پس‌زمینه
197
+ setup_task = asyncio.create_task(setup_telegram())
198
+
199
+ yield
200
+
201
+ # خاموش کردن امن
202
  try:
203
+ setup_task.cancel()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  await ptb_app.stop()
205
+ await ptb_app.shutdown()
206
+ except Exception:
207
+ pass
208
 
209
  app_web = FastAPI(lifespan=lifespan)
210
 
 
230
  if __name__ == "__main__":
231
  if not TOKEN:
232
  raise RuntimeError("TOKEN is missing!")
233
+ uvicorn.run("app:app_web", host="0.0.0.0", port=7860)