diff options
author | Dmitrii Morozov <snoopdesigns@gmail.com> | 2024-05-07 17:15:25 +0200 |
---|---|---|
committer | Dmitrii Morozov <snoopdesigns@gmail.com> | 2024-05-07 17:15:25 +0200 |
commit | ee3e87a6ec19878d56e8f386b20c58e4d9b211b3 (patch) | |
tree | c111165b0310581abeea0cecbfd9dabe2933e0d9 /telegram_bot/__init__.py | |
parent | cfa79cbbaf42a8f74a2cd4bca4d1d495b4d597f1 (diff) |
Modules
Diffstat (limited to 'telegram_bot/__init__.py')
-rw-r--r-- | telegram_bot/__init__.py | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/telegram_bot/__init__.py b/telegram_bot/__init__.py new file mode 100644 index 0000000..ab9f61d --- /dev/null +++ b/telegram_bot/__init__.py @@ -0,0 +1,59 @@ +import telebot +import os +import logging +import traceback +import sys +from telebot.async_telebot import AsyncTeleBot +from persistence import * + +class CommandHandler: + async def handle(self, message: telebot.types.Message): + pass + +class TelegramBot: + __bot: AsyncTeleBot + __user_repository: UserRepository + + def __init__(self, user_repository: UserRepository): + self.__user_repository = user_repository + + # 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.__user_repository.get_all_users(): + 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.__user_repository.remove_chat(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 |