Skip to content

Update bot main code - #50

Open
Sasha198-rt wants to merge 9 commits into
aeither:mainfrom
Sasha198-rt:main
Open

Sasha198-rt wants to merge 9 commits into
aeither:mainfrom
Sasha198-rt:main

Conversation

@Sasha198-rt

@Sasha198-rt Sasha198-rt commented Apr 8, 2026 •

Copy link
Copy Markdown

Updated main.py with new bot logic and removed old template code.

Summary by CodeRabbit

  • New Features

    • /start now replies with a fixed "Бот работает ✅" message.
    • All incoming messages are echoed back to the sender.
  • Breaking Changes

    • Previously available commands (e.g., a greeting command) and the prior command handling flow have been removed; some expected bot behaviors may no longer be present.
  • Note

    • Review before deploying — functionality has been simplified.

Removed user payment and download functionalities, added echo response.
Removed print statement for the token.
Add Telegram bot functionality with /start command and echo response.
@coderabbitai

coderabbitai Bot commented Apr 8, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Removed dotenv loading and dynamic token logic; replaced previous guarded bot initialization and command registration with a simplified top-level TeleBot setup that uses os.getenv(...) with a literal key, two top-level handlers (/start and echo), and an unconditional bot.polling() call.

Changes

Cohort / File(s) Summary
Bot core
main.py
Removed environment loading and dynamic token retrieval wrappers, removed previous register_commands and its handlers, added top-level start(message) (commands=['start']) and echo(message) (catch-all) handlers, uses os.getenv('TELEGRAM_BOT_TOKEN') literal key, and now calls bot.polling() unconditionally.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I hopped through code both day and night,
Swapped dotenv for a single light,
Two handlers now, one starts the cheer,
The other echoes all I hear,
Polling forever — hop, hop, delight! 🎉

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Update bot main code' is vague and generic, failing to convey specific information about the actual changes made to the codebase. Consider a more specific title such as 'Implement /start command and message echo handlers' or 'Replace bot template with basic command and echo functionality' to clearly indicate the primary changes.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@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: 1

🤖 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`:
- Line 1: The current top-level call to bot.send_message references undefined
names and runs at import time; fix by importing and initializing a TeleBot
instance (create a bot = TeleBot(<token>) or bot = telebot.TeleBot(TOKEN) using
a config or environment variable) and remove the top-level send_message call,
then register a handler (e.g., a function decorated with
`@bot.message_handler`(...) such as message_handler or on_message) and move the
bot.send_message(message.chat.id, "NEW CODE TEST 🚀") call into that handler
using the handler's message parameter; ensure the bot is started (bot.polling()
or webhooks) after handlers are registered.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 66f60965-0917-45bc-b974-0ccc310e3e9e

📥 Commits

Reviewing files that changed from the base of the PR and between 5cfd740 and 0653bc2.

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

Comment thread main.py Outdated
Added Telegram bot functionality with start command and message echo.

@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: 2

🧹 Nitpick comments (1)
main.py (1)

20-21: Wrap bot.polling() under a main guard to improve testability and control startup behavior.

The polling call currently executes at module import time, which prevents testing the module in isolation and limits control over when the bot starts.

🔧 Proposed refactor
-# Запуск
-bot.polling()
+def main():
+    bot.polling()
+
+if __name__ == "__main__":
+    main()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@main.py` around lines 20 - 21, The module currently calls bot.polling() at
import time; move that call into a dedicated main() function and invoke it under
a main guard (if __name__ == "__main__": main()) so the bot only starts when the
module is run directly, improving testability and control; locate the existing
bot.polling() call and refactor by creating a main() wrapper that performs any
necessary startup (e.g., bot.polling()) and place the conditional invocation at
the bottom of the file.
🤖 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 4-8: Remove the hardcoded token string and stop passing it as the
environment variable name: update the TOKEN assignment to call
os.getenv("TELEGRAM_BOT_TOKEN") (or another clearly named env var) and validate
the result before creating the bot; add a check after TOKEN is read that raises
a clear error or exits if TOKEN is None/empty so telebot.TeleBot(TOKEN) cannot
be called with None. Also ensure the leaked token is rotated/invalidated
out-of-band and add a .env.example entry for TELEGRAM_BOT_TOKEN to document the
required variable.
- Around line 16-18: The handler currently matches all updates via
`@bot.message_handler`(func=lambda message: True) and then calls echo(message)
which assumes message.text is present; restrict the handler to text-only updates
or guard the call so non-text messages are ignored. Update the decorator or
filter used on the handler (the `@bot.message_handler`) to only accept text
content (e.g., content_types=['text'] or an equivalent filter) or add an early
check inside echo (e.g., verify message.text is not None before calling
bot.send_message) so bot.send_message(message.chat.id, message.text) is only
executed for real text messages.

---

Nitpick comments:
In `@main.py`:
- Around line 20-21: The module currently calls bot.polling() at import time;
move that call into a dedicated main() function and invoke it under a main guard
(if __name__ == "__main__": main()) so the bot only starts when the module is
run directly, improving testability and control; locate the existing
bot.polling() call and refactor by creating a main() wrapper that performs any
necessary startup (e.g., bot.polling()) and place the conditional invocation at
the bottom of the file.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5accc550-51cb-437d-a400-6438e82e2dbd

📥 Commits

Reviewing files that changed from the base of the PR and between 0653bc2 and e5a6245.

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

Comment thread main.py
Comment on lines +4 to +8
# Получаем токен из Railway Variables
TOKEN = os.getenv("8709005198:AAG0SB65EJZR6leqzNpCL3RYpi8_7_ipeKo")

# Replace 'TELEGRAM_BOT_TOKEN' with the token you received from BotFather
TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
try:
bot = telebot.TeleBot(TOKEN)
register_commands(bot)
# Создаём бота
bot = telebot.TeleBot(TOKEN)

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 | 🔴 Critical

Critical: secret is exposed and token loading is broken.

Line 5 hardcodes a real token-like value in source and passes it as the environment variable name. This both leaks credentials and usually yields None, which can break bot startup at Line 8. Also rotate this leaked token immediately.

🔧 Proposed fix
 # Получаем токен из Railway Variables
-TOKEN = os.getenv("8709005198:AAG0SB65EJZR6leqzNpCL3RYpi8_7_ipeKo")
+TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
+if not TOKEN:
+    raise RuntimeError("TELEGRAM_BOT_TOKEN is not set")
 
 # Создаём бота
 bot = telebot.TeleBot(TOKEN)
#!/bin/bash
set -euo pipefail

MAIN_FILE="$(fd '^main\.py$' | head -n1)"
ENV_EXAMPLE="$(fd '^\.env\.example$' | head -n1 || true)"

echo "[main.py token line]"
rg -nP 'TOKEN\s*=\s*os\.getenv\(' "$MAIN_FILE" -C1

if [[ -n "${ENV_EXAMPLE}" ]]; then
  echo "[expected env var in .env.example]"
  rg -n 'TELEGRAM_BOT_TOKEN' "$ENV_EXAMPLE" -C1 || true
fi
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@main.py` around lines 4 - 8, Remove the hardcoded token string and stop
passing it as the environment variable name: update the TOKEN assignment to call
os.getenv("TELEGRAM_BOT_TOKEN") (or another clearly named env var) and validate
the result before creating the bot; add a check after TOKEN is read that raises
a clear error or exits if TOKEN is None/empty so telebot.TeleBot(TOKEN) cannot
be called with None. Also ensure the leaked token is rotated/invalidated
out-of-band and add a .env.example entry for TELEGRAM_BOT_TOKEN to document the
required variable.

Comment thread main.py
Comment on lines +16 to +18
@bot.message_handler(func=lambda message: True)
def echo(message):
bot.send_message(message.chat.id, message.text)

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

MAIN_FILE="$(fd '^main\.py$' | head -n1)"

echo "[handler definitions]"
rg -nP '@bot\.message_handler|def\s+(start|echo)\(' "$MAIN_FILE" -C2

echo "[echo payload usage]"
rg -nP 'send_message\(\s*message\.chat\.id\s*,\s*message\.text\s*\)' "$MAIN_FILE" -C1

echo "[content-type guards present?]"
rg -nP 'content_types\s*=|message\.content_type' "$MAIN_FILE" -C1 || true

Repository: aeither/telegram-bot-python

Length of output: 540


🌐 Web query:

telebot pyTelegramBotAPI message.text non-text content types stickers photos

💡 Result:

In pyTelegramBotAPI (telebot.TeleBot), message.text is only populated for content_type == 'text'. For photos, stickers, documents, etc., message.text will be None—you must either (a) register handlers by content_types, or (b) branch on message.content_type. (pypi.org)

Option A — separate handlers per content type

import telebot
bot = telebot.TeleBot(TOKEN)

`@bot.message_handler`(content_types=['text'])
def on_text(m):
    bot.reply_to(m, f"text: {m.text}")

`@bot.message_handler`(content_types=['photo'])
def on_photo(m):
    # photo is a list of PhotoSize (usually smallest..largest); pick the last for best quality
    file_id = m.photo[-1].file_id
    caption = m.caption  # may be None
    bot.reply_to(m, f"photo file_id={file_id}\ncaption={caption}")

`@bot.message_handler`(content_types=['sticker'])
def on_sticker(m):
    file_id = m.sticker.file_id
    bot.reply_to(m, f"sticker file_id={file_id}")

message_handler(..., content_types=...) expects a list and defaults to ['text'] if you don’t provide it. (pytba.readthedocs.io)
Also, Message.photo is list[PhotoSize] and Message.sticker is a Sticker object. (pytba.readthedocs.io)

Option B — one handler for multiple types

`@bot.message_handler`(content_types=['text', 'photo', 'sticker'])
def on_any(m):
    if m.content_type == 'text':
        ...
    elif m.content_type == 'photo':
        ...
    elif m.content_type == 'sticker':
        ...

content_type can be 'text', 'photo', 'sticker', etc. (many more are supported). (pypi.org)

Citations:


🌐 Web query:

pyTelegramBotAPI content_types text handler parameter

💡 Result:

In pyTelegramBotAPI (telebot), the content_types argument on @bot.message_handler(...) filters which message “content types” a handler will receive.

  • It must be a list of strings and it defaults to ['text'] (so if you don’t pass content_types, your handler only gets text messages). [1]
  • If you set it, the handler will receive only those types, e.g. ['text', 'photo']. [2]

Examples:

# Text only (explicit)
`@bot.message_handler`(content_types=['text'])
def on_text(message):
    bot.reply_to(message, "got text")
# Text only (implicit, because default is ['text'])
`@bot.message_handler`()
def on_text(message):
    bot.reply_to(message, "got text")
# Text + photos
`@bot.message_handler`(content_types=['text', 'photo'])
def on_text_or_photo(message):
    if message.content_type == 'text':
        ...
    elif message.content_type == 'photo':
        ...

Sources: pyTelegramBotAPI docs (TeleBot “Registers message handler”, content_types default) [1], plus an example/behavior explanation (setting content_types changes what your handler receives) [2].

[1] (pytba.readthedocs.io)
[2] (stackoverflow.com)

Citations:


Handle non-text updates before echoing message.text.

Line 16 matches every message type (with func=lambda message: True), but message.text is None for stickers, photos, documents, and other non-text content. Attempting to send None at line 18 will fail.

Restrict the handler to text-only messages:

🔧 Proposed fix
-@bot.message_handler(func=lambda message: True)
+@bot.message_handler(content_types=['text'])
 def echo(message):
     bot.send_message(message.chat.id, message.text)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@bot.message_handler(func=lambda message: True)
def echo(message):
bot.send_message(message.chat.id, message.text)
`@bot.message_handler`(content_types=['text'])
def echo(message):
bot.send_message(message.chat.id, message.text)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@main.py` around lines 16 - 18, The handler currently matches all updates via
`@bot.message_handler`(func=lambda message: True) and then calls echo(message)
which assumes message.text is present; restrict the handler to text-only updates
or guard the call so non-text messages are ignored. Update the decorator or
filter used on the handler (the `@bot.message_handler`) to only accept text
content (e.g., content_types=['text'] or an equivalent filter) or add an early
check inside echo (e.g., verify message.text is not None before calling
bot.send_message) so bot.send_message(message.chat.id, message.text) is only
executed for real text messages.

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