import os import logging from io import BytesIO import telebot import speechrecognition…
- User
import os import logging from io import BytesIO import telebot import speech_recognition as sr import requests from PIL import Image
Set up logging
logging.basicConfig(level=logging.INFO)
Securely get the bot token from environment variables
bot_token = os.getenv('TELEGRAM_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
return wrapperHandle voice messages
@bot.message_handler(content_types=['voice']) @handle_async_exceptions def handle_voice(message): try: file_info = bot.get_file(message.voice.file_id) logging.info(f"Processing voice message: {file_info.file_path}")
file = requests.get(f'https://api.telegram.org/file/bot{bot.token}/{file_info.file_path}') file.raise_for_status() recognizer = sr.Recognizer() with BytesIO(file.content) as file_obj: with sr.AudioFile(file_obj) as source: audio = recognizer.record(source) try: text = recognizer.recognize_google(audio, language='ru-RU') bot.reply_to(message, text) except sr.UnknownValueError: bot.reply_to(message, "Не удалось распознать голос.") except sr.RequestError as e: bot.reply_to(message, f"Ошибка сервиса распознавания: {e}") except requests.exceptions.RequestException as e: logging.error(f"Request error: {e}") bot.reply_to(message, f"Ошибка загрузки файла: {e}")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}")
file = 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 modify your Telegram bot so that it simply responds with a message indicating that it cannot recognize speech, you should modify the
handle_voicefunction. Replace the speech recognition code with a reply message. Here's the updated version of your code: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 = os.getenv('TELEGRAM_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 return wrapper # Handle 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}") file = 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)With this change, when the bot receives a voice message, it will respond with the message "Я пока не умею распознавать речь." (translated as "I cannot recognize speech yet."). The speech recognition functionality has been removed.
- User
Добавь в мой бот какие нибудь интересные функции
- Assistant
Certainly! Here are some interesting features you could add to your Telegram bot:
- Random Joke Generator: Provide users with random jokes when they ask for it.
- Weather Information: Give users the current weather information for a given location.
- Quote of the Day: Send users an inspirational quote each time they ask.
- Currency Converter: Convert currencies using real-time exchange rates.
I'll show you how to add the Random Joke Generator and Quote of the Day. For the other features, you'll need API keys from suitable services.
Here’s how you could implement the Random Joke Generator and Quote of the Day:
Updated Code with Random Joke and Quote of the Day
import os import logging import telebot import requests from io import BytesIO from PIL import Image # Set up logging logging.basicConfig(level=logging.INFO) # Securely get the bot token from environment variables bot_token = os.getenv('TELEGRAM_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 return wrapper # Handle 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}") file = 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)) 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}") # Handle /joke command for random jokes @bot.message_handler(commands=['joke']) @handle_async_exceptions def send_joke(message): joke_response = requests.get('https://official-joke-api.appspot.com/random_joke') if joke_response.status_code == 200: joke = joke_response.json() bot.reply_to(message, f"{joke['setup']} ... {joke['punchline']}") else: bot.reply_to(message, "Не удалось получить шутку.") # Handle /quote command for quote of the day @bot.message_handler(commands=['quote']) @handle_async_exceptions def send_quote(message): quote_response = requests.get('https://api.quotable.io/random') if quote_response.status_code == 200: quote = quote_response.json() bot.reply_to(message, f"\"{quote['content']}\" - {quote['author']}") else: bot.reply_to(message, "Не удалось получить цитату.") # Start the bot logging.info("Bot starting...") bot.polling(none_stop=True)Explanation
- Joke of the Day: Uses
https://official-joke-api.appspot.com/random_joketo fetch a random joke. - Quote of the Day: Uses
https://api.quotable.io/randomto fetch a random quote.
These two features add some interactivity and fun to your bot. Invoke them by sending
/jokeor/quotein the chat where the bot is present. For weather information and currency conversion, you would need to integrate with suitable APIs and handle incoming messages appropriately to fetch and display the requested data.