import os import logging from io import BytesIO import telebot import requests from PIL…
- User
import os import logging from io import BytesIO import telebot import requests from PIL import Image
Set up logging
logging.basicConfig(level=logging.INFO)
Securely get the bot token from environment variables
bot_token = "" if not bot_token: logging.error("Telegram bot token is not set in the environment variables.") exit(1)
bot = telebot.TeleBot(bot_token)
Error handling decorators for managing asynchronous exceptions
def handle_async_exceptions(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: logging.error(f'Error with function {func.name}: {e}') raise e
codereturn wrapperHandle voice messages
@bot.message_handler(content_types=['voice']) @handle_async_exceptions def handle_voice(message): bot.reply_to(message, "Я пока не умею распознавать речь.")
Handle photo messages
@bot.message_handler(content_types=['photo']) @handle_async_exceptions def handle_photo(message): try: file_info = bot.get_file(message.photo[-1].file_id) logging.info(f"Processing photo message: {file_info.file_path}")
codefile = requests.get(f'https://api.telegram.org/file/bot{bot.token}/{file_info.file_path}') file.raise_for_status() image = Image.open(BytesIO(file.content)) # Modify the image processing to match desired functionality inverted_image = image.transpose(Image.FLIP_TOP_BOTTOM) with BytesIO() as output: inverted_image.save(output, format='JPEG') output.seek(0) bot.send_photo(message.chat.id, output) except requests.exceptions.RequestException as e: logging.error(f"Request error: {e}") bot.reply_to(message, f"Ошибка загрузки файла: {e}") except Exception as e: logging.error(f"Image processing error: {e}") bot.reply_to(message, f"Ошибка обработки изображения: {e}")Start the bot
logging.info("Bot starting...") bot.polling(none_stop=True)
Добавь приветствие в боте
- Assistant
To add a greeting message to your bot, you can implement a handler for the
/startcommand. This command is often used to initiate interaction with the bot. Here's how you can add this functionality:python# Handle /start command @bot.message_handler(commands=['start']) @handle_async_exceptions def send_welcome(message): welcome_message = ( "Привет! Я ваш бот. Я могу обрабатывать голосовые и фото сообщения.\n" "Отправьте мне фото, и я его обработаю!" ) bot.reply_to(message, welcome_message) # Existing code for voice and photo handling goes here... # Start the bot logging.info("Bot starting...") bot.polling(none_stop=True)In the code above, a handler function
send_welcomeis created to handle the/startcommand. When the bot receives this command, it replies with a welcome message. Be sure to place this function above the code where the bot starts polling to ensure it gets registered before the bot begins handling messages.