summaryrefslogtreecommitdiff
path: root/telegram_bot/__init__.py
blob: c25af95558da6e5b37323d2413bb4b5d899e98a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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 CallbackQueryHandler:
    async def handle(self, call: telebot.types.CallbackQuery):
        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"])
    
    async def run(self):
        await self.__bot.polling(
            non_stop=True,
            timeout=500
        )
    
    def register_command_handler(self, command: str, command_handler: CommandHandler):
        self.__bot.register_message_handler(
            command_handler.handle, 
            commands=[ command ])
    
    def register_callback_query(self, callback_query_handler: CallbackQueryHandler, filter: typing.Callable):
        self.__bot.register_callback_query_handler(
            callback=callback_query_handler.handle,
            func=filter)
    
    async def answer_callback_query(self, callback_query_id):
        await self.__bot.answer_callback_query(callback_query_id=callback_query_id)
    
    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, reply_markup = None):
        await self.__bot.reply_to(
            message,
            message_text,
            reply_markup=reply_markup,
            parse_mode='MarkdownV2')