From aaef526c6c37ed1b3d4016092a2937433cd4d7d7 Mon Sep 17 00:00:00 2001 From: Dmitrii Morozov Date: Tue, 7 May 2024 04:08:27 +0200 Subject: Minor refactoring, extract commands to separate classes --- TelegramBot.py | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 TelegramBot.py (limited to 'TelegramBot.py') diff --git a/TelegramBot.py b/TelegramBot.py new file mode 100644 index 0000000..50db950 --- /dev/null +++ b/TelegramBot.py @@ -0,0 +1,59 @@ +import telebot +import os +import logging +import traceback +import sys +from telebot.async_telebot import AsyncTeleBot +from persistence import UserRepository + +class CommandHandler: + async def handle(self, message: telebot.types.Message): + pass + +class TelegramBot: + __bot: AsyncTeleBot + __userRepository: UserRepository + + def __init__(self, userRepository: UserRepository): + self.__userRepository = userRepository + + # Check token in environment variables + if "TELEBOT_BOT_TOKEN" not in os.environ: + raise AssertionError("Please configure TELEBOT_BOT_TOKEN as environment variables") + + self.__bot = telebot.async_telebot.AsyncTeleBot( + token=os.environ["TELEBOT_BOT_TOKEN"], + exception_handler=ExceptionHandler()) + + async def run(self): + await self.__bot.polling() + + def register_command_handler(self, command: str, command_handler: CommandHandler): + self.__bot.register_message_handler( + command_handler.handle, + commands=[ command ]) + + async def send_message_to_all(self, message_text: str): + for user in self.__userRepository.getAllUsers(): + try: + await self.__bot.send_message( + user[0], + message_text, + parse_mode='MarkdownV2' + ) + except Exception as error: + if 'bot was kicked from the group chat' in str(error): + self.__userRepository.removeChat(user[0]) + + async def reply(self, message, message_text): + await self.__bot.reply_to( + message, + message_text, + parse_mode='MarkdownV2') + +class ExceptionHandler(telebot.ExceptionHandler): + def handle(self, exception): + logging.error('Exception happened: {}'.format(str(exception))) + print(traceback.format_exc()) + sys.exit('Exiting with telebot exception') + return True \ No newline at end of file -- cgit v1.2.3