Skip to content

Commit

Permalink
Revert "Revert "Context based callbacks (#1100)""
Browse files Browse the repository at this point in the history
This reverts commit f8a17cd
  • Loading branch information
jsmnbom committed Sep 21, 2018
1 parent 4397903 commit cf95027
Show file tree
Hide file tree
Showing 45 changed files with 1,407 additions and 633 deletions.
19 changes: 19 additions & 0 deletions CHANGES.rst
Expand Up @@ -2,6 +2,25 @@
Changes
=======

**2018-??-??**
*Released 11.0.0*

Context based callbacks:
See https://git.io/vp113 for help.

- Use of `pass_` in handlers is deprecated.
- Instead use `use_context=True` on `Updater` or `Dispatcher` and change callback from (bot, update, others...) to (update, context).
- This also applies to error handlers `Dispatcher.add_error_handler` and JobQueue jobs (change (bot, job) to (context) here).
- For users with custom handlers subclassing Handler, this is mostly backwards compatible, but to use the new context based callbacks you need to implement the new collect_additional_context method.
- Passing bot to JobQueue.__init__ is deprecated. Use JobQueue.set_dispatcher with a dispatcher instead.

Other:
- Handlers should be faster due to deduped logic.

Other removals:
- Remove the ability to use filter lists in handlers.
- Remove the last CamelCase CheckUpdate methods from the handlers we missed earlier.

**2018-09-01**
*Released 11.1.0*

Expand Down
5 changes: 5 additions & 0 deletions docs/source/telegram.ext.callbackcontext.rst
@@ -0,0 +1,5 @@
telegram.ext.CallbackContext
============================

.. autoclass:: telegram.ext.CallbackContext
:members:
1 change: 1 addition & 0 deletions docs/source/telegram.ext.rst
Expand Up @@ -10,6 +10,7 @@ telegram.ext package
telegram.ext.jobqueue
telegram.ext.messagequeue
telegram.ext.delayqueue
telegram.ext.callbackcontext

Handlers
--------
Expand Down
32 changes: 17 additions & 15 deletions examples/conversationbot.py
Expand Up @@ -17,12 +17,12 @@
bot.
"""

import logging

from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
ConversationHandler)

import logging

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
Expand All @@ -32,7 +32,7 @@
GENDER, PHOTO, LOCATION, BIO = range(4)


def start(bot, update):
def start(update, context):
reply_keyboard = [['Boy', 'Girl', 'Other']]

update.message.reply_text(
Expand All @@ -44,7 +44,7 @@ def start(bot, update):
return GENDER


def gender(bot, update):
def gender(update, context):
user = update.message.from_user
logger.info("Gender of %s: %s", user.first_name, update.message.text)
update.message.reply_text('I see! Please send me a photo of yourself, '
Expand All @@ -54,9 +54,9 @@ def gender(bot, update):
return PHOTO


def photo(bot, update):
def photo(update, context):
user = update.message.from_user
photo_file = bot.get_file(update.message.photo[-1].file_id)
photo_file = update.message.photo[-1].get_file()
photo_file.download('user_photo.jpg')
logger.info("Photo of %s: %s", user.first_name, 'user_photo.jpg')
update.message.reply_text('Gorgeous! Now, send me your location please, '
Expand All @@ -65,7 +65,7 @@ def photo(bot, update):
return LOCATION


def skip_photo(bot, update):
def skip_photo(update, context):
user = update.message.from_user
logger.info("User %s did not send a photo.", user.first_name)
update.message.reply_text('I bet you look great! Now, send me your location please, '
Expand All @@ -74,7 +74,7 @@ def skip_photo(bot, update):
return LOCATION


def location(bot, update):
def location(update, context):
user = update.message.from_user
user_location = update.message.location
logger.info("Location of %s: %f / %f", user.first_name, user_location.latitude,
Expand All @@ -85,7 +85,7 @@ def location(bot, update):
return BIO


def skip_location(bot, update):
def skip_location(update, context):
user = update.message.from_user
logger.info("User %s did not send a location.", user.first_name)
update.message.reply_text('You seem a bit paranoid! '
Expand All @@ -94,15 +94,15 @@ def skip_location(bot, update):
return BIO


def bio(bot, update):
def bio(update, context):
user = update.message.from_user
logger.info("Bio of %s: %s", user.first_name, update.message.text)
update.message.reply_text('Thank you! I hope we can talk again some day.')

return ConversationHandler.END


def cancel(bot, update):
def cancel(update, context):
user = update.message.from_user
logger.info("User %s canceled the conversation.", user.first_name)
update.message.reply_text('Bye! I hope we can talk again some day.',
Expand All @@ -111,14 +111,16 @@ def cancel(bot, update):
return ConversationHandler.END


def error(bot, update, error):
def error(update, context):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
logger.warning('Update "%s" caused error "%s"', update, context.error)


def main():
# Create the EventHandler and pass it your bot's token.
updater = Updater("TOKEN")
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)

# Get the dispatcher to register handlers
dp = updater.dispatcher
Expand Down
24 changes: 14 additions & 10 deletions examples/conversationbot2.py
Expand Up @@ -17,12 +17,12 @@
bot.
"""

import logging

from telegram import ReplyKeyboardMarkup
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
ConversationHandler)

import logging

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
Expand All @@ -46,7 +46,7 @@ def facts_to_str(user_data):
return "\n".join(facts).join(['\n', '\n'])


def start(bot, update):
def start(update, context):
update.message.reply_text(
"Hi! My name is Doctor Botter. I will hold a more complex conversation with you. "
"Why don't you tell me something about yourself?",
Expand All @@ -55,23 +55,24 @@ def start(bot, update):
return CHOOSING


def regular_choice(bot, update, user_data):
def regular_choice(update, context):
text = update.message.text
user_data['choice'] = text
context.user_data['choice'] = text
update.message.reply_text(
'Your {}? Yes, I would love to hear about that!'.format(text.lower()))

return TYPING_REPLY


def custom_choice(bot, update):
def custom_choice(update, context):
update.message.reply_text('Alright, please send me the category first, '
'for example "Most impressive skill"')

return TYPING_CHOICE


def received_information(bot, update, user_data):
def received_information(update, context):
user_data = context.user_data
text = update.message.text
category = user_data['choice']
user_data[category] = text
Expand All @@ -85,7 +86,8 @@ def received_information(bot, update, user_data):
return CHOOSING


def done(bot, update, user_data):
def done(update, context):
user_data = context.user_data
if 'choice' in user_data:
del user_data['choice']

Expand All @@ -97,14 +99,16 @@ def done(bot, update, user_data):
return ConversationHandler.END


def error(bot, update, error):
def error(update, context):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)


def main():
# Create the Updater and pass it your bot's token.
updater = Updater("TOKEN")
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)

# Get the dispatcher to register handlers
dp = updater.dispatcher
Expand Down
19 changes: 11 additions & 8 deletions examples/echobot2.py
Expand Up @@ -17,9 +17,10 @@
bot.
"""

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
Expand All @@ -29,30 +30,32 @@

# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
def start(update, context):
"""Send a message when the command /start is issued."""
update.message.reply_text('Hi!')


def help(bot, update):
def help(update, context):
"""Send a message when the command /help is issued."""
update.message.reply_text('Help!')


def echo(bot, update):
def echo(update, context):
"""Echo the user message."""
update.message.reply_text(update.message.text)


def error(bot, update, error):
def error(update, context):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
logger.warning('Update "%s" caused error "%s"', update, context.error)


def main():
"""Start the bot."""
# Create the EventHandler and pass it your bot's token.
updater = Updater("TOKEN")
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)

# Get the dispatcher to register handlers
dp = updater.dispatcher
Expand Down
19 changes: 10 additions & 9 deletions examples/inlinebot.py
Expand Up @@ -16,14 +16,13 @@
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
import logging
from uuid import uuid4

from telegram.utils.helpers import escape_markdown

from telegram import InlineQueryResultArticle, ParseMode, \
InputTextMessageContent
from telegram.ext import Updater, InlineQueryHandler, CommandHandler
import logging
from telegram.utils.helpers import escape_markdown

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
Expand All @@ -34,17 +33,17 @@

# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
def start(update, context):
"""Send a message when the command /start is issued."""
update.message.reply_text('Hi!')


def help(bot, update):
def help(update, context):
"""Send a message when the command /help is issued."""
update.message.reply_text('Help!')


def inlinequery(bot, update):
def inlinequery(update, context):
"""Handle the inline query."""
query = update.inline_query.query
results = [
Expand All @@ -69,14 +68,16 @@ def inlinequery(bot, update):
update.inline_query.answer(results)


def error(bot, update, error):
def error(update, context):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
logger.warning('Update "%s" caused error "%s"', update, context.error)


def main():
# Create the Updater and pass it your bot's token.
updater = Updater("TOKEN")
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)

# Get the dispatcher to register handlers
dp = updater.dispatcher
Expand Down
19 changes: 10 additions & 9 deletions examples/inlinekeyboard.py
Expand Up @@ -5,6 +5,7 @@
# This program is dedicated to the public domain under the CC0 license.
"""
import logging

from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler

Expand All @@ -13,7 +14,7 @@
logger = logging.getLogger(__name__)


def start(bot, update):
def start(update, context):
keyboard = [[InlineKeyboardButton("Option 1", callback_data='1'),
InlineKeyboardButton("Option 2", callback_data='2')],

Expand All @@ -24,26 +25,26 @@ def start(bot, update):
update.message.reply_text('Please choose:', reply_markup=reply_markup)


def button(bot, update):
def button(update, context):
query = update.callback_query

bot.edit_message_text(text="Selected option: {}".format(query.data),
chat_id=query.message.chat_id,
message_id=query.message.message_id)
query.edit_message_text(text="Selected option: {}".format(query.data))


def help(bot, update):
def help(update, context):
update.message.reply_text("Use /start to test this bot.")


def error(bot, update, error):
def error(update, context):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
logger.warning('Update "%s" caused error "%s"', update, context.error)


def main():
# Create the Updater and pass it your bot's token.
updater = Updater("TOKEN")
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)

updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CallbackQueryHandler(button))
Expand Down

0 comments on commit cf95027

Please sign in to comment.