Repository navigation
Update main.py - #34
googlanubis-create wants to merge 1 commit into
Conversation
📝 WalkthroughWalkthroughTransitioned the Telegram bot from synchronous Changes
Sequence Diagram(s)sequenceDiagram
actor User
participant Telegram
participant Bot as Bot Application
participant DeepSeek as DeepSeek API
User->>Telegram: Send message
Telegram->>Bot: Deliver update
Bot->>Bot: handle_message triggered
Bot->>Telegram: Send typing action
Bot->>DeepSeek: POST chat completions request
DeepSeek->>Bot: Return response (HTTP 200)
Bot->>Bot: Parse choices[0].message.content
Bot->>Telegram: Send AI response
Telegram->>User: Display message
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
📝 Coding Plan
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment Tip CodeRabbit can use OpenGrep to find security vulnerabilities and bugs across 17+ programming languages.OpenGrep is compatible with Semgrep configurations. Add an |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@main.py`:
- Around line 79-80: The startup message claims the bot will run in "echo" mode
but the code still registers handle_message which always calls DeepSeek with a
None bearer; fix by either failing fast when DEEPSEEK_API_KEY is missing (raise
SystemExit or logger.error and exit) or by wiring a true fallback handler for
that path (register an echo handler instead of handle_message). Concretely, when
DEEPSEEK_API_KEY is falsy replace the registration of handle_message with a
lightweight echo handler (e.g., handle_message_echo) or early-exit before the
lines that register handle_message so handle_message is only registered when a
valid DEEPSEEK_API_KEY exists. Ensure the symbols handle_message and the
registration call (where handle_message is passed to the dispatcher/registrar)
are updated accordingly.
- Around line 69-71: The error_handler currently logs the entire Update object
which can leak user data; change logger.warning in error_handler to log only
minimal metadata (e.g., update.update_id and the handler name via
error_handler.__name__ or a passed handler identifier) and log the exception
separately (e.g., include context.error or its traceback) instead of serializing
the whole Update; update the references in error_handler and ensure no direct
serialization of update occurs anywhere (keep the function name error_handler
and context.error as the unique symbols to locate the fix).
- Line 25: The async handler function handle_message is blocking the event loop
by calling requests.post synchronously; change this to non-blocking by either
replacing requests.post with an async HTTP client (e.g., httpx.AsyncClient) or
offloading the synchronous call to a thread with asyncio.to_thread or
loop.run_in_executor and always pass a bounded timeout (e.g., timeout=5) and
catch exceptions (Timeout, RequestException) so the handler never blocks or
crashes; update the code around the requests.post call to use the chosen async
approach, propagate results back to handle_message, and ensure errors/timeouts
are logged and produce a safe fallback response.
| "Просто напиши мне что-нибудь, и я отвечу. Также я могу работать в группах, если меня туда добавить." | ||
| ) | ||
|
|
||
| async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): |
There was a problem hiding this comment.
Don’t block the async update loop on the DeepSeek request.
Line 52 runs a synchronous requests.post() inside an async python-telegram-bot handler, and there is no timeout. One slow or hung upstream call can freeze message processing for every chat until it returns. Use async I/O here, or at least offload the requests call to a thread and bound it with a timeout.
Minimal fix without switching HTTP libraries
+import asyncio
- response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload)
+ response = await asyncio.to_thread(
+ requests.post,
+ DEEPSEEK_API_URL,
+ headers=headers,
+ json=payload,
+ timeout=15,
+ )Also applies to: 52-53
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@main.py` at line 25, The async handler function handle_message is blocking
the event loop by calling requests.post synchronously; change this to
non-blocking by either replacing requests.post with an async HTTP client (e.g.,
httpx.AsyncClient) or offloading the synchronous call to a thread with
asyncio.to_thread or loop.run_in_executor and always pass a bounded timeout
(e.g., timeout=5) and catch exceptions (Timeout, RequestException) so the
handler never blocks or crashes; update the code around the requests.post call
to use the chosen async approach, propagate results back to handle_message, and
ensure errors/timeouts are logged and produce a safe fallback response.
| async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE): | ||
| """Обработчик ошибок""" | ||
| logger.warning(f"Update {update} caused error {context.error}") |
There was a problem hiding this comment.
Don’t log the entire Telegram Update payload.
Line 71 will serialize user messages and identifiers into logs on every exception. That is a privacy leak. Log only minimal metadata like update_id and handler name, then record the exception separately.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@main.py` around lines 69 - 71, The error_handler currently logs the entire
Update object which can leak user data; change logger.warning in error_handler
to log only minimal metadata (e.g., update.update_id and the handler name via
error_handler.__name__ or a passed handler identifier) and log the exception
separately (e.g., include context.error or its traceback) instead of serializing
the whole Update; update the references in error_handler and ensure no direct
serialization of update occurs anywhere (keep the function name error_handler
and context.error as the unique symbols to locate the fix).
| if not DEEPSEEK_API_KEY: | ||
| logger.warning("DEEPSEEK_API_KEY не найден! Бот будет работать в режиме эхо.") |
There was a problem hiding this comment.
The missing-key startup path is misleading and broken.
Line 80 says the bot will run in echo mode, but Lines 85-87 still register handle_message, which always calls DeepSeek with Bearer None. Either fail fast here or wire a real fallback handler for the no-key case.
One safe option
- if not DEEPSEEK_API_KEY:
- logger.warning("DEEPSEEK_API_KEY не найден! Бот будет работать в режиме эхо.")
+ if not DEEPSEEK_API_KEY:
+ logger.error("DEEPSEEK_API_KEY не найден!")
+ returnAlso applies to: 85-87
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@main.py` around lines 79 - 80, The startup message claims the bot will run in
"echo" mode but the code still registers handle_message which always calls
DeepSeek with a None bearer; fix by either failing fast when DEEPSEEK_API_KEY is
missing (raise SystemExit or logger.error and exit) or by wiring a true fallback
handler for that path (register an echo handler instead of handle_message).
Concretely, when DEEPSEEK_API_KEY is falsy replace the registration of
handle_message with a lightweight echo handler (e.g., handle_message_echo) or
early-exit before the lines that register handle_message so handle_message is
only registered when a valid DEEPSEEK_API_KEY exists. Ensure the symbols
handle_message and the registration call (where handle_message is passed to the
dispatcher/registrar) are updated accordingly.
Summary by CodeRabbit
Release Notes
New Features
/startcommand with a welcome messageImprovements