Skip to content

Context #1100

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 33 commits into from
May 21, 2018
Merged

Context #1100

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
3ce9363
Change handlers so context is supported
jsmnbom May 3, 2018
714d96d
Attempt to make parameter "guessing" work on py < 3.5
jsmnbom May 3, 2018
32a2453
Document use_context in all handlers
jsmnbom May 3, 2018
5738f00
Add Context to docs
jsmnbom May 3, 2018
0580ae3
Minor fixes to context handling
jsmnbom May 3, 2018
bad8f35
Add tests for context stuff
jsmnbom May 3, 2018
7e2fb8d
Allow the signature check to work on py<3.5 with methods
jsmnbom May 3, 2018
d133dd4
Fix order of operations
jsmnbom May 3, 2018
5bfaca0
Address most issues raised in CR
jsmnbom May 4, 2018
bfec5ea
Make CommandHandler no longer support filter lists
jsmnbom May 5, 2018
da26227
Fix indent
jsmnbom May 5, 2018
c450a4e
Improve readability in conversationhandler
jsmnbom May 5, 2018
35c07dd
Make context have Match instead of groups & groupdict
jsmnbom May 5, 2018
b325cc1
Remove filter list support from messagehandler too
jsmnbom May 5, 2018
945a5ec
Small fix to StringCommandHandler
jsmnbom May 5, 2018
07747f3
More small fixes to handlers
jsmnbom May 5, 2018
a54cfac
Amend CHANGES
jsmnbom May 5, 2018
30712c5
Fix tests and fix bugs raised by tests
jsmnbom May 5, 2018
e87a705
Don't allow users to ignore errors without messing with the warning f…
jsmnbom May 5, 2018
c69378f
Merge branch 'master' into context
jsmnbom May 5, 2018
397ab77
Ignore our own deprecation warnings when testing
jsmnbom May 5, 2018
46f2a26
Skipping deprecationwarning test on py2
Eldinnie May 7, 2018
fe27912
Forgot some changes
Eldinnie May 7, 2018
0f44eed
Handler: Improved documentation and text of deprecation warnings
tsnoam May 7, 2018
b54f7e5
HandlerContext: Keep only dispatcher and use properties; improved doc
tsnoam May 7, 2018
f26bf62
Complete fixing the documentation.
tsnoam May 7, 2018
8184902
Some small doc fixes (interlinks and optionals)
Eldinnie May 8, 2018
5dc53a5
Change add_error_handler to use HandlerContext too
jsmnbom May 10, 2018
eeb2816
More context based changes
jsmnbom May 10, 2018
256a9d1
Forgot about conversationhandler
jsmnbom May 10, 2018
63f8a07
Forgot jobqueue
jsmnbom May 10, 2018
1fb2e6e
Add tests for callbackcontext & for context based callback job
jsmnbom May 11, 2018
9c4dc3c
Fix as per review :)
jsmnbom May 15, 2018
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,26 @@
=======
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-05-02**
*Released 10.1.0*

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

.. autoclass:: telegram.ext.CallbackContext
:members:
1 change: 1 addition & 0 deletions docs/source/telegram.ext.rst
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy