From 9145f24efa2e691dab955f576b8a357f09092462 Mon Sep 17 00:00:00 2001 From: mattijn Date: Mon, 7 Sep 2015 03:13:40 +0200 Subject: [PATCH 1/6] added a father command. and some other a way to hide commands in the help. --- .gitignore | 3 ++ examples/command_handler_example.py | 25 ++++++++----- telegram/__init__.py | 4 +- telegram/command_handler.py | 57 ++++++++++++++++++++++++----- 4 files changed, 69 insertions(+), 20 deletions(-) diff --git a/.gitignore b/.gitignore index 3af8b7d5c..d7712b352 100644 --- a/.gitignore +++ b/.gitignore @@ -57,3 +57,6 @@ docs/_build/ # PyBuilder target/ .idea/ + +# token +mytoken.py diff --git a/examples/command_handler_example.py b/examples/command_handler_example.py index 33e1bc9f8..37bbd4986 100644 --- a/examples/command_handler_example.py +++ b/examples/command_handler_example.py @@ -1,11 +1,14 @@ # There could be some unused imports +import sys +sys.path.append('..') +sys.path.append('.') from inspect import getmembers, ismethod import threading import logging import telegram import time -from telegram import CommandHandlerWithHelp, CommandHandler -class ExampleCommandHandler(CommandHandlerWithHelp): +from telegram import CommandHandlerWithHelpAndFather, CommandHandler +class ExampleCommandHandler(CommandHandlerWithHelpAndFather): """This is an example how to use a CommandHandlerWithHelp or just a CommandHandler. If You want to use a CommandHandler it is very easy. @@ -31,7 +34,7 @@ class ExampleCommandHandler(CommandHandlerWithHelp): chat_id = update.message.chat.id reply_to = update.message.message_id message = "Sorry, I don't know how to do {command}.".format(command=update.message.text.split(' ')[0]) - self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to) + self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to) # creates /test command. This code gets called when a telegram user enters /test def command_test(self, update): @@ -39,7 +42,7 @@ class ExampleCommandHandler(CommandHandlerWithHelp): chat_id = update.message.chat.id reply_to = update.message.message_id message = 'Yeah, the server is online!' - self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to) + self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to) # creates /parrot command def command_parrot(self, update): @@ -50,7 +53,7 @@ class ExampleCommandHandler(CommandHandlerWithHelp): message = update.message.text[len(send[0]):] if len(send) == 1: message = '...' - self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to) + self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to) # creates /p command def command_p(self, update): @@ -67,7 +70,7 @@ class ExampleCommandHandler(CommandHandlerWithHelp): chat_id = update.message.chat.id reply_to = update.message.message_id message = 'Yeah, this is another test' - self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to) + self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to) class Exampe2CommandHandler(CommandHandler): @@ -79,11 +82,15 @@ class Exampe2CommandHandler(CommandHandler): chat_id = update.message.chat.id reply_to = update.message.message_id message = 'Yeah, the server is online!' - self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to) + self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to) if __name__ == '__main__': - import telegram - token = '' # use your own token here + import telegram as telegram + try: + from mytoken import token + except: + token = '' # use your own token here + print ('token = ', token) Bot = telegram.Bot(token=token) test_command_handler = ExampleCommandHandler(Bot) test_command_handler.run() diff --git a/telegram/__init__.py b/telegram/__init__.py index 834b4675f..a84e6cd11 100644 --- a/telegram/__init__.py +++ b/telegram/__init__.py @@ -45,10 +45,12 @@ from .emoji import Emoji from .message import Message from .update import Update from .bot import Bot +from .command_handler import * __all__ = ['Bot', 'Emoji', 'TelegramError', 'InputFile', 'ReplyMarkup', 'ForceReply', 'ReplyKeyboardHide', 'ReplyKeyboardMarkup', 'UserProfilePhotos', 'ChatAction', 'Location', 'Contact', 'Video', 'Sticker', 'Document', 'Audio', 'PhotoSize', 'GroupChat', 'Update', 'Message', 'User', 'TelegramObject', 'NullHandler', - 'Voice'] + 'Voice','CommandHandler', 'CommandHandlerWithHelp', + 'CommandHandlerWithFatherCommand', 'CommandHandlerWithHelpAndFather'] diff --git a/telegram/command_handler.py b/telegram/command_handler.py index 86de9f9d9..16dd08177 100644 --- a/telegram/command_handler.py +++ b/telegram/command_handler.py @@ -4,7 +4,7 @@ import logging import telegram import time logger = logging.getLogger(__name__) -__all__ = ['CommandHandler', 'CommandHandlerWithHelp'] +__all__ = ['CommandHandler', 'CommandHandlerWithHelp', 'CommandHandlerWithFatherCommand', 'CommandHandlerWithHelpAndFather'] class CommandHandler(object): """ This handles incomming commands and gives an easy way to create commands. @@ -38,6 +38,7 @@ class CommandHandler(object): The timeout on a thread. If a thread is alive after this period then try to join the thread in the next loop. """ + old_threads = [] while True: time.sleep(sleep) @@ -82,7 +83,9 @@ class CommandHandler(object): if username == bot_name: command_func = self._get_command_func(command) if command_func is not None: - self.bot.sendChatAction(update.message.chat.id,telegram.ChatAction.TYPING) + print (update.message.chat.id) + print (type(update.message.chat.id)) + self.bot.sendChatAction(chat_id=update.message.chat.id, action=telegram.ChatAction.TYPING) if self.isValidCommand is None or self.isValidCommand(update): if make_thread: t = threading.Thread(target=command_func, args=(update,)) @@ -108,7 +111,7 @@ class CommandHandler(object): chat_id = update.message.chat.id reply_to = update.message.message_id message = "Sorry, the command was not authorised or valid: {command}.".format(command=update.message.text.split(' ')[0]) - self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to) + self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to) def _command_not_found(self, update): """Inform the telegram user that the command was not found. @@ -119,7 +122,7 @@ class CommandHandler(object): chat_id = update.message.chat.id reply_to = update.message.message_id message = "Sorry, I didn't understand the command: {command}.".format(command=update.message.text.split(' ')[0]) - self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to) + self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to) class CommandHandlerWithHelp(CommandHandler): @@ -132,6 +135,7 @@ class CommandHandlerWithHelp(CommandHandler): self._help_list_title = 'These are the commands:' # the title of the list self.is_reply = True self.command_start = self.command_help + self.skip_in_help = [] def _generate_help(self): """ Generate a string which can be send as a help file. @@ -141,17 +145,23 @@ class CommandHandlerWithHelp(CommandHandler): command to the telegram user. """ - command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_'] + help_message = self._help_title + '\n\n' help_message += self._help_before_list + '\n\n' help_message += self._help_list_title + '\n' + help_message += self._generate_help_list() + help_message += '\n' + help_message += self._help_after_list + return help_message + + def _generate_help_list(self): + command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_' and attr[0] not in self.skip_in_help] + help_message = '' for command_function in command_functions: if command_function.__doc__ is not None: help_message += ' /' + command_function.__name__[8:] + ' - ' + command_function.__doc__ + '\n' else: help_message += ' /' + command_function.__name__[8:] + ' - ' + '\n' - help_message += '\n' - help_message += self._help_after_list return help_message def _command_not_found(self, update): @@ -160,15 +170,42 @@ class CommandHandlerWithHelp(CommandHandler): reply_to = update.message.message_id message = 'Sorry, I did not understand the command: {command}. Please see /help for all available commands' if self.is_reply: - self.bot.sendMessage(chat_id, message.format(command=update.message.text.split(' ')[0]), + self.bot.sendMessage(chat_id=chat_id, text=message.format(command=update.message.text.split(' ')[0]), reply_to_message_id=reply_to) else: - self.bot.sendMessage(chat_id, message.format(command=update.message.text.split(' ')[0])) + self.bot.sendMessage(chat_id=chat_id, text=message.format(command=update.message.text.split(' ')[0])) def command_help(self, update): """ The help file. """ chat_id = update.message.chat.id reply_to = update.message.message_id message = self._generate_help() - self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to) + self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to) + +class CommandHandlerWithFatherCommand(CommandHandler): + """ A class that creates some commands that are usefull when setting up the bot + """ + def __init__(self, bot): + super(CommandHandlerWithFatherCommand, self).__init__(bot) + self.skip_in_help = ['command_father'] + + def command_father(self, update): + chat_id = update.message.chat.id + self.bot.sendMessage(chat_id=chat_id, text='Send the following messages to telegram.me/BotFather') + self.bot.sendMessage(chat_id=chat_id, text='/setcommands') + self.bot.sendMessage(chat_id=chat_id, text='@' + self.bot.getMe()['username']) + commands = '' + command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_' and attr[0] not in self.skip_in_help] + + for command_function in command_functions: + if command_function.__doc__ is not None: + commands += command_function.__name__[8:] + ' - ' + command_function.__doc__ + '\n' + else: + commands += command_function.__name__[8:] + ' - ' + '\n' + self.bot.sendMessage(chat_id=chat_id, text=commands) + +class CommandHandlerWithHelpAndFather(CommandHandlerWithFatherCommand, CommandHandlerWithHelp): + """A class that combines CommandHandlerWithHelp and CommandHandlerWithFatherCommand. + """ + pass From ea5c690e7ae245cfa42e31daa51bce1ed46d327a Mon Sep 17 00:00:00 2001 From: mattijn Date: Mon, 7 Sep 2015 03:38:07 +0200 Subject: [PATCH 2/6] add a help for extra commands. --- telegram/command_handler.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/telegram/command_handler.py b/telegram/command_handler.py index 16dd08177..bc15b1ae0 100644 --- a/telegram/command_handler.py +++ b/telegram/command_handler.py @@ -133,9 +133,22 @@ class CommandHandlerWithHelp(CommandHandler): self._help_before_list = '' # text with information about the bot self._help_after_list = '' # a footer self._help_list_title = 'These are the commands:' # the title of the list + self._help_extra_message = 'These commands are only usefull to the developer.' self.is_reply = True self.command_start = self.command_help self.skip_in_help = [] + + def command_helpextra(self,update): + """ The commands in here are only usefull to the developer of the bot""" + command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_' and attr[0] in self.skip_in_help] + chat_id = update.message.chat.id + help_message = self._help_extra_message +'\n' + for command_function in command_functions: + if command_function.__doc__ is not None: + help_message += ' /' + command_function.__name__[8:] + ' - ' + command_function.__doc__ + '\n' + else: + help_message += ' /' + command_function.__name__[8:] + ' - ' + '\n' + self.bot.sendMessage(chat_id=chat_id,text=help_message) def _generate_help(self): """ Generate a string which can be send as a help file. From 5b8f41b3c1bf7a047b5200931f0af1c6df6dd705 Mon Sep 17 00:00:00 2001 From: mattijn Date: Mon, 7 Sep 2015 04:17:43 +0200 Subject: [PATCH 3/6] pep 8 command_handler.py --- telegram/command_handler.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/telegram/command_handler.py b/telegram/command_handler.py index bc15b1ae0..7ee8a974e 100644 --- a/telegram/command_handler.py +++ b/telegram/command_handler.py @@ -133,22 +133,23 @@ class CommandHandlerWithHelp(CommandHandler): self._help_before_list = '' # text with information about the bot self._help_after_list = '' # a footer self._help_list_title = 'These are the commands:' # the title of the list - self._help_extra_message = 'These commands are only usefull to the developer.' + self._help_extra_message = 'These commands are only usefull to the developer.' self.is_reply = True self.command_start = self.command_help self.skip_in_help = [] def command_helpextra(self,update): """ The commands in here are only usefull to the developer of the bot""" - command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_' and attr[0] in self.skip_in_help] + command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_' and + attr[0] in self.skip_in_help] chat_id = update.message.chat.id - help_message = self._help_extra_message +'\n' + help_message = self._help_extra_message + '\n' for command_function in command_functions: if command_function.__doc__ is not None: help_message += ' /' + command_function.__name__[8:] + ' - ' + command_function.__doc__ + '\n' else: help_message += ' /' + command_function.__name__[8:] + ' - ' + '\n' - self.bot.sendMessage(chat_id=chat_id,text=help_message) + self.bot.sendMessage(chat_id=chat_id, text=help_message) def _generate_help(self): """ Generate a string which can be send as a help file. @@ -158,7 +159,6 @@ class CommandHandlerWithHelp(CommandHandler): command to the telegram user. """ - help_message = self._help_title + '\n\n' help_message += self._help_before_list + '\n\n' help_message += self._help_list_title + '\n' @@ -168,7 +168,8 @@ class CommandHandlerWithHelp(CommandHandler): return help_message def _generate_help_list(self): - command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_' and attr[0] not in self.skip_in_help] + command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_' and + attr[0] not in self.skip_in_help] help_message = '' for command_function in command_functions: if command_function.__doc__ is not None: @@ -204,20 +205,23 @@ class CommandHandlerWithFatherCommand(CommandHandler): self.skip_in_help = ['command_father'] def command_father(self, update): + """Gives you the commands you need to setup this bot. in telegram.me/BotFather""" chat_id = update.message.chat.id self.bot.sendMessage(chat_id=chat_id, text='Send the following messages to telegram.me/BotFather') self.bot.sendMessage(chat_id=chat_id, text='/setcommands') self.bot.sendMessage(chat_id=chat_id, text='@' + self.bot.getMe()['username']) commands = '' - command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_' and attr[0] not in self.skip_in_help] + command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_' and + attr[0] not in self.skip_in_help] for command_function in command_functions: if command_function.__doc__ is not None: - commands += command_function.__name__[8:] + ' - ' + command_function.__doc__ + '\n' + commands += command_function.__name__[8:] + ' - ' + command_function.__doc__ + '\n' else: - commands += command_function.__name__[8:] + ' - ' + '\n' + commands += command_function.__name__[8:] + ' - ' + '\n' self.bot.sendMessage(chat_id=chat_id, text=commands) + class CommandHandlerWithHelpAndFather(CommandHandlerWithFatherCommand, CommandHandlerWithHelp): """A class that combines CommandHandlerWithHelp and CommandHandlerWithFatherCommand. """ From 69aa1c252bced9931e374cf6bd8b955abc387f4f Mon Sep 17 00:00:00 2001 From: mattijn Date: Mon, 7 Sep 2015 04:55:00 +0200 Subject: [PATCH 4/6] added an easier way to get frequent commands from message. --- telegram/message.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/telegram/message.py b/telegram/message.py index 1caf61dc7..e77f3ea4b 100644 --- a/telegram/message.py +++ b/telegram/message.py @@ -171,6 +171,12 @@ class Message(TelegramObject): return Message(**data) + def __getitem__(self, item): + if item in self.__dict__.keys(): + return self.__dict__[item] + elif item == 'chat_id': + return self.chat.id + def to_dict(self): """ Returns: From 89bab207b64e17f014cd8adafc1f3d021fe9852e Mon Sep 17 00:00:00 2001 From: mattijn Date: Mon, 7 Sep 2015 05:11:08 +0200 Subject: [PATCH 5/6] pep8 --- telegram/command_handler.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/telegram/command_handler.py b/telegram/command_handler.py index 7ee8a974e..fe4eb204f 100644 --- a/telegram/command_handler.py +++ b/telegram/command_handler.py @@ -4,7 +4,10 @@ import logging import telegram import time logger = logging.getLogger(__name__) -__all__ = ['CommandHandler', 'CommandHandlerWithHelp', 'CommandHandlerWithFatherCommand', 'CommandHandlerWithHelpAndFather'] +__all__ = ['CommandHandler', 'CommandHandlerWithHelp', 'CommandHandlerWithFatherCommand', + 'CommandHandlerWithHelpAndFather'] + + class CommandHandler(object): """ This handles incomming commands and gives an easy way to create commands. @@ -15,7 +18,8 @@ class CommandHandler(object): """ def __init__(self, bot): self.bot = bot # a telegram bot - 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. + self.isValidCommand = None # a function that returns a boolean and takes one agrument an update. + # If False is returned the the command is not executed. def _get_command_func(self, command): if command[0] == '/': @@ -83,8 +87,6 @@ class CommandHandler(object): if username == bot_name: command_func = self._get_command_func(command) if command_func is not None: - print (update.message.chat.id) - print (type(update.message.chat.id)) self.bot.sendChatAction(chat_id=update.message.chat.id, action=telegram.ChatAction.TYPING) if self.isValidCommand is None or self.isValidCommand(update): if make_thread: @@ -110,7 +112,8 @@ class CommandHandler(object): """ chat_id = update.message.chat.id reply_to = update.message.message_id - message = "Sorry, the command was not authorised or valid: {command}.".format(command=update.message.text.split(' ')[0]) + message = "Sorry, the command was not authorised or valid: {command}.".format( + command=update.message.text.split(' ')[0]) self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to) def _command_not_found(self, update): From 6ffcdcf2fea1e39e65c7e7bd905a4ed8e7d2305d Mon Sep 17 00:00:00 2001 From: mattijn Date: Mon, 7 Sep 2015 05:13:08 +0200 Subject: [PATCH 6/6] removed unused imports --- examples/command_handler_example.py | 9 --------- 1 file changed, 9 deletions(-) diff --git a/examples/command_handler_example.py b/examples/command_handler_example.py index 37bbd4986..f3e70ab21 100644 --- a/examples/command_handler_example.py +++ b/examples/command_handler_example.py @@ -1,12 +1,3 @@ -# There could be some unused imports -import sys -sys.path.append('..') -sys.path.append('.') -from inspect import getmembers, ismethod -import threading -import logging -import telegram -import time from telegram import CommandHandlerWithHelpAndFather, CommandHandler class ExampleCommandHandler(CommandHandlerWithHelpAndFather): """This is an example how to use a CommandHandlerWithHelp or just a CommandHandler.