-
Notifications
You must be signed in to change notification settings - Fork 5.9k
Customize context #2262
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
Customize context #2262
Changes from all commits
Commits
Show all changes
40 commits
Select commit
Hold shift + click to select a range
d2e768d
Document CC constructors
Bibo-Joshi 4f8014f
Add custom_context parameter and try to sort out annotations
Bibo-Joshi 680ef7a
Add tests
Bibo-Joshi e1eb585
POC for customizing *_data
Bibo-Joshi 7de4a33
merge master
Bibo-Joshi 9189994
Get typing to work to reasonable accuracy
Bibo-Joshi 254fe2d
Improve type hints some more
Bibo-Joshi f24cdff
Test Dispatcher integration
Bibo-Joshi c221944
Pass CC to PP
Bibo-Joshi 932b86e
Merge branch 'master' into customize-context
Bibo-Joshi 6eed0ea
Fix tests
Bibo-Joshi c93eb28
Add tests for PicklePersistence
Bibo-Joshi c72559f
Increase coverage
Bibo-Joshi a058cf4
Merge branch 'master' into customize-context
Bibo-Joshi 1ff8503
Start refactoring to introduce BasePersistence.refresh_*_data
Bibo-Joshi 524ce0d
Fix existing tests
Bibo-Joshi a0a65dc
Add new tests
Bibo-Joshi 86f3a13
Update docs & add some versioning directives
Bibo-Joshi ab99075
Merge branch 'master' into customize-context
Bibo-Joshi 5dc7e18
Annotation fix
Bibo-Joshi 39d1e78
Only specify major version of GH Actions
Bibo-Joshi 6753bcf
Slight typing improvements
Bibo-Joshi b20cd09
Address review
Bibo-Joshi e184443
More review
Bibo-Joshi ce4738c
Shame on me
Bibo-Joshi 39a9f83
Drop double copying from persistence & adjust tests
Bibo-Joshi 700878d
Merge branch 'master' into customize-context
Bibo-Joshi c16a647
Add example to examples directory
Bibo-Joshi cb17b85
Deepsource
Bibo-Joshi e4a05d9
review
Bibo-Joshi 45eae20
Make BP.refresh_* methods non-breaking
Bibo-Joshi 5779f8e
Merge branch 'master' into customize-context
Bibo-Joshi 86bec4a
Merge branch 'master' into customize-context
Bibo-Joshi ae7b6e5
Fix slots for Updater on py3.6
Bibo-Joshi 2ca7f17
Fix slot tests
Bibo-Joshi 7e6e39e
Merge branch 'slot-fixes' into customize-context
Bibo-Joshi 5f5b4f0
Merge branch 'master' into customize-context
Bibo-Joshi 23c4577
More slot fixes 🥳
Bibo-Joshi 871f334
Try fixing pre-commit
Bibo-Joshi d6b04ea
Some more versioning directives
Bibo-Joshi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| :github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/ext/contexttypes.py | ||
|
|
||
| telegram.ext.ContextTypes | ||
| ========================= | ||
|
|
||
| .. autoclass:: telegram.ext.ContextTypes | ||
| :members: | ||
| :show-inheritance: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| :github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/ext/utils/types.py | ||
|
|
||
| telegram.ext.utils.types Module | ||
| ================================ | ||
|
|
||
| .. automodule:: telegram.ext.utils.types | ||
| :members: | ||
| :show-inheritance: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| #!/usr/bin/env python | ||
| # pylint: disable=C0116,W0613 | ||
| # This program is dedicated to the public domain under the CC0 license. | ||
|
|
||
| """ | ||
| Simple Bot to showcase `telegram.ext.ContextTypes`. | ||
|
|
||
| Usage: | ||
| Press Ctrl-C on the command line or send a signal to the process to stop the | ||
| bot. | ||
| """ | ||
|
|
||
| from collections import defaultdict | ||
| from typing import DefaultDict, Optional, Set | ||
|
|
||
| from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, ParseMode | ||
| from telegram.ext import ( | ||
| Updater, | ||
| CommandHandler, | ||
| CallbackContext, | ||
| ContextTypes, | ||
| CallbackQueryHandler, | ||
| TypeHandler, | ||
| Dispatcher, | ||
| ) | ||
|
|
||
|
|
||
| class ChatData: | ||
| """Custom class for chat_data. Here we store data per message.""" | ||
|
|
||
| def __init__(self) -> None: | ||
| self.clicks_per_message: DefaultDict[int, int] = defaultdict(int) | ||
|
|
||
|
|
||
| # The [dict, ChatData, dict] is for type checkers like mypy | ||
| class CustomContext(CallbackContext[dict, ChatData, dict]): | ||
| """Custom class for context.""" | ||
|
|
||
| def __init__(self, dispatcher: Dispatcher): | ||
| super().__init__(dispatcher=dispatcher) | ||
| self._message_id: Optional[int] = None | ||
|
|
||
| @property | ||
| def bot_user_ids(self) -> Set[int]: | ||
| """Custom shortcut to access a value stored in the bot_data dict""" | ||
| return self.bot_data.setdefault('user_ids', set()) | ||
|
|
||
| @property | ||
| def message_clicks(self) -> Optional[int]: | ||
| """Access the number of clicks for the message this context object was built for.""" | ||
| if self._message_id: | ||
| return self.chat_data.clicks_per_message[self._message_id] | ||
| return None | ||
|
|
||
| @message_clicks.setter | ||
| def message_clicks(self, value: int) -> None: | ||
| """Allow to change the count""" | ||
| if not self._message_id: | ||
| raise RuntimeError('There is no message associated with this context obejct.') | ||
| self.chat_data.clicks_per_message[self._message_id] = value | ||
|
|
||
| @classmethod | ||
| def from_update(cls, update: object, dispatcher: 'Dispatcher') -> 'CustomContext': | ||
| """Override from_update to set _message_id.""" | ||
| # Make sure to call super() | ||
| context = super().from_update(update, dispatcher) | ||
|
|
||
| if context.chat_data and isinstance(update, Update) and update.effective_message: | ||
| context._message_id = update.effective_message.message_id # pylint: disable=W0212 | ||
|
|
||
| # Remember to return the object | ||
| return context | ||
|
|
||
|
|
||
| def start(update: Update, context: CustomContext) -> None: | ||
| """Display a message with a button.""" | ||
| update.message.reply_html( | ||
| 'This button was clicked <i>0</i> times.', | ||
Bibo-Joshi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| reply_markup=InlineKeyboardMarkup.from_button( | ||
| InlineKeyboardButton(text='Click me!', callback_data='button') | ||
| ), | ||
| ) | ||
|
|
||
|
|
||
| def count_click(update: Update, context: CustomContext) -> None: | ||
| """Update the click count for the message.""" | ||
| context.message_clicks += 1 | ||
| update.callback_query.answer() | ||
| update.effective_message.edit_text( | ||
| f'This button was clicked <i>{context.message_clicks}</i> times.', | ||
| reply_markup=InlineKeyboardMarkup.from_button( | ||
| InlineKeyboardButton(text='Click me!', callback_data='button') | ||
| ), | ||
| parse_mode=ParseMode.HTML, | ||
| ) | ||
|
|
||
|
|
||
| def print_users(update: Update, context: CustomContext) -> None: | ||
| """Show which users have been using this bot.""" | ||
| update.message.reply_text( | ||
| 'The following user IDs have used this bot: ' | ||
| f'{", ".join(map(str, context.bot_user_ids))}' | ||
| ) | ||
|
|
||
|
|
||
| def track_users(update: Update, context: CustomContext) -> None: | ||
| """Store the user id of the incoming update, if any.""" | ||
| if update.effective_user: | ||
| context.bot_user_ids.add(update.effective_user.id) | ||
|
|
||
|
|
||
| def main() -> None: | ||
| """Run the bot.""" | ||
| context_types = ContextTypes(context=CustomContext, chat_data=ChatData) | ||
| updater = Updater("TOKEN", context_types=context_types) | ||
|
|
||
| dispatcher = updater.dispatcher | ||
| # run track_users in its own group to not interfere with the user handlers | ||
| dispatcher.add_handler(TypeHandler(Update, track_users), group=-1) | ||
| dispatcher.add_handler(CommandHandler("start", start)) | ||
| dispatcher.add_handler(CallbackQueryHandler(count_click)) | ||
| dispatcher.add_handler(CommandHandler("print_users", print_users)) | ||
|
|
||
| updater.start_polling() | ||
| updater.idle() | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -44,6 +44,7 @@ omit = | |
| [coverage:report] | ||
| exclude_lines = | ||
| if TYPE_CHECKING: | ||
| ... | ||
|
|
||
| [mypy] | ||
| warn_unused_ignores = True | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.