Bases: typing.Generic
, contextlib.AbstractAsyncContextManager
This class dispatches all kinds of updates to its registered handlers, and is the entry point to a PTB application.
Instances of this class can be used as asyncio context managers, where
async with application: # code
is roughly equivalent to
try: await application.initialize() # code finally: await application.shutdown()
This class is a Generic
class and accepts six type variables:
The type of bot
. Must be telegram.Bot
or a subclass of that class.
The type of the argument context
of callback functions for (error) handlers and jobs. Must be telegram.ext.CallbackContext
or a subclass of that class. This must be consistent with the following types.
The type of the values of user_data
.
The type of the values of chat_data
.
The type of bot_data
.
The type of job_queue
. Must either be telegram.ext.JobQueue
or a subclass of that or None
.
The bot object that should be passed to the handlers.
The synchronized queue that will contain the updates.
Optional. The updater used by this application.
A dictionary handlers can use to store data for the chat. For each integer chat id, the corresponding value of this mapping is available as telegram.ext.CallbackContext.chat_data
in handler callbacks for updates from that chat.
Changed in version 20.0: chat_data
is now read-only. Note that the values of the mapping are still mutable, i.e. editing context.chat_data
within a handler callback is possible (and encouraged), but editing the mapping application.chat_data
itself is not.
Tip
Manually modifying chat_data
is almost never needed and unadvisable.
Entries are never deleted automatically from this mapping. If you want to delete the data associated with a specific chat, e.g. if the bot got removed from that chat, please use drop_chat_data()
.
A dictionary handlers can use to store data for the user. For each integer user id, the corresponding value of this mapping is available as telegram.ext.CallbackContext.user_data
in handler callbacks for updates from that user.
Changed in version 20.0: user_data
is now read-only. Note that the values of the mapping are still mutable, i.e. editing context.user_data
within a handler callback is possible (and encouraged), but editing the mapping application.user_data
itself is not.
Tip
Manually modifying user_data
is almost never needed and unadvisable.
Entries are never deleted automatically from this mapping. If you want to delete the data associated with a specific user, e.g. if that user blocked the bot, please use drop_user_data()
.
A dictionary handlers can use to store data for the bot.
The persistence class to store data that should be persistent over restarts.
A dictionary mapping each handler group to the list of handlers registered to that group.
dict[int
, list[telegram.ext.BaseHandler
]]
A dictionary where the keys are error handlers and the values indicate whether they are to be run blocking.
dict[coroutine function, bool
]
Specifies the types used by this dispatcher for the context
argument of handler and job callbacks.
Optional. A callback that will be executed by Application.run_polling()
and Application.run_webhook()
after initializing the application via initialize()
.
Optional. A callback that will be executed by Application.run_polling()
and Application.run_webhook()
after shutting down the application via shutdown()
.
Optional. A callback that will be executed by Application.run_polling()
and Application.run_webhook()
after stopping the application via stop()
.
Added in version 20.1.
Asynchronous context manager which initializes
the App.
The initialized App instance.
Exception – If an exception is raised during initialization, shutdown()
is called in this case.
Asynchronous context manager which shuts down
the App.
Give a string representation of the application in the form Application[bot=...]
.
As this class doesn’t implement object.__str__()
, the default implementation will be used, which is equivalent to __repr__()
.
Registers an error handler in the Application. This handler will receive every error which happens in your bot. See the docs of process_error()
for more details on how errors are handled.
Note
Attempts to add the same callback multiple times will be ignored.
Hint
This method currently has no influence on calls to process_error()
that are already in progress.
Warning
This behavior should currently be considered an implementation detail and not as guaranteed behavior.
callback (coroutine function) –
The callback function for this error handler. Will be called when an error is raised. Callback signature:
async def callback(update: Optional[object], context: CallbackContext)
The error that happened will be present in telegram.ext.CallbackContext.error
.
block (bool
, optional) – Determines whether the return value of the callback should be awaited before processing the next error handler in process_error()
. Defaults to True
.
Register a handler.
TL;DR: Order and priority counts. 0 or 1 handlers per group will be used. End handling of update with telegram.ext.ApplicationHandlerStop
.
A handler must be an instance of a subclass of telegram.ext.BaseHandler
. All handlers are organized in groups with a numeric value. The default group is 0. All groups will be evaluated for handling an update, but only 0 or 1 handler per group will be used. If telegram.ext.ApplicationHandlerStop
is raised from one of the handlers, no further handlers (regardless of the group) will be called.
The priority/order of handlers is determined as follows:
Priority of the group (lower group number == higher priority)
The first handler in a group which can handle an update (see telegram.ext.BaseHandler.check_update
) will be used. Other handlers from the group will not be used. The order in which handlers were added to the group defines the priority.
Warning
Adding persistent telegram.ext.ConversationHandler
after the application has been initialized is discouraged. This is because the persisted conversation states need to be loaded into memory while the application is already processing updates, which might lead to race conditions and undesired behavior. In particular, current conversation states may be overridden by the loaded data.
Hint
This method currently has no influence on calls to process_update()
that are already in progress.
Warning
This behavior should currently be considered an implementation detail and not as guaranteed behavior.
handler (telegram.ext.BaseHandler
) – A BaseHandler instance.
Registers multiple handlers at once. The order of the handlers in the passed sequence(s) matters. See add_handler()
for details.
Added in version 20.0.
handlers (Sequence[telegram.ext.BaseHandler
] | dict[int, Sequence[telegram.ext.BaseHandler
]]) –
Specify a sequence of handlers or a dictionary where the keys are groups and values are handlers.
Changed in version 21.7: Accepts any collections.abc.Sequence
as input instead of just a list or tuple.
group (int
, optional) – Specify which group the sequence of handlers
should be added to. Defaults to 0
.
Example:
app.add_handlers(handlers={ -1: [MessageHandler(...)], 1: [CallbackQueryHandler(...), CommandHandler(...)] }
TypeError – If the combination of arguments is invalid.
Convenience method. Returns a new telegram.ext.ApplicationBuilder
.
Added in version 20.0.
The number of concurrent updates that will be processed in parallel. A value of 0
indicates updates are not being processed concurrently.
Changed in version 20.4: This is now just a shortcut to update_processor.max_concurrent_updates
.
Thin wrapper around asyncio.create_task()
that handles exceptions raised by the coroutine
with process_error()
.
Note
If coroutine
raises an exception, it will be set on the task created by this method even though it’s handled by process_error()
.
If the application is currently running, tasks created by this method will be awaited with stop()
.
The awaitable to run as task.
Changed in version 20.2: Accepts asyncio.Future
and generator-based coroutine functions.
Deprecated since version 20.4: Since Python 3.12, generator-based coroutine functions are no longer accepted.
update (object
, optional) – If set, will be passed to process_error()
as additional information for the error handlers. Moreover, the corresponding chat_data
and user_data
entries will be updated in the next run of update_persistence()
after the coroutine
is finished.
The name of the task.
Added in version 20.4.
The created task.
Drops the corresponding entry from the chat_data
. Will also be deleted from the persistence on the next run of update_persistence()
, if applicable.
Added in version 20.0.
Drops the corresponding entry from the user_data
. Will also be deleted from the persistence on the next run of update_persistence()
, if applicable.
Added in version 20.0.
Initializes the Application by initializing:
The bot
, by calling telegram.Bot.initialize()
.
The updater
, by calling telegram.ext.Updater.initialize()
.
The persistence
, by loading persistent conversations and data.
The update_processor
by calling telegram.ext.BaseUpdateProcessor.initialize()
.
Does not call post_init
- that is only done by run_polling()
and run_webhook()
.
JobQueue
used by the
Mark entries of chat_data
and user_data
to be updated on the next run of update_persistence()
.
Tip
Use this method sparingly. If you have to use this method, it likely means that you access and modify context.application.chat/user_data[some_id]
within a callback. Note that for data which should be available globally in all handler callbacks independent of the chat/user, it is recommended to use bot_data
instead.
Added in version 20.3.
Moves the contents of chat_data
at key old_chat_id
to the key new_chat_id
. Also marks the entries to be updated accordingly in the next run of update_persistence()
.
message (telegram.Message
, optional) –
A message with either migrate_from_chat_id
or migrate_to_chat_id
. Mutually exclusive with passing old_chat_id
and new_chat_id
.
old_chat_id (int
, optional) – The old chat ID. Mutually exclusive with passing message
new_chat_id (int
, optional) – The new chat ID. Mutually exclusive with passing message
ValueError – Raised if the input is invalid.
Processes an error by passing it to all error handlers registered with add_error_handler()
. If one of the error handlers raises telegram.ext.ApplicationHandlerStop
, the error will not be handled by other error handlers. Raising telegram.ext.ApplicationHandlerStop
also stops processing of the update when this method is called by process_update()
, i.e. no further handlers (even in other groups) will handle the update. All other exceptions raised by an error handler will just be logged.
update (object
| telegram.Update
) – The update that caused the error.
job (telegram.ext.Job
, optional) –
The job that caused the error.
Added in version 20.0.
coroutine (coroutine function, optional) – The coroutine that caused the error.
True
, if one of the error handlers raised telegram.ext.ApplicationHandlerStop
. False
, otherwise.
Processes a single update and marks the update to be updated by the persistence later. Exceptions raised by handler callbacks will be processed by process_error()
.
Changed in version 20.0: Persistence is now updated in an interval set by telegram.ext.BasePersistence.update_interval
.
update (telegram.Update
| object
| telegram.error.TelegramError
) – The update to process.
RuntimeError – If the application was not initialized.
Removes an error handler.
Hint
This method currently has no influence on calls to process_error()
that are already in progress.
Warning
This behavior should currently be considered an implementation detail and not as guaranteed behavior.
callback (coroutine function) – The error handler to remove.
Remove a handler from the specified group.
Hint
This method currently has no influence on calls to process_update()
that are already in progress.
Warning
This behavior should currently be considered an implementation detail and not as guaranteed behavior.
handler (telegram.ext.BaseHandler
) – A telegram.ext.BaseHandler
instance.
group (object
, optional) – The group identifier. Default is 0
.
Convenience method that takes care of initializing and starting the app, polling updates from Telegram using telegram.ext.Updater.start_polling()
and a graceful shutdown of the app on exit.
The app will shut down when KeyboardInterrupt
or SystemExit
is raised. This also works from within handlers, error handlers and jobs. However, using stop_running()
will give a somewhat cleaner shutdown behavior than manually raising those exceptions. On unix, the app will also shut down on receiving the signals specified by stop_signals
.
The order of execution by run_polling()
is roughly as follows:
Run the application until the users stops it
A small wrapper is passed to telegram.ext.Updater.start_polling.error_callback
which forwards errors occurring during polling to registered error handlers
. The update parameter of the callback will be set to None
.
Tip
When combining python-telegram-bot
with other asyncio
based frameworks, using this method is likely not the best choice, as it blocks the event loop until it receives a stop signal as described above. Instead, you can manually call the methods listed below to start and shut down the application and the updater
. Keeping the event loop running and listening for a stop signal is then up to you.
To gracefully stop the execution of this method from within a handler, job or error callback, use stop_running()
.
Changed in version Removed: the deprecated parameters read_timeout
, write_timeout
, connect_timeout
, and pool_timeout
. Use the corresponding methods in telegram.ext.ApplicationBuilder
instead.
poll_interval (float
, optional) – Time to wait between polling updates from Telegram in seconds. Default is 0.0
.
timeout (int
| datetime.timedelta
, optional) –
Passed to telegram.Bot.get_updates.timeout
. Default is timedelta(seconds=10)
.
Changed in version v22.2: datetime.timedelta
objects are accepted in addition to plain int
values.
bootstrap_retries (int
, optional) –
Whether the bootstrapping phase (calling initialize()
and the boostrapping of telegram.ext.Updater.start_polling()
) will retry on failures on the Telegram server.
< 0 - retry indefinitely
0 - no retries (default)
> 0 - retry up to X times
Changed in version 21.11: The default value will be changed to from -1
to 0
. Indefinite retries during bootstrapping are not recommended.
drop_pending_updates (bool
, optional) – Whether to clean any pending updates on Telegram servers before actually starting to poll. Default is False
.
allowed_updates (Sequence[str
], optional) –
Passed to telegram.Bot.get_updates()
.
Changed in version 21.9: Accepts any collections.abc.Sequence
as input instead of just a list
close_loop (bool
, optional) –
If True
, the current event loop will be closed upon shutdown. Defaults to True
.
stop_signals (Sequence[int
] | None
, optional) –
Signals that will shut down the app. Pass None
to not use stop signals. Defaults to signal.SIGINT
, signal.SIGTERM
and signal.SIGABRT
on non Windows platforms.
RuntimeError – If the Application does not have an telegram.ext.Updater
.
Convenience method that takes care of initializing and starting the app, listening for updates from Telegram using telegram.ext.Updater.start_webhook()
and a graceful shutdown of the app on exit.
The app will shut down when KeyboardInterrupt
or SystemExit
is raised. This also works from within handlers, error handlers and jobs. However, using stop_running()
will give a somewhat cleaner shutdown behavior than manually raising those exceptions. On unix, the app will also shut down on receiving the signals specified by stop_signals
.
If cert
and key
are not provided, the webhook will be started directly on http://listen:port/url_path
, so SSL can be handled by another application. Else, the webhook will be started on https://listen:port/url_path
. Also calls telegram.Bot.set_webhook()
as required.
The order of execution by run_webhook()
is roughly as follows:
Run the application until the users stops it
Important
If you want to use this method, you must install PTB with the optional requirement webhooks
, i.e.
pip install "python-telegram-bot[webhooks]"
Tip
When combining python-telegram-bot
with other asyncio
based frameworks, using this method is likely not the best choice, as it blocks the event loop until it receives a stop signal as described above. Instead, you can manually call the methods listed below to start and shut down the application and the updater
. Keeping the event loop running and listening for a stop signal is then up to you.
To gracefully stop the execution of this method from within a handler, job or error callback, use stop_running()
.
listen (str
, optional) – IP-Address to listen on. Defaults to 127.0.0.1.
port (int
, optional) – Port the bot should be listening on. Must be one of telegram.constants.SUPPORTED_WEBHOOK_PORTS
unless the bot is running behind a proxy. Defaults to 80
.
url_path (str
, optional) – Path inside url. Defaults to `` ‘’ ``
cert (pathlib.Path
| str
, optional) – Path to the SSL certificate file.
key (pathlib.Path
| str
, optional) – Path to the SSL key file.
bootstrap_retries (int
, optional) –
Whether the bootstrapping phase (calling initialize()
and the boostrapping of telegram.ext.Updater.start_polling()
) will retry on failures on the Telegram server.
< 0 - retry indefinitely
0 - no retries (default)
> 0 - retry up to X times
webhook_url (str
, optional) – Explicitly specify the webhook url. Useful behind NAT, reverse proxy, etc. Default is derived from listen
, port
, url_path
, cert
, and key
.
allowed_updates (Sequence[str
], optional) –
Passed to telegram.Bot.set_webhook()
.
Changed in version 21.9: Accepts any collections.abc.Sequence
as input instead of just a list
drop_pending_updates (bool
, optional) – Whether to clean any pending updates on Telegram servers before actually starting to poll. Default is False
.
ip_address (str
, optional) – Passed to telegram.Bot.set_webhook()
.
max_connections (int
, optional) – Passed to telegram.Bot.set_webhook()
. Defaults to 40
.
close_loop (bool
, optional) –
If True
, the current event loop will be closed upon shutdown. Defaults to True
.
stop_signals (Sequence[int
] | None
, optional) –
Signals that will shut down the app. Pass None
to not use stop signals. Defaults to signal.SIGINT
, signal.SIGTERM
and signal.SIGABRT
.
secret_token (str
, optional) –
Secret token to ensure webhook requests originate from Telegram. See telegram.Bot.set_webhook.secret_token
for more details.
When added, the web server started by this call will expect the token to be set in the X-Telegram-Bot-Api-Secret-Token
header of an incoming request and will raise a http.HTTPStatus.FORBIDDEN
error if either the header isn’t set or it is set to a wrong token.
Added in version 20.0.
unix (pathlib.Path
| str
| socket.socket
, optional) –
Can be either:
the path to the unix socket file as pathlib.Path
or str
. This will be passed to tornado.netutil.bind_unix_socket to create the socket. If the Path does not exist, the file will be created.
or the socket itself. This option allows you to e.g. restrict the permissions of the socket for improved security. Note that you need to pass the correct family, type and socket options yourself.
Caution
This parameter is a replacement for the default TCP bind. Therefore, it is mutually exclusive with listen
and port
. When using this param, you must also run a reverse proxy to the unix socket and set the appropriate webhook_url
.
Added in version 20.8.
Changed in version 21.1: Added support to pass a socket instance itself.
Indicates if this application is running.
Shuts down the Application by shutting down:
bot
by calling telegram.Bot.shutdown()
updater
by calling telegram.ext.Updater.shutdown()
persistence
by calling update_persistence()
and BasePersistence.flush()
update_processor
by calling telegram.ext.BaseUpdateProcessor.shutdown()
Does not call post_shutdown
- that is only done by run_polling()
and run_webhook()
.
RuntimeError – If the application is still running
.
Starts
a background task that fetches updates from update_queue
and processes them via process_update()
.
job_queue
, if set.
a background task that calls update_persistence()
in regular intervals, if persistence
is set.
Tip
When using a custom logic for startup and shutdown of the application, eventual cancellation of pending tasks should happen only after stop()
has been called in order to ensure that the tasks mentioned above are not cancelled prematurely.
RuntimeError – If the application is already running or was not initialized.
Stops the process after processing any pending updates or tasks created by create_task()
. Also stops job_queue
, if set. Finally, calls update_persistence()
and BasePersistence.flush()
on persistence
, if set.
Warning
Once this method is called, no more updates will be fetched from update_queue
, even if it’s not empty.
RuntimeError – If the application is not running.
This method can be used to stop the execution of run_polling()
or run_webhook()
from within a handler, job or error callback. This allows a graceful shutdown of the application, i.e. the methods listed in run_polling
and run_webhook
will still be executed.
This method can also be called within post_init()
. This allows for a graceful, early shutdown of the application if some condition is met (e.g., a database connection could not be established).
Note
If the application is not running and this method is not called within post_init()
, this method does nothing.
Warning
This method is designed to for use in combination with run_polling()
or run_webhook()
. Using this method in combination with a custom logic for starting and stopping the application is not guaranteed to work as expected. Use at your own risk.
Added in version 20.5.
Changed in version 21.2: Added support for calling within post_init()
.
Updates user_data
, chat_data
, bot_data
in persistence
along with callback_data_cache
and the conversation states of any persistent ConversationHandler
registered for this application.
For user_data
and chat_data
, only those entries are updated which either were used or have been manually marked via mark_data_for_update_persistence()
since the last run of this method.
Tip
This method will be called in regular intervals by the application. There is usually no need to call it manually.
Note
Any data is deep copied with copy.deepcopy()
before handing it over to the persistence in order to avoid race conditions, so all persisted data must be copyable.
The update processor used by this application.
Added in version 20.4.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4