diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 04081c87c05..c5e6cfcb31c 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -20,9 +20,7 @@ Setting things up 4. Install dependencies: - ``$ pip install -r requirements.txt`` - - ``$ pip install -r requirements-dev.txt`` + ``$ pip install -r requirements.txt -r requirements-dev.txt`` Finding something to do ----------------------- @@ -56,6 +54,8 @@ Here's how to make a one-off code change. - You can refer to relevant issues in the commit message by writing, e.g., "#105". + - Your code should adhere to the `PEP 8 Style Guide`_, with the exception that we have a maximum line length of 99. + - For consistency, please conform to `Google Python Style Guide`_ and `Google Python Style Docstrings`_. In addition, code should be formatted consistently with other code around it. - The following exceptions to the above (Google's) style guides applies: @@ -116,7 +116,7 @@ Here's how to make a one-off code change. - At the end, the reviewer will merge the pull request. -6. **Tidy up!** Delete the feature branch from your both your local clone and the GitHub repository: +6. **Tidy up!** Delete the feature branch from both your local clone and the GitHub repository: ``$ git branch -D your-branch-name`` @@ -127,6 +127,7 @@ Here's how to make a one-off code change. .. _`Code of Conduct`: https://www.python.org/psf/codeofconduct/ .. _`issue tracker`: https://github.com/python-telegram-bot/python-telegram-bot/issues .. _`developers' mailing list`: mailto:devs@python-telegram-bot.org +.. _`PEP 8 Style Guide`: https://www.python.org/dev/peps/pep-0008/ .. _`Google Python Style Guide`: https://google-styleguide.googlecode.com/svn/trunk/pyguide.html .. _`Google Python Style Docstrings`: http://sphinx-doc.org/latest/ext/example_google.html .. _AUTHORS.rst: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/AUTHORS.rst diff --git a/README.rst b/README.rst index 0c8a548a499..a5715f421bc 100644 --- a/README.rst +++ b/README.rst @@ -201,7 +201,7 @@ _`API` Note: Using the ``Bot`` class directly is the 'old' method, we have an easier way to make bots described in the next section. All of this is however still important information, even if you're using the ``telegram.ext`` submodule! -The API is exposed via the ``telegram.Bot`` class. +The API is exposed via the ``telegram.Bot`` class. The methods have names as described in the official `Telegram Bot API `_, but equivalent snake_case methods are available for `PEP8 `_ enthusiasts. So for example `telegram.Bot.send_message` is the same as `telegram.Bot.sendMessage`. To generate an Access Token you have to talk to `BotFather `_ and follow a few simple steps (described `here `_). @@ -355,7 +355,7 @@ We want this function to be called on a Telegram message that contains the ``/st >>> from telegram.ext import CommandHandler >>> start_handler = CommandHandler('start', start) - >>> dispatcher.addHandler(start_handler) + >>> dispatcher.add_handler(start_handler) The last step is to tell the ``Updater`` to start working: @@ -372,7 +372,7 @@ Our bot is now up and running (go ahead and try it)! It's not doing anything yet ... >>> from telegram.ext import MessageHandler, Filters >>> echo_handler = MessageHandler([Filters.text], echo) - >>> dispatcher.addHandler(echo_handler) + >>> dispatcher.add_handler(echo_handler) Our bot should now reply to all text messages that are not a command with a message that has the same content. @@ -385,7 +385,7 @@ Let's add some functionality to our bot. We want to add the ``/caps`` command, t ... bot.sendMessage(chat_id=update.message.chat_id, text=text_caps) ... >>> caps_handler = CommandHandler('caps', caps, pass_args=True) - >>> dispatcher.addHandler(caps_handler) + >>> dispatcher.add_handler(caps_handler) To enable our bot to respond to inline queries, we can add the following (you will also have to talk to BotFather): @@ -400,7 +400,7 @@ To enable our bot to respond to inline queries, we can add the following (you wi ... >>> from telegram.ext import InlineQueryHandler >>> inline_caps_handler = InlineQueryHandler(inline_caps) - >>> dispatcher.addHandler(inline_caps_handler) + >>> dispatcher.add_handler(inline_caps_handler) People might try to send commands to the bot that it doesn't understand, so we can use a ``RegexHandler`` to recognize all commands that were not recognized by the previous handlers. **Note:** This handler has to be added last, else it will be triggered before the ``CommandHandlers`` had a chance to look at the update: @@ -411,7 +411,7 @@ People might try to send commands to the bot that it doesn't understand, so we c ... >>> from telegram.ext import RegexHandler >>> unknown_handler = RegexHandler(r'/.*', unknown) - >>> dispatcher.addHandler(unknown_handler) + >>> dispatcher.add_handler(unknown_handler) If you're done playing around, stop the bot with this: diff --git a/examples/clibot.py b/examples/clibot.py index 03c2696fec3..ee53f9a772c 100644 --- a/examples/clibot.py +++ b/examples/clibot.py @@ -24,6 +24,8 @@ from time import sleep import logging +from future.builtins import input + # Enable Logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', @@ -112,24 +114,24 @@ def main(): dp = updater.dispatcher # This is how we add handlers for Telegram messages - dp.addHandler(CommandHandler("start", start)) - dp.addHandler(CommandHandler("help", help)) + dp.add_handler(CommandHandler("start", start)) + dp.add_handler(CommandHandler("help", help)) # Message handlers only receive updates that don't contain commands - dp.addHandler(MessageHandler([Filters.text], message)) + dp.add_handler(MessageHandler([Filters.text], message)) # Regex handlers will receive all updates on which their regex matches, # but we have to add it in a separate group, since in one group, # only one handler will be executed - dp.addHandler(RegexHandler('.*', any_message), group=1) + dp.add_handler(RegexHandler('.*', any_message), group=1) # String handlers work pretty much the same. Note that we have to tell # the handler to pass the args or update_queue parameter - dp.addHandler(StringCommandHandler('reply', cli_reply, pass_args=True)) - dp.addHandler(StringRegexHandler('[^/].*', cli_noncommand, - pass_update_queue=True)) + dp.add_handler(StringCommandHandler('reply', cli_reply, pass_args=True)) + dp.add_handler(StringRegexHandler('[^/].*', cli_noncommand, + pass_update_queue=True)) # All TelegramErrors are caught for you and delivered to the error # handler(s). Other types of Errors are not caught. - dp.addErrorHandler(error) + dp.add_error_handler(error) # Start the Bot and store the update Queue, so we can insert updates update_queue = updater.start_polling(timeout=10) @@ -153,10 +155,7 @@ def main(): # Start CLI-Loop while True: - try: - text = raw_input() - except NameError: - text = input() + text = input() # Gracefully stop the event handler if text == 'stop': diff --git a/examples/echobot2.py b/examples/echobot2.py index 4833b9bb170..3fd9d47052e 100644 --- a/examples/echobot2.py +++ b/examples/echobot2.py @@ -54,14 +54,14 @@ def main(): dp = updater.dispatcher # on different commands - answer in Telegram - dp.addHandler(CommandHandler("start", start)) - dp.addHandler(CommandHandler("help", help)) + dp.add_handler(CommandHandler("start", start)) + dp.add_handler(CommandHandler("help", help)) # on noncommand i.e message - echo the message on Telegram - dp.addHandler(MessageHandler([Filters.text], echo)) + dp.add_handler(MessageHandler([Filters.text], echo)) # log all errors - dp.addErrorHandler(error) + dp.add_error_handler(error) # Start the Bot updater.start_polling() diff --git a/examples/inlinebot.py b/examples/inlinebot.py index f9243543d67..ffa62f90a44 100644 --- a/examples/inlinebot.py +++ b/examples/inlinebot.py @@ -87,14 +87,14 @@ def main(): dp = updater.dispatcher # on different commands - answer in Telegram - dp.addHandler(CommandHandler("start", start)) - dp.addHandler(CommandHandler("help", help)) + dp.add_handler(CommandHandler("start", start)) + dp.add_handler(CommandHandler("help", help)) # on noncommand i.e message - echo the message on Telegram - dp.addHandler(InlineQueryHandler(inlinequery)) + dp.add_handler(InlineQueryHandler(inlinequery)) # log all errors - dp.addErrorHandler(error) + dp.add_error_handler(error) # Start the Bot updater.start_polling() diff --git a/examples/inlinekeyboard_example.py b/examples/inlinekeyboard_example.py index d17eca9004a..ed85ba12722 100644 --- a/examples/inlinekeyboard_example.py +++ b/examples/inlinekeyboard_example.py @@ -105,12 +105,12 @@ def error(bot, update, error): # The command updater.dispatcher.addHandler(CommandHandler('set', set_value)) # The answer -updater.dispatcher.addHandler(MessageHandler([Filters.text], entered_value)) +updater.dispatcher.add_handler(MessageHandler([Filters.text], entered_value)) # The confirmation -updater.dispatcher.addHandler(CallbackQueryHandler(confirm_value)) -updater.dispatcher.addHandler(CommandHandler('start', help)) -updater.dispatcher.addHandler(CommandHandler('help', help)) -updater.dispatcher.addErrorHandler(error) +updater.dispatcher.add_handler(CallbackQueryHandler(confirm_value)) +updater.dispatcher.add_handler(CommandHandler('start', help)) +updater.dispatcher.add_handler(CommandHandler('help', help)) +updater.dispatcher.add_error_handler(error) # Start the Bot updater.start_polling() diff --git a/examples/state_machine_bot.py b/examples/state_machine_bot.py index 2017a7f18a0..f40361aae97 100644 --- a/examples/state_machine_bot.py +++ b/examples/state_machine_bot.py @@ -91,12 +91,12 @@ def help(bot, update): updater = Updater("TOKEN") # The command -updater.dispatcher.addHandler(CommandHandler('set', set_value)) +updater.dispatcher.add_handler(CommandHandler('set', set_value)) # The answer and confirmation -updater.dispatcher.addHandler(MessageHandler([Filters.text], set_value)) -updater.dispatcher.addHandler(CommandHandler('cancel', cancel)) -updater.dispatcher.addHandler(CommandHandler('start', help)) -updater.dispatcher.addHandler(CommandHandler('help', help)) +updater.dispatcher.add_handler(MessageHandler([Filters.text], set_value)) +updater.dispatcher.add_handler(CommandHandler('cancel', cancel)) +updater.dispatcher.add_handler(CommandHandler('start', help)) +updater.dispatcher.add_handler(CommandHandler('help', help)) # Start the Bot updater.start_polling() diff --git a/examples/timerbot.py b/examples/timerbot.py index 6b2efc59be5..00ec65403b7 100644 --- a/examples/timerbot.py +++ b/examples/timerbot.py @@ -73,12 +73,12 @@ def main(): dp = updater.dispatcher # on different commands - answer in Telegram - dp.addHandler(CommandHandler("start", start)) - dp.addHandler(CommandHandler("help", start)) - dp.addHandler(CommandHandler("set", set, pass_args=True)) + dp.add_handler(CommandHandler("start", start)) + dp.add_handler(CommandHandler("help", start)) + dp.add_handler(CommandHandler("set", set, pass_args=True)) # log all errors - dp.addErrorHandler(error) + dp.add_error_handler(error) # Start the Bot updater.start_polling() diff --git a/setup.cfg b/setup.cfg index 83200fc3a8d..2b23f9015ba 100644 --- a/setup.cfg +++ b/setup.cfg @@ -10,4 +10,4 @@ all_files = 1 upload-dir = docs/build/html [flake8] -max-line-length = 99 \ No newline at end of file +max-line-length = 99 diff --git a/telegram/__init__.py b/telegram/__init__.py index 393b5a0afea..4311406060e 100644 --- a/telegram/__init__.py +++ b/telegram/__init__.py @@ -19,6 +19,8 @@ """A library that provides a Python interface to the Telegram Bot API""" +from sys import version_info + from .base import TelegramObject from .user import User from .chat import Chat @@ -142,3 +144,9 @@ 'Venue', 'Video', 'Voice'] + + +if version_info < (2, 7): + from warnings import warn + warn("python-telegram-bot will stop supporting Python 2.6 in a future release. " + "Please upgrade your Python!") diff --git a/telegram/bot.py b/telegram/bot.py index f9b710de439..4f2b2e2388f 100644 --- a/telegram/bot.py +++ b/telegram/bot.py @@ -1384,3 +1384,29 @@ def __reduce__(self): return (self.__class__, (self.token, self.base_url.replace(self.token, ''), self.base_file_url.replace(self.token, ''))) + + # snake_case (PEP8) aliases + get_me = getMe + send_message = sendMessage + forward_message = forwardMessage + send_photo = sendPhoto + send_audio = sendAudio + send_document = sendDocument + send_sticker = sendSticker + send_video = sendVideo + send_voice = sendVoice + send_location = sendLocation + send_venue = sendVenue + send_contact = sendContact + send_chat_action = sendChatAction + answer_inline_query = answerInlineQuery + get_user_profile_photos = getUserProfilePhotos + get_file = getFile + kick_chat_member = kickChatMember + unban_chat_member = unbanChatMember + answer_callback_query = answerCallbackQuery + edit_message_text = editMessageText + edit_message_caption = editMessageCaption + edit_message_reply_markup = editMessageReplyMarkup + get_updates = getUpdates + set_webhook = setWebhook diff --git a/telegram/ext/callbackqueryhandler.py b/telegram/ext/callbackqueryhandler.py index 7d0e6e87ab5..da749a58446 100644 --- a/telegram/ext/callbackqueryhandler.py +++ b/telegram/ext/callbackqueryhandler.py @@ -21,6 +21,7 @@ from .handler import Handler from telegram import Update +from telegram.utils.deprecate import deprecate class CallbackQueryHandler(Handler): @@ -29,7 +30,7 @@ class CallbackQueryHandler(Handler): Args: callback (function): A function that takes ``bot, update`` as - positional arguments. It will be called when the ``checkUpdate`` + positional arguments. It will be called when the ``check_update`` has determined that an update should be processed by this handler. pass_update_queue (optional[bool]): If the handler should be passed the update queue as a keyword argument called ``update_queue``. It can @@ -39,10 +40,15 @@ class CallbackQueryHandler(Handler): def __init__(self, callback, pass_update_queue=False): super(CallbackQueryHandler, self).__init__(callback, pass_update_queue) - def checkUpdate(self, update): + def check_update(self, update): return isinstance(update, Update) and update.callback_query - def handleUpdate(self, update, dispatcher): - optional_args = self.collectOptionalArgs(dispatcher) + def handle_update(self, update, dispatcher): + optional_args = self.collect_optional_args(dispatcher) self.callback(dispatcher.bot, update, **optional_args) + + # old non-PEP8 Handler methods + m = "telegram.CallbackQueryHandler." + checkUpdate = deprecate(check_update, m + "checkUpdate", m + "check_update") + handleUpdate = deprecate(handle_update, m + "handleUpdate", m + "handle_update") diff --git a/telegram/ext/choseninlineresulthandler.py b/telegram/ext/choseninlineresulthandler.py index bd7757ec03d..000c4ab3691 100644 --- a/telegram/ext/choseninlineresulthandler.py +++ b/telegram/ext/choseninlineresulthandler.py @@ -21,6 +21,7 @@ from .handler import Handler from telegram import Update +from telegram.utils.deprecate import deprecate class ChosenInlineResultHandler(Handler): @@ -30,7 +31,7 @@ class ChosenInlineResultHandler(Handler): Args: callback (function): A function that takes ``bot, update`` as - positional arguments. It will be called when the ``checkUpdate`` + positional arguments. It will be called when the ``check_update`` has determined that an update should be processed by this handler. pass_update_queue (optional[bool]): If the handler should be passed the update queue as a keyword argument called ``update_queue``. It can @@ -41,10 +42,15 @@ def __init__(self, callback, pass_update_queue=False): super(ChosenInlineResultHandler, self).__init__(callback, pass_update_queue) - def checkUpdate(self, update): + def check_update(self, update): return isinstance(update, Update) and update.chosen_inline_result - def handleUpdate(self, update, dispatcher): - optional_args = self.collectOptionalArgs(dispatcher) + def handle_update(self, update, dispatcher): + optional_args = self.collect_optional_args(dispatcher) self.callback(dispatcher.bot, update, **optional_args) + + # old non-PEP8 Handler methods + m = "telegram.ChosenInlineResultHandler." + checkUpdate = deprecate(check_update, m + "checkUpdate", m + "check_update") + handleUpdate = deprecate(handle_update, m + "handleUpdate", m + "handle_update") diff --git a/telegram/ext/commandhandler.py b/telegram/ext/commandhandler.py index c140626aa36..5e427e1245c 100644 --- a/telegram/ext/commandhandler.py +++ b/telegram/ext/commandhandler.py @@ -21,6 +21,7 @@ from .handler import Handler from telegram import Update +from telegram.utils.deprecate import deprecate class CommandHandler(Handler): @@ -32,7 +33,7 @@ class CommandHandler(Handler): Args: command (str): The name of the command this handler should listen for. callback (function): A function that takes ``bot, update`` as - positional arguments. It will be called when the ``checkUpdate`` + positional arguments. It will be called when the ``check_update`` has determined that an update should be processed by this handler. pass_args (optional[bool]): If the handler should be passed the arguments passed to the command as a keyword argument called ` @@ -49,7 +50,7 @@ def __init__(self, command, callback, pass_args=False, self.command = command self.pass_args = pass_args - def checkUpdate(self, update): + def check_update(self, update): return (isinstance(update, Update) and update.message and update.message.text and @@ -57,10 +58,15 @@ def checkUpdate(self, update): update.message.text[1:].split(' ')[0].split('@')[0] == self.command) - def handleUpdate(self, update, dispatcher): - optional_args = self.collectOptionalArgs(dispatcher) + def handle_update(self, update, dispatcher): + optional_args = self.collect_optional_args(dispatcher) if self.pass_args: optional_args['args'] = update.message.text.split(' ')[1:] self.callback(dispatcher.bot, update, **optional_args) + + # old non-PEP8 Handler methods + m = "telegram.CommandHandler." + checkUpdate = deprecate(check_update, m + "checkUpdate", m + "check_update") + handleUpdate = deprecate(handle_update, m + "handleUpdate", m + "handle_update") diff --git a/telegram/ext/dispatcher.py b/telegram/ext/dispatcher.py index 351fe278d63..386972262f5 100644 --- a/telegram/ext/dispatcher.py +++ b/telegram/ext/dispatcher.py @@ -28,6 +28,7 @@ from telegram import (TelegramError, NullHandler) from telegram.ext.handler import Handler +from telegram.utils.deprecate import deprecate logging.getLogger(__name__).addHandler(NullHandler()) @@ -201,7 +202,7 @@ def processUpdate(self, update): 'processing the update') break - def addHandler(self, handler, group=DEFAULT_GROUP): + def add_handler(self, handler, group=DEFAULT_GROUP): """ Register a handler. @@ -239,7 +240,7 @@ def addHandler(self, handler, group=DEFAULT_GROUP): self.handlers[group].append(handler) - def removeHandler(self, handler, group=DEFAULT_GROUP): + def remove_handler(self, handler, group=DEFAULT_GROUP): """ Remove a handler from the specified group @@ -253,7 +254,7 @@ def removeHandler(self, handler, group=DEFAULT_GROUP): del self.handlers[group] self.groups.remove(group) - def addErrorHandler(self, callback): + def add_error_handler(self, callback): """ Registers an error handler in the Dispatcher. @@ -264,7 +265,7 @@ def addErrorHandler(self, callback): self.error_handlers.append(callback) - def removeErrorHandler(self, callback): + def remove_error_handler(self, callback): """ De-registers an error handler. @@ -286,3 +287,11 @@ def dispatchError(self, update, error): for callback in self.error_handlers: callback(self.bot, update, error) + + # old non-PEP8 Dispatcher methods + m = "telegram.dispatcher." + addHandler = deprecate(add_handler, m + "AddHandler", m + "add_handler") + removeHandler = deprecate(remove_handler, m + "removeHandler", m + "remove_handler") + addErrorHandler = deprecate(add_error_handler, m + "addErrorHandler", m + "add_error_handler") + removeErrorHandler = deprecate(remove_error_handler, + m + "removeErrorHandler", m + "remove_error_handler") diff --git a/telegram/ext/handler.py b/telegram/ext/handler.py index a2f6dead22c..fd93b5f42c0 100644 --- a/telegram/ext/handler.py +++ b/telegram/ext/handler.py @@ -20,6 +20,8 @@ """ This module contains the base class for handlers as used by the Dispatcher """ +from telegram.utils.deprecate import deprecate + class Handler(object): """ @@ -28,7 +30,7 @@ class Handler(object): Args: callback (function): A function that takes ``bot, update`` as - positional arguments. It will be called when the ``checkUpdate`` + positional arguments. It will be called when the ``check_update`` has determined that an update should be processed by this handler. pass_update_queue (optional[bool]): If the callback should be passed the update queue as a keyword argument called ``update_queue``. It @@ -39,7 +41,7 @@ def __init__(self, callback, pass_update_queue=False): self.callback = callback self.pass_update_queue = pass_update_queue - def checkUpdate(self, update): + def check_update(self, update): """ This method is called to determine if an update should be handled by this handler instance. It should always be overridden. @@ -52,7 +54,7 @@ def checkUpdate(self, update): """ raise NotImplementedError - def handleUpdate(self, update, dispatcher): + def handle_update(self, update, dispatcher): """ This method is called if it was determined that an update should indeed be handled by this instance. It should also be overridden, but in most @@ -65,7 +67,7 @@ def handleUpdate(self, update, dispatcher): """ raise NotImplementedError - def collectOptionalArgs(self, dispatcher): + def collect_optional_args(self, dispatcher): """ Prepares the optional arguments that are the same for all types of handlers @@ -78,3 +80,10 @@ def collectOptionalArgs(self, dispatcher): optional_args['update_queue'] = dispatcher.update_queue return optional_args + + # old non-PEP8 Handler methods + m = "telegram.Handler." + checkUpdate = deprecate(check_update, m + "checkUpdate", m + "check_update") + handleUpdate = deprecate(handle_update, m + "handleUpdate", m + "handle_update") + collectOptionalArgs = deprecate(collect_optional_args, + m + "collectOptionalArgs", m + "collect_optional_args") diff --git a/telegram/ext/inlinequeryhandler.py b/telegram/ext/inlinequeryhandler.py index 56a7823d9f7..6f0f6e26a0b 100644 --- a/telegram/ext/inlinequeryhandler.py +++ b/telegram/ext/inlinequeryhandler.py @@ -21,6 +21,7 @@ from .handler import Handler from telegram import Update +from telegram.utils.deprecate import deprecate class InlineQueryHandler(Handler): @@ -29,7 +30,7 @@ class InlineQueryHandler(Handler): Args: callback (function): A function that takes ``bot, update`` as - positional arguments. It will be called when the ``checkUpdate`` + positional arguments. It will be called when the ``check_update`` has determined that an update should be processed by this handler. pass_update_queue (optional[bool]): If the handler should be passed the update queue as a keyword argument called ``update_queue``. It can @@ -39,10 +40,15 @@ class InlineQueryHandler(Handler): def __init__(self, callback, pass_update_queue=False): super(InlineQueryHandler, self).__init__(callback, pass_update_queue) - def checkUpdate(self, update): + def check_update(self, update): return isinstance(update, Update) and update.inline_query - def handleUpdate(self, update, dispatcher): - optional_args = self.collectOptionalArgs(dispatcher) + def handle_update(self, update, dispatcher): + optional_args = self.collect_optional_args(dispatcher) self.callback(dispatcher.bot, update, **optional_args) + + # old non-PEP8 Handler methods + m = "telegram.InlineQueryHandler." + checkUpdate = deprecate(check_update, m + "checkUpdate", m + "check_update") + handleUpdate = deprecate(handle_update, m + "handleUpdate", m + "handle_update") diff --git a/telegram/ext/messagehandler.py b/telegram/ext/messagehandler.py index 135a08f071c..0da942b6355 100644 --- a/telegram/ext/messagehandler.py +++ b/telegram/ext/messagehandler.py @@ -21,6 +21,7 @@ from .handler import Handler from telegram import Update +from telegram.utils.deprecate import deprecate class Filters(object): @@ -103,7 +104,7 @@ class MessageHandler(Handler): accepted. If ``bool(filters)`` evaluates to ``False``, messages are not filtered. callback (function): A function that takes ``bot, update`` as - positional arguments. It will be called when the ``checkUpdate`` + positional arguments. It will be called when the ``check_update`` has determined that an update should be processed by this handler. pass_update_queue (optional[bool]): If the handler should be passed the update queue as a keyword argument called ``update_queue``. It can @@ -114,7 +115,7 @@ def __init__(self, filters, callback, pass_update_queue=False): super(MessageHandler, self).__init__(callback, pass_update_queue) self.filters = filters - def checkUpdate(self, update): + def check_update(self, update): if isinstance(update, Update) and update.message: if not self.filters: res = True @@ -124,7 +125,12 @@ def checkUpdate(self, update): res = False return res - def handleUpdate(self, update, dispatcher): - optional_args = self.collectOptionalArgs(dispatcher) + def handle_update(self, update, dispatcher): + optional_args = self.collect_optional_args(dispatcher) self.callback(dispatcher.bot, update, **optional_args) + + # old non-PEP8 Handler methods + m = "telegram.MessageHandler." + checkUpdate = deprecate(check_update, m + "checkUpdate", m + "check_update") + handleUpdate = deprecate(handle_update, m + "handleUpdate", m + "handle_update") diff --git a/telegram/ext/regexhandler.py b/telegram/ext/regexhandler.py index c3a7f976b4a..0f82ddf8bc1 100644 --- a/telegram/ext/regexhandler.py +++ b/telegram/ext/regexhandler.py @@ -25,6 +25,7 @@ from .handler import Handler from telegram import Update +from telegram.utils.deprecate import deprecate class RegexHandler(Handler): @@ -37,7 +38,7 @@ class RegexHandler(Handler): Args: pattern (str or Pattern): The regex pattern. callback (function): A function that takes ``bot, update`` as - positional arguments. It will be called when the ``checkUpdate`` + positional arguments. It will be called when the ``check_update`` has determined that an update should be processed by this handler. pass_groups (optional[bool]): If the callback should be passed the result of ``re.match(pattern, text).groups()`` as a keyword @@ -61,7 +62,7 @@ def __init__(self, pattern, callback, pass_groups=False, self.pass_groups = pass_groups self.pass_groupdict = pass_groupdict - def checkUpdate(self, update): + def check_update(self, update): if (isinstance(update, Update) and update.message and update.message.text): @@ -70,8 +71,8 @@ def checkUpdate(self, update): else: return False - def handleUpdate(self, update, dispatcher): - optional_args = self.collectOptionalArgs(dispatcher) + def handle_update(self, update, dispatcher): + optional_args = self.collect_optional_args(dispatcher) match = re.match(self.pattern, update.message.text) if self.pass_groups: @@ -80,3 +81,8 @@ def handleUpdate(self, update, dispatcher): optional_args['groupdict'] = match.groupdict() self.callback(dispatcher.bot, update, **optional_args) + + # old non-PEP8 Handler methods + m = "telegram.RegexHandler." + checkUpdate = deprecate(check_update, m + "checkUpdate", m + "check_update") + handleUpdate = deprecate(handle_update, m + "handleUpdate", m + "handle_update") diff --git a/telegram/ext/stringcommandhandler.py b/telegram/ext/stringcommandhandler.py index b9df4375ea9..c9d5f46a527 100644 --- a/telegram/ext/stringcommandhandler.py +++ b/telegram/ext/stringcommandhandler.py @@ -20,6 +20,7 @@ """ This module contains the StringCommandHandler class """ from .handler import Handler +from telegram.utils.deprecate import deprecate class StringCommandHandler(Handler): @@ -30,7 +31,7 @@ class StringCommandHandler(Handler): Args: command (str): The name of the command this handler should listen for. callback (function): A function that takes ``bot, update`` as - positional arguments. It will be called when the ``checkUpdate`` + positional arguments. It will be called when the ``check_update`` has determined that an update should be processed by this handler. pass_args (optional[bool]): If the handler should be passed the arguments passed to the command as a keyword argument called ` @@ -47,15 +48,20 @@ def __init__(self, command, callback, pass_args=False, self.command = command self.pass_args = pass_args - def checkUpdate(self, update): + def check_update(self, update): return (isinstance(update, str) and update.startswith('/') and update[1:].split(' ')[0] == self.command) - def handleUpdate(self, update, dispatcher): - optional_args = self.collectOptionalArgs(dispatcher) + def handle_update(self, update, dispatcher): + optional_args = self.collect_optional_args(dispatcher) if self.pass_args: optional_args['args'] = update.split(' ')[1:] self.callback(dispatcher.bot, update, **optional_args) + + # old non-PEP8 Handler methods + m = "telegram.StringCommandHandler." + checkUpdate = deprecate(check_update, m + "checkUpdate", m + "check_update") + handleUpdate = deprecate(handle_update, m + "handleUpdate", m + "handle_update") diff --git a/telegram/ext/stringregexhandler.py b/telegram/ext/stringregexhandler.py index 6ea748fd22a..020ba09532f 100644 --- a/telegram/ext/stringregexhandler.py +++ b/telegram/ext/stringregexhandler.py @@ -24,6 +24,7 @@ from future.utils import string_types from .handler import Handler +from telegram.utils.deprecate import deprecate class StringRegexHandler(Handler): @@ -36,7 +37,7 @@ class StringRegexHandler(Handler): Args: pattern (str or Pattern): The regex pattern. callback (function): A function that takes ``bot, update`` as - positional arguments. It will be called when the ``checkUpdate`` + positional arguments. It will be called when the ``check_update`` has determined that an update should be processed by this handler. pass_groups (optional[bool]): If the callback should be passed the result of ``re.match(pattern, update).groups()`` as a keyword @@ -60,12 +61,12 @@ def __init__(self, pattern, callback, pass_groups=False, self.pass_groups = pass_groups self.pass_groupdict = pass_groupdict - def checkUpdate(self, update): + def check_update(self, update): return isinstance(update, string_types) and bool( re.match(self.pattern, update)) - def handleUpdate(self, update, dispatcher): - optional_args = self.collectOptionalArgs(dispatcher) + def handle_update(self, update, dispatcher): + optional_args = self.collect_optional_args(dispatcher) match = re.match(self.pattern, update) if self.pass_groups: @@ -74,3 +75,8 @@ def handleUpdate(self, update, dispatcher): optional_args['groupdict'] = match.groupdict() self.callback(dispatcher.bot, update, **optional_args) + + # old non-PEP8 Handler methods + m = "telegram.StringRegexHandler." + checkUpdate = deprecate(check_update, m + "checkUpdate", m + "check_update") + handleUpdate = deprecate(handle_update, m + "handleUpdate", m + "handle_update") diff --git a/telegram/ext/typehandler.py b/telegram/ext/typehandler.py index b81a878348e..d72b5bf2427 100644 --- a/telegram/ext/typehandler.py +++ b/telegram/ext/typehandler.py @@ -20,6 +20,7 @@ """ This module contains the TypeHandler class """ from .handler import Handler +from telegram.utils.deprecate import deprecate class TypeHandler(Handler): @@ -30,7 +31,7 @@ class TypeHandler(Handler): type (type): The ``type`` of updates this handler should process, as determined by ``isinstance`` callback (function): A function that takes ``bot, update`` as - positional arguments. It will be called when the ``checkUpdate`` + positional arguments. It will be called when the ``check_update`` has determined that an update should be processed by this handler. strict (optional[bool]): Use ``type`` instead of ``isinstance``. Default is ``False`` @@ -44,13 +45,18 @@ def __init__(self, type, callback, strict=False, pass_update_queue=False): self.type = type self.strict = strict - def checkUpdate(self, update): + def check_update(self, update): if not self.strict: return isinstance(update, self.type) else: return type(update) is self.type - def handleUpdate(self, update, dispatcher): - optional_args = self.collectOptionalArgs(dispatcher) + def handle_update(self, update, dispatcher): + optional_args = self.collect_optional_args(dispatcher) self.callback(dispatcher.bot, update, **optional_args) + + # old non-PEP8 Handler methods + m = "telegram.TypeHandler." + checkUpdate = deprecate(check_update, m + "checkUpdate", m + "check_update") + handleUpdate = deprecate(handle_update, m + "handleUpdate", m + "handle_update") diff --git a/telegram/utils/deprecate.py b/telegram/utils/deprecate.py new file mode 100644 index 00000000000..3036f177c78 --- /dev/null +++ b/telegram/utils/deprecate.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python +# +# A library that provides a Python interface to the Telegram Bot API +# Copyright (C) 2015-2016 +# Leandro Toledo de Souza +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser Public License for more details. +# +# You should have received a copy of the GNU Lesser Public License +# along with this program. If not, see [http://www.gnu.org/licenses/]. + +"""This module facilitates the deprecation of functions""" + +import warnings + + +def deprecate(func, old, new): + """Warn users invoking old to switch to the new function.""" + def f(*args, **kwargs): + warnings.warn("{0} is being deprecated, please use {1} from now on".format(old, new)) + return func(*args, **kwargs) + return f