Skip to content

Update main.py - #34

Open
googlanubis-create wants to merge 1 commit into
aeither:mainfrom
googlanubis-create:patch-2
Open

googlanubis-create wants to merge 1 commit into
aeither:mainfrom
googlanubis-create:patch-2

Conversation

@googlanubis-create

@googlanubis-create googlanubis-create commented Mar 20, 2026 •

Copy link
Copy Markdown

Summary by CodeRabbit

Release Notes

  • New Features

    • Bot now responds to /start command with a welcome message
    • Text messages are processed using AI-powered chat completions for intelligent conversational responses
  • Improvements

    • Enhanced error handling with structured logging for improved reliability and debugging
    • Startup validation ensures required credentials are properly configured before bot launches

@coderabbitai

coderabbitai Bot commented Mar 20, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Transitioned the Telegram bot from synchronous telebot polling to asynchronous python-telegram-bot (Application). Added async handlers for /start command, text messages with DeepSeek API integration, and error logging. Implemented environment variable validation and structured logging during startup with application.run_polling().

Changes

Cohort / File(s) Summary
Bot Core Migration
main.py
Replaced synchronous telebot polling with async python-telegram-bot Application. Removed old inline /start and /hello command handlers plus echo handler. Added async start(), handle_message(), and error_handler() functions. Message handler now sends typing action, calls DeepSeek chat completions API via HTTP POST, and parses JSON response. Integrated structured logging and startup validation for TELEGRAM_BOT_TOKEN and optional DEEPSEEK_API_KEY.

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A hop through the code, async and true,
From polling to handlers, all shiny and new,
The rabbit did cheer as DeepSeek took flight,
Messages dancing through Telegram's light,
Async/await magic—what a wonderful sight! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Update main.py' is vague and generic, providing no meaningful information about the substantial architectural changes made (migration from synchronous telebot to async python-telegram-bot, DeepSeek API integration, logging setup). Replace with a descriptive title that captures the main change, such as 'Migrate to async python-telegram-bot with DeepSeek integration' or 'Replace telebot with async Application and add DeepSeek API support'.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Tip

CodeRabbit can use OpenGrep to find security vulnerabilities and bugs across 17+ programming languages.

OpenGrep is compatible with Semgrep configurations. Add an opengrep.yml or semgrep.yml configuration file to your project to enable OpenGrep analysis.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 56542522-26df-4c96-8c96-183a8d97a244

📥 Commits

Reviewing files that changed from the base of the PR and between 5cfd740 and 3833f7e.

📒 Files selected for processing (1)
  • main.py

Comment thread main.py
"Просто напиши мне что-нибудь, и я отвечу. Также я могу работать в группах, если меня туда добавить."
)

async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

Comment thread main.py
Comment on lines +69 to +71
async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Обработчик ошибок"""
logger.warning(f"Update {update} caused error {context.error}")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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).

Comment thread main.py
Comment on lines +79 to +80
if not DEEPSEEK_API_KEY:
logger.warning("DEEPSEEK_API_KEY не найден! Бот будет работать в режиме эхо.")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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 не найден!")
+        return

Also 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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant