Skip to content

Builder pattern for ext #2646

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 87 commits into from
Oct 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
87 commits
Select commit Hold shift + click to select a range
c3774c6
Temporarily enable tests for the v14 branch
Bibo-Joshi Jul 14, 2021
d9b48cc
Move and Rename TelegramDecryptionError to telegram.error.PassportDec…
harshil21 Aug 11, 2021
b37f9d2
Add Code Comment Guidelines to Contribution Guide (#2612)
Poolitzer Aug 11, 2021
d696412
Improve Type Hinting for CallbackContext (#2587)
revolter Aug 12, 2021
2ed8869
Add Custom pytest Marker to Ease Development (#2628)
Poolitzer Aug 12, 2021
be00397
Make BasePersistence Methods Abstract (#2624)
starry-shivam Aug 12, 2021
f284061
Refactor Initialization of Persistence Classes (#2604)
Bibo-Joshi Aug 13, 2021
43b02fb
First rough start
Bibo-Joshi Aug 15, 2021
fd1e5f9
Continue working - type hinting is messy :/
Bibo-Joshi Aug 15, 2021
844364b
Work on type hints
Bibo-Joshi Aug 16, 2021
735085a
Some pre-commit stuff
Bibo-Joshi Aug 17, 2021
e5eed68
get started on Dispatcher/UpdaterBuilder
Bibo-Joshi Aug 17, 2021
68dee51
docs for DispatcherUpdater
Bibo-Joshi Aug 19, 2021
96100f6
docs for UpdaterBuilder
Bibo-Joshi Aug 22, 2021
55398f3
Bump pre-commit again
Bibo-Joshi Aug 22, 2021
b65c1c3
Remove `__dict__` from `__slots__` and drop Python 3.6 (#2619, #2636)
harshil21 Aug 19, 2021
209642b
Remove day_is_strict argument of JobQueue.run_monthly (#2634)
iota-008 Aug 26, 2021
e4cfda2
Get started on tests
Bibo-Joshi Aug 26, 2021
cfb8d44
More tests for builders
Bibo-Joshi Aug 27, 2021
a32851a
Drop Non-CallbackContext API (#2617)
Poolitzer Aug 29, 2021
48698ea
Fix Signatures and Improve test_official (#2643)
harshil21 Aug 29, 2021
eae1eca
Update examples
Bibo-Joshi Aug 29, 2021
ed1d501
Start updating tests
Bibo-Joshi Aug 29, 2021
9b00727
Merge branch 'v14' into builder-pattern-for-ext
Bibo-Joshi Aug 29, 2021
a5340e3
Remove Deprecated Functionality (#2644)
Bibo-Joshi Aug 30, 2021
d6b18ef
Fix a few more tests
Bibo-Joshi Aug 30, 2021
28f837c
Merge branch 'v14' into builder-pattern-for-ext
Bibo-Joshi Aug 30, 2021
62683e2
Do some stuff
Bibo-Joshi Aug 30, 2021
d794209
more test fixes
Bibo-Joshi Aug 31, 2021
a5197af
Try fixing pre-commit and DS
Bibo-Joshi Aug 31, 2021
a964531
Add some tests
Bibo-Joshi Sep 1, 2021
133c6a4
Fix something
Bibo-Joshi Sep 1, 2021
8679d16
Use new type alias in examples
Bibo-Joshi Sep 1, 2021
8777b36
Make Updater/Dispatcher.exception_event public & documented
Bibo-Joshi Sep 1, 2021
eb1f0a9
Remove debug prints
Bibo-Joshi Sep 3, 2021
bdb713c
Add support for custom Updater/Dispatcher subclasses
Bibo-Joshi Sep 4, 2021
5240655
Drop Non-CallbackContext API (#2617)
Poolitzer Aug 29, 2021
76e4875
Fix Signatures and Improve test_official (#2643)
harshil21 Aug 29, 2021
930a615
Remove Deprecated Functionality (#2644)
Bibo-Joshi Aug 30, 2021
15b274a
Merge branch 'v14' into builder-pattern-for-ext
Bibo-Joshi Sep 4, 2021
4eb49dd
Add Updater/Dispatcher.builder & some more docs
Bibo-Joshi Sep 5, 2021
63e1bab
Temporarily enable tests for the v14 branch
Bibo-Joshi Jul 14, 2021
4598eea
Move and Rename TelegramDecryptionError to telegram.error.PassportDec…
harshil21 Aug 11, 2021
d7366fc
Add Code Comment Guidelines to Contribution Guide (#2612)
Poolitzer Aug 11, 2021
5b3983d
Improve Type Hinting for CallbackContext (#2587)
revolter Aug 12, 2021
df2e48f
Add Custom pytest Marker to Ease Development (#2628)
Poolitzer Aug 12, 2021
e72ca06
Make BasePersistence Methods Abstract (#2624)
starry-shivam Aug 12, 2021
60f6c38
Refactor Initialization of Persistence Classes (#2604)
Bibo-Joshi Aug 13, 2021
fe60272
Remove `__dict__` from `__slots__` and drop Python 3.6 (#2619, #2636)
harshil21 Aug 19, 2021
df81477
Remove day_is_strict argument of JobQueue.run_monthly (#2634)
iota-008 Aug 26, 2021
f857f06
Drop Non-CallbackContext API (#2617)
Poolitzer Aug 29, 2021
a717db8
Fix Signatures and Improve test_official (#2643)
harshil21 Aug 29, 2021
12fe042
Remove Deprecated Functionality (#2644)
Bibo-Joshi Aug 30, 2021
663b81c
Merge branch 'v14' into builder-pattern-for-ext
Bibo-Joshi Sep 9, 2021
82a7b51
Start on addressing review
Bibo-Joshi Sep 12, 2021
9ff22d5
drop `check_if_already_set` and *_was_set
Bibo-Joshi Sep 12, 2021
d451c1c
Merge remote-tracking branch 'origin/builder-pattern-for-ext' into bu…
Bibo-Joshi Sep 12, 2021
62378fd
TRy making codecov happy
Bibo-Joshi Sep 12, 2021
331c4f5
Temporarily enable tests for the v14 branch
Bibo-Joshi Jul 14, 2021
9dc30cf
Move and Rename TelegramDecryptionError to telegram.error.PassportDec…
harshil21 Aug 11, 2021
b089cc9
Add Code Comment Guidelines to Contribution Guide (#2612)
Poolitzer Aug 11, 2021
3a19383
Improve Type Hinting for CallbackContext (#2587)
revolter Aug 12, 2021
414a18c
Add Custom pytest Marker to Ease Development (#2628)
Poolitzer Aug 12, 2021
8edb49d
Make BasePersistence Methods Abstract (#2624)
starry-shivam Aug 12, 2021
cce9c18
Refactor Initialization of Persistence Classes (#2604)
Bibo-Joshi Aug 13, 2021
dc0207a
Remove `__dict__` from `__slots__` and drop Python 3.6 (#2619, #2636)
harshil21 Aug 19, 2021
4af252f
Remove day_is_strict argument of JobQueue.run_monthly (#2634)
iota-008 Aug 26, 2021
b6e4b54
Drop Non-CallbackContext API (#2617)
Poolitzer Aug 29, 2021
4359812
Fix Signatures and Improve test_official (#2643)
harshil21 Aug 29, 2021
dbdd35e
Remove Deprecated Functionality (#2644)
Bibo-Joshi Aug 30, 2021
a7c7c82
Add User Friendly Type Check For Init Of {Inline, Reply}KeyboardMarku…
harshil21 Sep 15, 2021
3026ca7
Merge branch 'v14' into builder-pattern-for-ext
Bibo-Joshi Sep 15, 2021
8ac65fc
Refine Dispatcher.dispatch_error (#2660)
Bibo-Joshi Sep 17, 2021
6e21a3f
Merge branch 'v14' into builder-pattern-for-ext
Bibo-Joshi Sep 17, 2021
f0270bc
Address review
Bibo-Joshi Sep 17, 2021
66f0604
Warnings Overhaul (#2662)
harshil21 Sep 20, 2021
4f21c06
Clear Up Import Policy (#2671)
Bibo-Joshi Sep 22, 2021
7f0ca4d
Merge branch 'v14' into builder-pattern-for-ext
Bibo-Joshi Sep 22, 2021
28dc9c0
Call Request.stop() on shutdown
Bibo-Joshi Sep 22, 2021
2a858f3
Fix tests temporarily
Bibo-Joshi Sep 22, 2021
5542a46
Make InlineQuery.answer Raise ValueError (#2675)
Bibo-Joshi Sep 24, 2021
b216a6a
Merge branch 'v14' into builder-pattern-for-ext
Bibo-Joshi Sep 27, 2021
f88b533
Review
Bibo-Joshi Sep 27, 2021
84cc43f
Merge branch 'v14' into builder-pattern-for-ext
Bibo-Joshi Oct 3, 2021
430d852
Merge branch 'v14' into builder-pattern-for-ext
Bibo-Joshi Oct 5, 2021
5fa9c4c
Merge branch 'v14' into builder-pattern-for-ext
Bibo-Joshi Oct 9, 2021
fd288df
Changes according to #2700
Bibo-Joshi Oct 9, 2021
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
11 changes: 8 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ repos:
hooks:
- id: flake8
- repo: https://github.com/PyCQA/pylint
rev: v2.8.3
rev: v2.10.2
hooks:
- id: pylint
files: ^(telegram|examples)/.*\.py$
Expand All @@ -27,12 +27,17 @@ repos:
- cachetools==4.2.2
- . # this basically does `pip install -e .`
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.812
rev: v0.910
hooks:
- id: mypy
name: mypy-ptb
files: ^telegram/.*\.py$
additional_dependencies:
- types-ujson
- types-pytz
- types-cryptography
- types-certifi
- types-cachetools
- certifi
- tornado>=6.1
- APScheduler==3.6.3
Expand All @@ -51,7 +56,7 @@ repos:
- cachetools==4.2.2
- . # this basically does `pip install -e .`
- repo: https://github.com/asottile/pyupgrade
rev: v2.19.1
rev: v2.24.0
hooks:
- id: pyupgrade
files: ^(telegram|examples|tests)/.*\.py$
Expand Down
7 changes: 7 additions & 0 deletions docs/source/telegram.ext.dispatcherbuilder.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/ext/builders.py

telegram.ext.DispatcherBuilder
==============================

.. autoclass:: telegram.ext.DispatcherBuilder
:members:
3 changes: 3 additions & 0 deletions docs/source/telegram.ext.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ telegram.ext package
.. toctree::

telegram.ext.extbot
telegram.ext.updaterbuilder
telegram.ext.updater
telegram.ext.dispatcherbuilder
telegram.ext.dispatcher
telegram.ext.dispatcherhandlerstop
telegram.ext.callbackcontext
Expand Down Expand Up @@ -60,4 +62,5 @@ utils
.. toctree::

telegram.ext.utils.promise
telegram.ext.utils.stack
telegram.ext.utils.types
7 changes: 7 additions & 0 deletions docs/source/telegram.ext.updaterbuilder.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/ext/builders.py

telegram.ext.UpdaterBuilder
===========================

.. autoclass:: telegram.ext.UpdaterBuilder
:members:
8 changes: 8 additions & 0 deletions docs/source/telegram.ext.utils.stack.rst
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/stack.py

telegram.ext.utils.stack Module
================================

.. automodule:: telegram.ext.utils.stack
:members:
:show-inheritance:
28 changes: 18 additions & 10 deletions examples/arbitrarycallbackdatabot.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,38 +11,40 @@

from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import (
Updater,
CommandHandler,
CallbackQueryHandler,
CallbackContext,
InvalidCallbackData,
PicklePersistence,
Updater,
CallbackContext,
)


# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)


def start(update: Update, context: CallbackContext) -> None:
def start(update: Update, context: CallbackContext.DEFAULT_TYPE) -> None:
"""Sends a message with 5 inline buttons attached."""
number_list: List[int] = []
update.message.reply_text('Please choose:', reply_markup=build_keyboard(number_list))


def help_command(update: Update, context: CallbackContext) -> None:
def help_command(update: Update, context: CallbackContext.DEFAULT_TYPE) -> None:
"""Displays info on how to use the bot."""
update.message.reply_text(
"Use /start to test this bot. Use /clear to clear the stored data so that you can see "
"what happens, if the button data is not available. "
)


def clear(update: Update, context: CallbackContext) -> None:
def clear(update: Update, context: CallbackContext.DEFAULT_TYPE) -> None:
"""Clears the callback data cache"""
context.bot.callback_data_cache.clear_callback_data() # type: ignore[attr-defined]
context.bot.callback_data_cache.clear_callback_queries() # type: ignore[attr-defined]
context.bot.callback_data_cache.clear_callback_data()
context.bot.callback_data_cache.clear_callback_queries()
update.effective_message.reply_text('All clear!')


Expand All @@ -53,7 +55,7 @@ def build_keyboard(current_list: List[int]) -> InlineKeyboardMarkup:
)


def list_button(update: Update, context: CallbackContext) -> None:
def list_button(update: Update, context: CallbackContext.DEFAULT_TYPE) -> None:
"""Parses the CallbackQuery and updates the message text."""
query = update.callback_query
query.answer()
Expand All @@ -73,7 +75,7 @@ def list_button(update: Update, context: CallbackContext) -> None:
context.drop_callback_data(query)


def handle_invalid_button(update: Update, context: CallbackContext) -> None:
def handle_invalid_button(update: Update, context: CallbackContext.DEFAULT_TYPE) -> None:
"""Informs the user that the button is no longer available."""
update.callback_query.answer()
update.effective_message.edit_text(
Expand All @@ -86,7 +88,13 @@ def main() -> None:
# We use persistence to demonstrate how buttons can still work after the bot was restarted
persistence = PicklePersistence(filepath='arbitrarycallbackdatabot')
# Create the Updater and pass it your bot's token.
updater = Updater("TOKEN", persistence=persistence, arbitrary_callback_data=True)
updater = (
Updater.builder()
.token("TOKEN")
.persistence(persistence)
.arbitrary_callback_data(True)
.build()
)

updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CommandHandler('help', help_command))
Expand Down
13 changes: 7 additions & 6 deletions examples/chatmemberbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@

from telegram import Update, Chat, ChatMember, ParseMode, ChatMemberUpdated
from telegram.ext import (
Updater,
CommandHandler,
CallbackContext,
ChatMemberHandler,
Updater,
CallbackContext,
)

# Enable logging

logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
Expand Down Expand Up @@ -66,7 +67,7 @@ def extract_status_change(
return was_member, is_member


def track_chats(update: Update, context: CallbackContext) -> None:
def track_chats(update: Update, context: CallbackContext.DEFAULT_TYPE) -> None:
"""Tracks the chats the bot is in."""
result = extract_status_change(update.my_chat_member)
if result is None:
Expand Down Expand Up @@ -101,7 +102,7 @@ def track_chats(update: Update, context: CallbackContext) -> None:
context.bot_data.setdefault("channel_ids", set()).discard(chat.id)


def show_chats(update: Update, context: CallbackContext) -> None:
def show_chats(update: Update, context: CallbackContext.DEFAULT_TYPE) -> None:
"""Shows which chats the bot is in"""
user_ids = ", ".join(str(uid) for uid in context.bot_data.setdefault("user_ids", set()))
group_ids = ", ".join(str(gid) for gid in context.bot_data.setdefault("group_ids", set()))
Expand All @@ -114,7 +115,7 @@ def show_chats(update: Update, context: CallbackContext) -> None:
update.effective_message.reply_text(text)


def greet_chat_members(update: Update, context: CallbackContext) -> None:
def greet_chat_members(update: Update, context: CallbackContext.DEFAULT_TYPE) -> None:
"""Greets new users in chats and announces when someone leaves"""
result = extract_status_change(update.chat_member)
if result is None:
Expand All @@ -139,7 +140,7 @@ def greet_chat_members(update: Update, context: CallbackContext) -> None:
def main() -> None:
"""Start the bot."""
# Create the Updater and pass it your bot's token.
updater = Updater("TOKEN")
updater = Updater.builder().token("TOKEN").build()

# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
Expand Down
9 changes: 5 additions & 4 deletions examples/contexttypesbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,14 @@

from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, ParseMode
from telegram.ext import (
Updater,
CommandHandler,
CallbackContext,
ContextTypes,
CallbackQueryHandler,
TypeHandler,
Dispatcher,
ExtBot,
Updater,
)


Expand All @@ -32,8 +33,8 @@ 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]):
# The [ExtBot, dict, ChatData, dict] is for type checkers like mypy
class CustomContext(CallbackContext[ExtBot, dict, ChatData, dict]):
"""Custom class for context."""

def __init__(self, dispatcher: Dispatcher):
Expand Down Expand Up @@ -113,7 +114,7 @@ def track_users(update: Update, context: CustomContext) -> None:
def main() -> None:
"""Run the bot."""
context_types = ContextTypes(context=CustomContext, chat_data=ChatData)
updater = Updater("TOKEN", context_types=context_types)
updater = Updater.builder().token("TOKEN").context_types(context_types).build()

dispatcher = updater.dispatcher
# run track_users in its own group to not interfere with the user handlers
Expand Down
22 changes: 11 additions & 11 deletions examples/conversationbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,25 @@

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


# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)

logger = logging.getLogger(__name__)

GENDER, PHOTO, LOCATION, BIO = range(4)


def start(update: Update, context: CallbackContext) -> int:
def start(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
"""Starts the conversation and asks the user about their gender."""
reply_keyboard = [['Boy', 'Girl', 'Other']]

Expand All @@ -52,7 +52,7 @@ def start(update: Update, context: CallbackContext) -> int:
return GENDER


def gender(update: Update, context: CallbackContext) -> int:
def gender(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
"""Stores the selected gender and asks for a photo."""
user = update.message.from_user
logger.info("Gender of %s: %s", user.first_name, update.message.text)
Expand All @@ -65,7 +65,7 @@ def gender(update: Update, context: CallbackContext) -> int:
return PHOTO


def photo(update: Update, context: CallbackContext) -> int:
def photo(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
"""Stores the photo and asks for a location."""
user = update.message.from_user
photo_file = update.message.photo[-1].get_file()
Expand All @@ -78,7 +78,7 @@ def photo(update: Update, context: CallbackContext) -> int:
return LOCATION


def skip_photo(update: Update, context: CallbackContext) -> int:
def skip_photo(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
"""Skips the photo and asks for a location."""
user = update.message.from_user
logger.info("User %s did not send a photo.", user.first_name)
Expand All @@ -89,7 +89,7 @@ def skip_photo(update: Update, context: CallbackContext) -> int:
return LOCATION


def location(update: Update, context: CallbackContext) -> int:
def location(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
"""Stores the location and asks for some info about the user."""
user = update.message.from_user
user_location = update.message.location
Expand All @@ -103,7 +103,7 @@ def location(update: Update, context: CallbackContext) -> int:
return BIO


def skip_location(update: Update, context: CallbackContext) -> int:
def skip_location(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
"""Skips the location and asks for info about the user."""
user = update.message.from_user
logger.info("User %s did not send a location.", user.first_name)
Expand All @@ -114,7 +114,7 @@ def skip_location(update: Update, context: CallbackContext) -> int:
return BIO


def bio(update: Update, context: CallbackContext) -> int:
def bio(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
"""Stores the info about the user and ends the conversation."""
user = update.message.from_user
logger.info("Bio of %s: %s", user.first_name, update.message.text)
Expand All @@ -123,7 +123,7 @@ def bio(update: Update, context: CallbackContext) -> int:
return ConversationHandler.END


def cancel(update: Update, context: CallbackContext) -> int:
def cancel(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:
"""Cancels and ends the conversation."""
user = update.message.from_user
logger.info("User %s canceled the conversation.", user.first_name)
Expand All @@ -137,7 +137,7 @@ def cancel(update: Update, context: CallbackContext) -> int:
def main() -> None:
"""Run the bot."""
# Create the Updater and pass it your bot's token.
updater = Updater("TOKEN")
updater = Updater.builder().token("TOKEN").build()

# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
Expand Down
Loading