Repository navigation
Update bot main code - #50
Sasha198-rt wants to merge 9 commits into
Conversation
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.
📝 WalkthroughWalkthroughRemoved dotenv loading and dynamic token logic; replaced previous guarded bot initialization and command registration with a simplified top-level TeleBot setup that uses Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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 |
There was a problem hiding this comment.
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
Added Telegram bot functionality with start command and message echo.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
main.py (1)
20-21: Wrapbot.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
| # Получаем токен из 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) |
There was a problem hiding this comment.
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.
| @bot.message_handler(func=lambda message: True) | ||
| def echo(message): | ||
| bot.send_message(message.chat.id, message.text) |
There was a problem hiding this comment.
🧩 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 || trueRepository: 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:
- 1: https://pypi.org/project/pyTelegramBotAPI/
- 2: https://pytba.readthedocs.io/en/4.29.0/sync_version/
- 3: https://pytba.readthedocs.io/_/downloads/en/4.29.0/pdf/?utm_source=openai
- 4: https://pypi.org/project/pyTelegramBotAPI/
🌐 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 passcontent_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:
- 1: https://pytba.readthedocs.io/_/downloads/en/4.8.0/pdf/
- 2: https://stackoverflow.com/questions/68721475/pytelegrambotapi-message-handlers-cant-see-photo?utm_source=openai
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.
| @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.
Updated main.py with new bot logic and removed old template code.
Summary by CodeRabbit
New Features
Breaking Changes
Note