diff --git a/.gitignore b/.gitignore index a43e5f473..e72837bb9 100644 --- a/.gitignore +++ b/.gitignore @@ -58,3 +58,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..f3e70ab21 100644 --- a/examples/command_handler_example.py +++ b/examples/command_handler_example.py @@ -1,11 +1,5 @@ -# There could be some unused imports -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 +25,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 +33,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 +44,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 +61,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 +73,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..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'] +__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] == '/': @@ -38,6 +42,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 +87,7 @@ 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) + 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,)) @@ -107,8 +112,9 @@ 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) + 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): """Inform the telegram user that the command was not found. @@ -119,7 +125,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): @@ -130,8 +136,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.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. @@ -141,17 +162,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 +187,45 @@ 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): + """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] + + 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 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: