From b496fabf62c1c750b30d0c8d51432700bddc3361 Mon Sep 17 00:00:00 2001 From: Bibo-Joshi <22366557+Bibo-Joshi@users.noreply.github.com> Date: Mon, 20 May 2024 15:52:30 +0200 Subject: [PATCH] Call `Application.post_stop` Only if `Application.stop` was called (#4211) --- telegram/ext/_application.py | 5 +++-- telegram/ext/_applicationbuilder.py | 8 +++++++- tests/ext/test_application.py | 4 ++-- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/telegram/ext/_application.py b/telegram/ext/_application.py index 79467b2b4b1..b18877bc013 100644 --- a/telegram/ext/_application.py +++ b/telegram/ext/_application.py @@ -1086,8 +1086,9 @@ def __run( loop.run_until_complete(self.updater.stop()) # type: ignore[union-attr] if self.running: loop.run_until_complete(self.stop()) - if self.post_stop: - loop.run_until_complete(self.post_stop(self)) + # post_stop should be called only if stop was called! + if self.post_stop: + loop.run_until_complete(self.post_stop(self)) loop.run_until_complete(self.shutdown()) if self.post_shutdown: loop.run_until_complete(self.post_shutdown(self)) diff --git a/telegram/ext/_applicationbuilder.py b/telegram/ext/_applicationbuilder.py index 783a4985872..9fa1fe65455 100644 --- a/telegram/ext/_applicationbuilder.py +++ b/telegram/ext/_applicationbuilder.py @@ -1334,7 +1334,13 @@ def post_stop( Tip: This can be used for custom stop logic that requires to await coroutines, e.g. - sending message to a chat before shutting down the bot + sending message to a chat before shutting down the bot. + + Hint: + The callback will be called only, if :meth:`Application.stop` was indeed called + successfully. For example, if the application is stopped early by calling + :meth:`Application.stop_running` within :meth:`post_init`, then the set callback will + *not* be called. Example: .. code:: diff --git a/tests/ext/test_application.py b/tests/ext/test_application.py index 6d1827ae4ed..714abf8537a 100644 --- a/tests/ext/test_application.py +++ b/tests/ext/test_application.py @@ -2134,7 +2134,6 @@ def after(_, name): "app_initialize", "updater_initialize", "app_shutdown", - "post_stop", "post_shutdown", "updater_shutdown", } @@ -2441,7 +2440,8 @@ async def callback(*args, **kwargs): app.run_polling(close_loop=False) # The important part here is that start(_polling) are *not* called! - assert called_callbacks == ["post_stop", "post_shutdown"] + # post_stop must not be called either, since we never called stop() + assert called_callbacks == ["post_shutdown"] assert len(caplog.records) == 1 assert caplog.records[-1].name == "telegram.ext.Application"