|
| 1 | +from inspect import getmembers, ismethod |
| 2 | +import threading |
| 3 | +import logging |
| 4 | +import telegram |
| 5 | +import time |
| 6 | +logger = logging.getLogger(__name__) |
| 7 | +__all__ = ['CommandHandler', 'CommandHandlerWithHelp'] |
| 8 | +class CommandHandler(object): |
| 9 | + """ This handles incomming commands and gives an easy way to create commands. |
| 10 | +
|
| 11 | + How to use this: |
| 12 | + create a new class which inherits this class or CommandHandlerWithHelp. |
| 13 | + define new methods that start with 'command_' and then the command_name. |
| 14 | + run run() |
| 15 | + """ |
| 16 | + def __init__(self, bot): |
| 17 | + self.bot = bot # a telegram bot |
| 18 | + self.isValidCommand = None # a function that returns a boolean and takes one agrument an update. if False is returned the the comaand is not executed. |
| 19 | + |
| 20 | + def _get_command_func(self, command): |
| 21 | + if command[0] == '/': |
| 22 | + command = command[1:] |
| 23 | + if hasattr(self, 'command_' + command): |
| 24 | + return self.__getattribute__('command_' + command) # a function |
| 25 | + else: |
| 26 | + return None |
| 27 | + |
| 28 | + def run(self, make_thread=True, last_update_id=None, thread_timeout=2, sleep=0.2): |
| 29 | + """Continuously check for commands and run the according method |
| 30 | +
|
| 31 | + Args: |
| 32 | + make_thread: |
| 33 | + if True make a thread for each command it found. |
| 34 | + if False make run the code linearly |
| 35 | + last_update: |
| 36 | + the offset arg from getUpdates and is kept up to date within this function |
| 37 | + thread_timeout: |
| 38 | + The timeout on a thread. If a thread is alive after this period then try to join the thread in |
| 39 | + the next loop. |
| 40 | + """ |
| 41 | + old_threads = [] |
| 42 | + while True: |
| 43 | + time.sleep(sleep) |
| 44 | + threads, last_update_id = self.run_once(make_thread=make_thread, last_update_id=last_update_id) |
| 45 | + for t in threads: |
| 46 | + t.start() |
| 47 | + for t in old_threads: |
| 48 | + threads.append(t) |
| 49 | + old_threads = [] |
| 50 | + for t in threads: |
| 51 | + t.join(timeout=thread_timeout) |
| 52 | + if t.isAlive(): |
| 53 | + old_threads.append(t) |
| 54 | + |
| 55 | + def run_once(self, make_thread=True, last_update_id=None): |
| 56 | + """ Check the the messages for commands and make a Thread with the command or run the command depending on make_thread. |
| 57 | +
|
| 58 | + Args: |
| 59 | + make_thread: |
| 60 | + True: the function returns a list with threads. Which didn't start yet. |
| 61 | + False: the function just runs the command it found and returns an empty list. |
| 62 | + last_update_id: |
| 63 | + the offset arg from getUpdates and is kept up to date within this function |
| 64 | +
|
| 65 | + Returns: |
| 66 | + A tuple of two elements. The first element is a list with threads which didn't start yet or an empty list if |
| 67 | + make_threads==False. The second element is the updated las_update_id |
| 68 | + """ |
| 69 | + bot_name = self.bot.getMe().username |
| 70 | + threads = [] |
| 71 | + try: |
| 72 | + updates = self.bot.getUpdates(offset=last_update_id) |
| 73 | + except: |
| 74 | + updates = [] |
| 75 | + for update in updates: |
| 76 | + last_update_id = update.update_id + 1 |
| 77 | + message = update.message |
| 78 | + if message.text[0] == '/': |
| 79 | + command, username = message.text.split(' ')[0], bot_name |
| 80 | + if '@' in command: |
| 81 | + command, username = command.split('@') |
| 82 | + if username == bot_name: |
| 83 | + command_func = self._get_command_func(command) |
| 84 | + if command_func is not None: |
| 85 | + self.bot.sendChatAction(update.message.chat.id,telegram.ChatAction.TYPING) |
| 86 | + if self.isValidCommand is None or self.isValidCommand(update): |
| 87 | + if make_thread: |
| 88 | + t = threading.Thread(target=command_func, args=(update,)) |
| 89 | + threads.append(t) |
| 90 | + else: |
| 91 | + command_func(update) |
| 92 | + else: |
| 93 | + self._command_not_found(update) # TODO this must be another function. |
| 94 | + else: |
| 95 | + if make_thread: |
| 96 | + t = threading.Thread(target=self._command_not_found, args=(update,)) |
| 97 | + threads.append(t) |
| 98 | + else: |
| 99 | + self._command_not_valid(update) |
| 100 | + return threads, last_update_id |
| 101 | + |
| 102 | + def _command_not_valid(self, update): |
| 103 | + """Inform the telegram user that the command was not found. |
| 104 | +
|
| 105 | + Override this method if you want to do it another way then by sending the the text: |
| 106 | + Sorry, I didn't understand the command: /command[@bot]. |
| 107 | + """ |
| 108 | + chat_id = update.message.chat.id |
| 109 | + reply_to = update.message.message_id |
| 110 | + message = "Sorry, the command was not authorised or valid: {command}.".format(command=update.message.text.split(' ')[0]) |
| 111 | + self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to) |
| 112 | + |
| 113 | + def _command_not_found(self, update): |
| 114 | + """Inform the telegram user that the command was not found. |
| 115 | +
|
| 116 | + Override this method if you want to do it another way then by sending the the text: |
| 117 | + Sorry, I didn't understand the command: /command[@bot]. |
| 118 | + """ |
| 119 | + chat_id = update.message.chat.id |
| 120 | + reply_to = update.message.message_id |
| 121 | + message = "Sorry, I didn't understand the command: {command}.".format(command=update.message.text.split(' ')[0]) |
| 122 | + self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to) |
| 123 | + |
| 124 | + |
| 125 | +class CommandHandlerWithHelp(CommandHandler): |
| 126 | + """ This CommandHandler has a builtin /help. It grabs the text from the docstrings of command_ functions.""" |
| 127 | + def __init__(self, bot): |
| 128 | + super(CommandHandlerWithHelp, self).__init__(bot) |
| 129 | + self._help_title = 'Welcome to {name}.'.format(name=self.bot.getMe().username) # the title of help |
| 130 | + self._help_before_list = '' # text with information about the bot |
| 131 | + self._help_after_list = '' # a footer |
| 132 | + self._help_list_title = 'These are the commands:' # the title of the list |
| 133 | + self.is_reply = True |
| 134 | + self.command_start = self.command_help |
| 135 | + |
| 136 | + def _generate_help(self): |
| 137 | + """ Generate a string which can be send as a help file. |
| 138 | +
|
| 139 | + This function generates a help file from all the docstrings from the commands. |
| 140 | + so docstrings of methods that start with command_ should explain what a command does and how a to use the |
| 141 | + command to the telegram user. |
| 142 | + """ |
| 143 | + |
| 144 | + command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_'] |
| 145 | + help_message = self._help_title + '\n\n' |
| 146 | + help_message += self._help_before_list + '\n\n' |
| 147 | + help_message += self._help_list_title + '\n' |
| 148 | + for command_function in command_functions: |
| 149 | + if command_function.__doc__ is not None: |
| 150 | + help_message += ' /' + command_function.__name__[8:] + ' - ' + command_function.__doc__ + '\n' |
| 151 | + else: |
| 152 | + help_message += ' /' + command_function.__name__[8:] + ' - ' + '\n' |
| 153 | + help_message += '\n' |
| 154 | + help_message += self._help_after_list |
| 155 | + return help_message |
| 156 | + |
| 157 | + def _command_not_found(self, update): |
| 158 | + """Inform the telegram user that the command was not found.""" |
| 159 | + chat_id = update.message.chat.id |
| 160 | + reply_to = update.message.message_id |
| 161 | + message = 'Sorry, I did not understand the command: {command}. Please see /help for all available commands' |
| 162 | + if self.is_reply: |
| 163 | + self.bot.sendMessage(chat_id, message.format(command=update.message.text.split(' ')[0]), |
| 164 | + reply_to_message_id=reply_to) |
| 165 | + else: |
| 166 | + self.bot.sendMessage(chat_id, message.format(command=update.message.text.split(' ')[0])) |
| 167 | + |
| 168 | + def command_help(self, update): |
| 169 | + """ The help file. """ |
| 170 | + chat_id = update.message.chat.id |
| 171 | + reply_to = update.message.message_id |
| 172 | + message = self._generate_help() |
| 173 | + self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to) |
| 174 | + |
0 commit comments