AnataBak commited on
Commit
ceca536
·
verified ·
1 Parent(s): 3a6c05b

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. src/botik/__main__.py +1 -1
  2. src/botik/webhook_app.py +27 -14
src/botik/__main__.py CHANGED
@@ -21,7 +21,7 @@ def main() -> None:
21
  storage.initialize()
22
  gemini = GeminiService(settings.gemini_api_key)
23
  application = build_application(settings=settings, storage=storage, gemini=gemini)
24
- if settings.run_mode == "webhook":
25
  run_webhook_server(application=application, settings=settings)
26
  return
27
 
 
21
  storage.initialize()
22
  gemini = GeminiService(settings.gemini_api_key)
23
  application = build_application(settings=settings, storage=storage, gemini=gemini)
24
+ if settings.app_base_url is not None:
25
  run_webhook_server(application=application, settings=settings)
26
  return
27
 
src/botik/webhook_app.py CHANGED
@@ -23,7 +23,6 @@ def run_webhook_server(application: Application, settings: Settings) -> None:
23
 
24
 
25
  def create_webhook_app(application: Application, settings: Settings) -> FastAPI:
26
- webhook_url = _build_webhook_url(settings)
27
  startup_state = {
28
  "ready": False,
29
  "task": None,
@@ -32,7 +31,7 @@ def create_webhook_app(application: Application, settings: Settings) -> FastAPI:
32
  @asynccontextmanager
33
  async def lifespan(_: FastAPI):
34
  startup_state["task"] = asyncio.create_task(
35
- _startup_until_ready(application, settings, webhook_url, startup_state)
36
  )
37
  try:
38
  yield
@@ -60,6 +59,8 @@ def create_webhook_app(application: Application, settings: Settings) -> FastAPI:
60
  request: Request,
61
  x_telegram_bot_api_secret_token: str | None = Header(default=None),
62
  ) -> dict[str, bool]:
 
 
63
  expected_secret = settings.webhook_secret
64
  if expected_secret and x_telegram_bot_api_secret_token != expected_secret:
65
  raise HTTPException(status_code=401, detail="Invalid secret token")
@@ -74,15 +75,9 @@ def create_webhook_app(application: Application, settings: Settings) -> FastAPI:
74
  return app
75
 
76
 
77
- def _build_webhook_url(settings: Settings) -> str:
78
- assert settings.app_base_url is not None
79
- return f"{settings.app_base_url.rstrip('/')}{WEBHOOK_PATH}"
80
-
81
-
82
  async def _startup_until_ready(
83
  application: Application,
84
  settings: Settings,
85
- webhook_url: str,
86
  startup_state: dict[str, object],
87
  ) -> None:
88
  attempt = 0
@@ -92,16 +87,29 @@ async def _startup_until_ready(
92
  await application.initialize()
93
  await application.start()
94
  await _cache_bot_info(application)
95
- await application.bot.set_webhook(
96
- url=webhook_url,
97
- secret_token=settings.webhook_secret,
98
- allowed_updates=Update.ALL_TYPES,
99
- )
100
- logger.info("Webhook is set to %s", webhook_url)
 
 
 
 
 
 
 
 
101
  startup_state["ready"] = True
102
  return
103
  except Exception as error:
104
  logger.warning("Startup attempt %s failed: %s", attempt, error)
 
 
 
 
 
105
  try:
106
  await application.stop()
107
  except Exception:
@@ -111,3 +119,8 @@ async def _startup_until_ready(
111
  except Exception:
112
  pass
113
  await asyncio.sleep(min(30, 5 * attempt))
 
 
 
 
 
 
23
 
24
 
25
  def create_webhook_app(application: Application, settings: Settings) -> FastAPI:
 
26
  startup_state = {
27
  "ready": False,
28
  "task": None,
 
31
  @asynccontextmanager
32
  async def lifespan(_: FastAPI):
33
  startup_state["task"] = asyncio.create_task(
34
+ _startup_until_ready(application, settings, startup_state)
35
  )
36
  try:
37
  yield
 
59
  request: Request,
60
  x_telegram_bot_api_secret_token: str | None = Header(default=None),
61
  ) -> dict[str, bool]:
62
+ if settings.run_mode != "webhook":
63
+ raise HTTPException(status_code=404, detail="Webhook mode is disabled")
64
  expected_secret = settings.webhook_secret
65
  if expected_secret and x_telegram_bot_api_secret_token != expected_secret:
66
  raise HTTPException(status_code=401, detail="Invalid secret token")
 
75
  return app
76
 
77
 
 
 
 
 
 
78
  async def _startup_until_ready(
79
  application: Application,
80
  settings: Settings,
 
81
  startup_state: dict[str, object],
82
  ) -> None:
83
  attempt = 0
 
87
  await application.initialize()
88
  await application.start()
89
  await _cache_bot_info(application)
90
+ if settings.run_mode == "webhook":
91
+ webhook_url = _build_webhook_url(settings)
92
+ await application.bot.set_webhook(
93
+ url=webhook_url,
94
+ secret_token=settings.webhook_secret,
95
+ allowed_updates=Update.ALL_TYPES,
96
+ )
97
+ logger.info("Webhook is set to %s", webhook_url)
98
+ else:
99
+ await application.bot.delete_webhook(drop_pending_updates=False)
100
+ if application.updater is None:
101
+ raise RuntimeError("Polling mode requires an updater")
102
+ await application.updater.start_polling(allowed_updates=Update.ALL_TYPES)
103
+ logger.info("Polling mode started")
104
  startup_state["ready"] = True
105
  return
106
  except Exception as error:
107
  logger.warning("Startup attempt %s failed: %s", attempt, error)
108
+ if application.updater is not None:
109
+ try:
110
+ await application.updater.stop()
111
+ except Exception:
112
+ pass
113
  try:
114
  await application.stop()
115
  except Exception:
 
119
  except Exception:
120
  pass
121
  await asyncio.sleep(min(30, 5 * attempt))
122
+
123
+
124
+ def _build_webhook_url(settings: Settings) -> str:
125
+ assert settings.app_base_url is not None
126
+ return f"{settings.app_base_url.rstrip('/')}{WEBHOOK_PATH}"