ApplicationBuilder¶
- class telegram.ext.ApplicationBuilder[source]¶
This class serves as initializer for
telegram.ext.Applicationvia the so called builder pattern. To build atelegram.ext.Application, one first initializes an instance of this class. Arguments for thetelegram.ext.Applicationto build are then added by subsequently calling the methods of the builder. Finally, thetelegram.ext.Applicationis built by callingbuild(). In the simplest case this can look like the following example.Example
application = ApplicationBuilder().token("TOKEN").build()
Please see the description of the individual methods for information on which arguments can be set and what the defaults are when not called. When no default is mentioned, the argument will not be used by default.
Note
Some arguments are mutually exclusive. E.g. after calling
token(), you can’t set a custom bot withbot()and vice versa.Unless a custom
telegram.Botinstance is set viabot(),build()will usetelegram.ext.ExtBotfor the bot.
See also
Changed in version 22.0: Removed deprecated methods
proxy_urlandget_updates_proxy_url.- application_class(application_class, kwargs=None)[source]¶
Sets a custom subclass instead of
telegram.ext.Application. The subclass’s__init__should look like thisdef __init__(self, custom_arg_1, custom_arg_2, ..., **kwargs): super().__init__(**kwargs) self.custom_arg_1 = custom_arg_1 self.custom_arg_2 = custom_arg_2
- Parameters:
application_class (
type) – A subclass oftelegram.ext.Applicationkwargs (dict[
str,object], optional) – Keyword arguments for the initialization. Defaults to an empty dict.
- Returns:
The same builder with the updated argument.
- Return type:
- arbitrary_callback_data(arbitrary_callback_data)[source]¶
Specifies whether
telegram.ext.Application.botshould allow arbitrary objects as callback data fortelegram.InlineKeyboardButtonand how many keyboards should be cached in memory. If not called, only strings can be used as callback data and no data will be stored in memory.Important
If you want to use this feature, you must install PTB with the optional requirement
callback-data, i.e.pip install "python-telegram-bot[callback-data]"
Examples
See also
- Parameters:
arbitrary_callback_data (
bool|int) – IfTrueis passed, the default cache size of1024will be used. Pass an integer to specify a different cache size.- Returns:
The same builder with the updated argument.
- Return type:
- base_file_url(base_file_url)[source]¶
Sets the base file URL for
telegram.ext.Application.bot. If not called, will default to'https://api.telegram.org/file/bot'.Changed in version 21.11: Supports callable input and string formatting.
- Parameters:
base_file_url (
str| Callable[[str],str]) – The URL or input for the URL as accepted bytelegram.Bot.base_file_url.- Returns:
The same builder with the updated argument.
- Return type:
- base_url(base_url)[source]¶
Sets the base URL for
telegram.ext.Application.bot. If not called, will default to'https://api.telegram.org/bot'.Changed in version 21.11: Supports callable input and string formatting.
- Parameters:
base_url (
str| Callable[[str],str]) – The URL or input for the URL as accepted bytelegram.Bot.base_url.- Returns:
The same builder with the updated argument.
- Return type:
- bot(bot)[source]¶
Sets a
telegram.Botinstance fortelegram.ext.Application.bot. Instances of subclasses liketelegram.ext.ExtBotare also valid.- Parameters:
bot (
telegram.Bot) – The bot.- Returns:
The same builder with the updated argument.
- Return type:
- build()[source]¶
Builds a
telegram.ext.Applicationwith the provided arguments.Calls
telegram.ext.JobQueue.set_application()andtelegram.ext.BasePersistence.set_bot()if appropriate.- Returns:
- concurrent_updates(concurrent_updates)[source]¶
Specifies if and how many updates may be processed concurrently instead of one by one. If not called, updates will be processed one by one.
Warning
Processing updates concurrently is not recommended when stateful handlers like
telegram.ext.ConversationHandlerare used. Only use this if you are sure that your bot does not (explicitly or implicitly) rely on updates being processed sequentially.Tip
When making requests to the Bot API in an asynchronous fashion (e.g. via
block=False,Application.create_task,concurrent_updates()or theJobQueue), it can happen that more requests are being made in parallel than there are connections in the pool. If the number of requests is much higher than the number of connections, even settingpool_timeout()to a larger value may not always be enough to prevent pool timeouts. You should therefore setconcurrent_updates(),connection_pool_size()andpool_timeout()to values that make sense for your setup.- Parameters:
concurrent_updates (
bool|int|BaseUpdateProcessor) –Passing
Truewill allow for256updates to be processed concurrently usingtelegram.ext.SimpleUpdateProcessor. Pass an integer to specify a different number of updates that may be processed concurrently. Pass an instance oftelegram.ext.BaseUpdateProcessorto use that instance for handling updates concurrently.Changed in version 20.4: Now accepts
BaseUpdateProcessorinstances.- Returns:
The same builder with the updated argument.
- Return type:
- connect_timeout(connect_timeout)[source]¶
Sets the connection attempt timeout for the
connect_timeoutparameter oftelegram.Bot.request. Defaults to5.0.See also
- Parameters:
connect_timeout (
float) – Seetelegram.request.HTTPXRequest.connect_timeoutfor more information.- Returns:
The same builder with the updated argument.
- Return type:
- connection_pool_size(connection_pool_size)[source]¶
Sets the size of the connection pool for the
connection_pool_sizeparameter oftelegram.Bot.request. Defaults to256.Tip
When making requests to the Bot API in an asynchronous fashion (e.g. via
block=False,Application.create_task,concurrent_updates()or theJobQueue), it can happen that more requests are being made in parallel than there are connections in the pool. If the number of requests is much higher than the number of connections, even settingpool_timeout()to a larger value may not always be enough to prevent pool timeouts. You should therefore setconcurrent_updates(),connection_pool_size()andpool_timeout()to values that make sense for your setup.See also
- Parameters:
connection_pool_size (
int) – The size of the connection pool.- Returns:
The same builder with the updated argument.
- Return type:
- context_types(context_types)[source]¶
Sets a
telegram.ext.ContextTypesinstance fortelegram.ext.Application.context_types.Examples
- Parameters:
context_types (
telegram.ext.ContextTypes) – The context types.- Returns:
The same builder with the updated argument.
- Return type:
- defaults(defaults)[source]¶
Sets the
telegram.ext.Defaultsinstance fortelegram.ext.Application.bot.See also
- Parameters:
defaults (
telegram.ext.Defaults) – The defaults instance.- Returns:
The same builder with the updated argument.
- Return type:
- get_updates_connect_timeout(get_updates_connect_timeout)[source]¶
Sets the connection attempt timeout for the
telegram.request.HTTPXRequest.connect_timeoutparameter which is used for thetelegram.Bot.get_updates()request. Defaults to5.0.See also
- Parameters:
get_updates_connect_timeout (
float) – Seetelegram.request.HTTPXRequest.connect_timeoutfor more information.- Returns:
The same builder with the updated argument.
- Return type:
- get_updates_connection_pool_size(get_updates_connection_pool_size)[source]¶
Sets the size of the connection pool for the
telegram.request.HTTPXRequest.connection_pool_sizeparameter which is used for thetelegram.Bot.get_updates()request. Defaults to1.See also
- Parameters:
get_updates_connection_pool_size (
int) – The size of the connection pool.- Returns:
The same builder with the updated argument.
- Return type:
- get_updates_http_version(get_updates_http_version)[source]¶
Sets the HTTP protocol version which is used for the
http_versionparameter which is used in thetelegram.Bot.get_updates()request. By default, HTTP/1.1 is used.See also
Note
Users have observed stability issues with HTTP/2, which happen due to how the h2 library handles cancellations of keepalive connections. See #3556 for a discussion.
You will also need to install the http2 dependency. Keep in mind that the HTTP/1.1 implementation may be considered the “more robust option at this time”.
pip install httpx[http2]
Added in version 20.1.
Changed in version 20.2: Reset the default version to 1.1.
- Parameters:
get_updates_http_version (
str) –Pass
"2"or"2.0"if you’d like to use HTTP/2 for making requests to Telegram. Defaults to"1.1", in which case HTTP/1.1 is used.Changed in version 20.5: Accept
"2"as a valid value.- Returns:
The same builder with the updated argument.
- Return type:
- get_updates_pool_timeout(get_updates_pool_timeout)[source]¶
Sets the connection pool’s connection freeing timeout for the
pool_timeoutparameter which is used for thetelegram.Bot.get_updates()request. Defaults to1.0.See also
- Parameters:
get_updates_pool_timeout (
float) – Seetelegram.request.HTTPXRequest.pool_timeoutfor more information.- Returns:
The same builder with the updated argument.
- Return type:
- get_updates_proxy(get_updates_proxy)[source]¶
Sets the proxy for the
telegram.request.HTTPXRequest.proxyparameter which is used fortelegram.Bot.get_updates(). Defaults toNone.See also
Added in version 20.7.
- Parameters:
proxy (
str|httpx.Proxy|httpx.URL) – The URL to a proxy server, ahttpx.Proxyobject or ahttpx.URLobject. Seetelegram.request.HTTPXRequest.proxyfor more information.- Returns:
The same builder with the updated argument.
- Return type:
- get_updates_read_timeout(get_updates_read_timeout)[source]¶
Sets the waiting timeout for the
telegram.request.HTTPXRequest.read_timeoutparameter which is used for thetelegram.Bot.get_updates()request. Defaults to5.0.See also
- Parameters:
get_updates_read_timeout (
float) – Seetelegram.request.HTTPXRequest.read_timeoutfor more information.- Returns:
The same builder with the updated argument.
- Return type:
- get_updates_request(get_updates_request)[source]¶
Sets a
telegram.request.BaseRequestinstance for theget_updates_requestparameter oftelegram.ext.Application.bot.See also
- Parameters:
get_updates_request (
telegram.request.BaseRequest) – The request instance.- Returns:
The same builder with the updated argument.
- Return type:
- get_updates_socket_options(get_updates_socket_options)[source]¶
Sets the options for the
socket_optionsparameter oftelegram.Bot.get_updates_request. Defaults toNone.See also
Added in version 20.7.
- Parameters:
get_updates_socket_options (Collection[
tuple], optional) – Socket options. Seetelegram.request.HTTPXRequest.socket_optionsfor more information.- Returns:
The same builder with the updated argument.
- Return type:
- get_updates_write_timeout(get_updates_write_timeout)[source]¶
Sets the write operation timeout for the
telegram.request.HTTPXRequest.write_timeoutparameter which is used for thetelegram.Bot.get_updates()request. Defaults to5.0.See also
- Parameters:
get_updates_write_timeout (
float) – Seetelegram.request.HTTPXRequest.write_timeoutfor more information.- Returns:
The same builder with the updated argument.
- Return type:
- http_version(http_version)[source]¶
Sets the HTTP protocol version which is used for the
http_versionparameter oftelegram.Bot.request. By default, HTTP/1.1 is used.See also
Note
Users have observed stability issues with HTTP/2, which happen due to how the h2 library handles cancellations of keepalive connections. See #3556 for a discussion.
If you want to use HTTP/2, you must install PTB with the optional requirement
http2, i.e.pip install "python-telegram-bot[http2]"
Keep in mind that the HTTP/1.1 implementation may be considered the “more robust option at this time”.
Added in version 20.1.
Changed in version 20.2: Reset the default version to 1.1.
- Parameters:
http_version (
str) –Pass
"2"or"2.0"if you’d like to use HTTP/2 for making requests to Telegram. Defaults to"1.1", in which case HTTP/1.1 is used.Changed in version 20.5: Accept
"2"as a valid value.- Returns:
The same builder with the updated argument.
- Return type:
- job_queue(job_queue)[source]¶
Sets a
telegram.ext.JobQueueinstance fortelegram.ext.Application.job_queue. If not called, a job queue will be instantiated if the requirements oftelegram.ext.JobQueueare installed.Examples
See also
Note
telegram.ext.JobQueue.set_application()will be called automatically bybuild().The job queue will be automatically started and stopped by
telegram.ext.Application.start()andtelegram.ext.Application.stop(), respectively.When passing
Noneor when the requirements oftelegram.ext.JobQueueare not installed,telegram.ext.ConversationHandler.conversation_timeoutcan not be used, as this usestelegram.ext.Application.job_queueinternally.
- Parameters:
job_queue (
telegram.ext.JobQueue) – The job queue. PassNoneif you don’t want to use a job queue.- Returns:
The same builder with the updated argument.
- Return type:
- local_mode(local_mode)[source]¶
Specifies the value for
local_modefor thetelegram.ext.Application.bot. If not called, will default toFalse.See also
- Parameters:
local_mode (
bool) – Whether the bot should run in local mode.- Returns:
The same builder with the updated argument.
- Return type:
- media_write_timeout(media_write_timeout)[source]¶
Sets the media write operation timeout for the
media_write_timeoutparameter oftelegram.Bot.request. Defaults to20.Added in version 21.0.
- Parameters:
media_write_timeout (
float) – Seetelegram.request.HTTPXRequest.media_write_timeoutfor more information.- Returns:
The same builder with the updated argument.
- Return type:
- persistence(persistence)[source]¶
Sets a
telegram.ext.BasePersistenceinstance fortelegram.ext.Application.persistence.Note
When using a persistence, note that all data stored in
context.user_data,context.chat_data,context.bot_dataand intelegram.ext.ExtBot.callback_data_cachemust be copyable withcopy.deepcopy(). This is due to the data being deep copied before handing it over to the persistence in order to avoid race conditions.Examples
See also
Warning
If a
telegram.ext.ContextTypesinstance is set viacontext_types(), the persistence instance must use the same types!- Parameters:
persistence (
telegram.ext.BasePersistence) – The persistence instance.- Returns:
The same builder with the updated argument.
- Return type:
- pool_timeout(pool_timeout)[source]¶
Sets the connection pool’s connection freeing timeout for the
pool_timeoutparameter oftelegram.Bot.request. Defaults to1.0.Tip
When making requests to the Bot API in an asynchronous fashion (e.g. via
block=False,Application.create_task,concurrent_updates()or theJobQueue), it can happen that more requests are being made in parallel than there are connections in the pool. If the number of requests is much higher than the number of connections, even settingpool_timeout()to a larger value may not always be enough to prevent pool timeouts. You should therefore setconcurrent_updates(),connection_pool_size()andpool_timeout()to values that make sense for your setup.See also
- Parameters:
pool_timeout (
float) – Seetelegram.request.HTTPXRequest.pool_timeoutfor more information.- Returns:
The same builder with the updated argument.
- Return type:
- post_init(post_init)[source]¶
Sets a callback to be executed by
Application.run_polling()andApplication.run_webhook()after executingApplication.initialize()but before executingUpdater.start_polling()orUpdater.start_webhook(), respectively.Tip
This can be used for custom startup logic that requires to await coroutines, e.g. setting up the bots commands via
set_my_commands().Example
async def post_init(application: Application) -> None: await application.bot.set_my_commands([('start', 'Starts the bot')]) application = Application.builder().token("TOKEN").post_init(post_init).build()
Note
If you implement custom logic that implies that you will not be using
Application’s methodsrun_polling()orrun_webhook()to run your application (like it’s done in Custom Webhook Bot Example), the callback you set in this method will not be called automatically. So instead of setting a callback with this method, you have to explicitlyawaitthe function that you want to run at this stage of your application’s life (in the example mentioned above, that would be inasync with applicationcontext manager).See also
- Parameters:
post_init (coroutine function) –
The custom callback. Must be a coroutine function and must accept exactly one positional argument, which is the
Application:async def post_init(application: Application) -> None:
- Returns:
The same builder with the updated argument.
- Return type:
- post_shutdown(post_shutdown)[source]¶
Sets a callback to be executed by
Application.run_polling()andApplication.run_webhook()after executingUpdater.shutdown()andApplication.shutdown().Tip
This can be used for custom shutdown logic that requires to await coroutines, e.g. closing a database connection
Example
async def post_shutdown(application: Application) -> None: await application.bot_data['database'].close() application = Application.builder() .token("TOKEN") .post_shutdown(post_shutdown) .build()
Note
If you implement custom logic that implies that you will not be using
Application’s methodsrun_polling()orrun_webhook()to run your application (like it’s done in Custom Webhook Bot Example), the callback you set in this method will not be called automatically. So instead of setting a callback with this method, you have to explicitlyawaitthe function that you want to run at this stage of your application’s life (in the example mentioned above, that would be inasync with applicationcontext manager).See also
- Parameters:
post_shutdown (coroutine function) –
The custom callback. Must be a coroutine function and must accept exactly one positional argument, which is the
Application:async def post_shutdown(application: Application) -> None:
- Returns:
The same builder with the updated argument.
- Return type:
- post_stop(post_stop)[source]¶
Sets a callback to be executed by
Application.run_polling()andApplication.run_webhook()after executingUpdater.stop()andApplication.stop().Added in version 20.1.
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.
Hint
The callback will be called only, if
Application.stop()was indeed called successfully. For example, if the application is stopped early by callingApplication.stop_running()withinpost_init(), then the set callback will not be called.Example
async def post_stop(application: Application) -> None: await application.bot.send_message(123456, "Shutting down...") application = Application.builder() .token("TOKEN") .post_stop(post_stop) .build()
Note
If you implement custom logic that implies that you will not be using
Application’s methodsrun_polling()orrun_webhook()to run your application (like it’s done in Custom Webhook Bot Example), the callback you set in this method will not be called automatically. So instead of setting a callback with this method, you have to explicitlyawaitthe function that you want to run at this stage of your application’s life (in the example mentioned above, that would be inasync with applicationcontext manager).See also
- Parameters:
post_stop (coroutine function) –
The custom callback. Must be a coroutine function and must accept exactly one positional argument, which is the
Application:async def post_stop(application: Application) -> None:
- Returns:
The same builder with the updated argument.
- Return type:
- private_key(private_key, password=None)[source]¶
Sets the private key and corresponding password for decryption of telegram passport data for
telegram.ext.Application.bot.Examples
See also
- Parameters:
private_key (
bytes|str|pathlib.Path) – The private key or the file path of a file that contains the key. In the latter case, the file’s content will be read automatically.password (
bytes|str|pathlib.Path, optional) – The corresponding password or the file path of a file that contains the password. In the latter case, the file’s content will be read automatically.
- Returns:
The same builder with the updated argument.
- Return type:
- proxy(proxy)[source]¶
Sets the proxy for the
proxyparameter oftelegram.Bot.request. Defaults toNone.See also
Added in version 20.7.
- Parameters:
proxy (
str|httpx.Proxy|httpx.URL) – The URL to a proxy server, ahttpx.Proxyobject or ahttpx.URLobject. Seetelegram.request.HTTPXRequest.proxyfor more information.- Returns:
The same builder with the updated argument.
- Return type:
- rate_limiter(rate_limiter)[source]¶
Sets a
telegram.ext.BaseRateLimiterinstance for thetelegram.ext.ExtBot.rate_limiterparameter oftelegram.ext.Application.bot.- Parameters:
rate_limiter (
telegram.ext.BaseRateLimiter) – The rate limiter.- Returns:
The same builder with the updated argument.
- Return type:
- read_timeout(read_timeout)[source]¶
Sets the waiting timeout for the
read_timeoutparameter oftelegram.Bot.request. Defaults to5.0.See also
- Parameters:
read_timeout (
float) – Seetelegram.request.HTTPXRequest.read_timeoutfor more information.- Returns:
The same builder with the updated argument.
- Return type:
- request(request)[source]¶
Sets a
telegram.request.BaseRequestinstance for thetelegram.Bot.requestparameter oftelegram.ext.Application.bot.See also
- Parameters:
request (
telegram.request.BaseRequest) – The request instance.- Returns:
The same builder with the updated argument.
- Return type:
- socket_options(socket_options)[source]¶
Sets the options for the
socket_optionsparameter oftelegram.Bot.request. Defaults toNone.See also
Added in version 20.7.
- Parameters:
socket_options (Collection[
tuple], optional) – Socket options. Seetelegram.request.HTTPXRequest.socket_optionsfor more information.- Returns:
The same builder with the updated argument.
- Return type:
- token(token)[source]¶
Sets the token for
telegram.ext.Application.bot.- Parameters:
- Returns:
The same builder with the updated argument.
- Return type:
- update_queue(update_queue)[source]¶
Sets a
asyncio.Queueinstance fortelegram.ext.Application.update_queue, i.e. the queue that the application will fetch updates from. Will also be used for thetelegram.ext.Application.updater. If not called, a queue will be instantiated.See also
- Parameters:
update_queue (
asyncio.Queue) – The queue.- Returns:
The same builder with the updated argument.
- Return type:
- updater(updater)[source]¶
Sets a
telegram.ext.Updaterinstance fortelegram.ext.Application.updater. Thetelegram.ext.Updater.botandtelegram.ext.Updater.update_queuewill be used fortelegram.ext.Application.botandtelegram.ext.Application.update_queue, respectively.- Parameters:
updater (
telegram.ext.Updater|None) – The updater instance orNoneif no updater should be used.- Returns:
The same builder with the updated argument.
- Return type:
- write_timeout(write_timeout)[source]¶
Sets the write operation timeout for the
write_timeoutparameter oftelegram.Bot.request. Defaults to5.0.See also
- Parameters:
write_timeout (
float) – Seetelegram.request.HTTPXRequest.write_timeoutfor more information.- Returns:
The same builder with the updated argument.
- Return type: