
Reference
Resources
arbitrarycallbackdatabot.pychatmemberbot.pycontexttypesbot.pyconversationbot.pyconversationbot2.pycustomwebhookbot.pydeeplinking.pyechobot.pyerrorhandlerbot.pyinlinebot.pyinlinekeyboard.pyinlinekeyboard2.pynestedconversationbot.pypassportbot.pypaymentbot.pypersistentconversationbot.pypollbot.pytimerbot.pywebappbot.pyProject
This class serves as initializer fortelegram.ext.Application via the so calledbuilder pattern. To build atelegram.ext.Application, one first initializes aninstance of this class. Arguments for thetelegram.ext.Application to build are thenadded by subsequently calling the methods of the builder. Finally, thetelegram.ext.Application is built by callingbuild(). In the simplest case thiscan 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 beset and what the defaults are when not called. When no default is mentioned, the argument willnot be used by default.
Note
Some arguments are mutually exclusive. E.g. after callingtoken(), you can’t seta custom bot withbot() and vice versa.
Unless a customtelegram.Bot instance is set viabot(),build() willusetelegram.ext.ExtBot for the bot.
See also
Changed in version 22.0:Removed deprecated methodsproxy_url andget_updates_proxy_url.
Sets a custom subclass instead oftelegram.ext.Application. Thesubclass’s__init__ should look like this
def__init__(self,custom_arg_1,custom_arg_2,...,**kwargs):super().__init__(**kwargs)self.custom_arg_1=custom_arg_1self.custom_arg_2=custom_arg_2
application_class (type) – A subclass oftelegram.ext.Application
kwargs (dict[str,object], optional) – Keyword arguments for theinitialization. Defaults to an empty dict.
The same builder with the updated argument.
Specifies whethertelegram.ext.Application.bot should allow arbitrary objects ascallback data fortelegram.InlineKeyboardButton and how many keyboards should becached in memory. If not called, only strings can be used as callback data and no data willbe stored in memory.
Important
If you want to use this feature, you must install PTB with the optional requirementcallback-data, i.e.
pipinstall"python-telegram-bot[callback-data]"Examples
See also
arbitrary_callback_data (bool |int) – IfTrue is passed, thedefault cache size of1024 will be used. Pass an integer to specify a differentcache size.
The same builder with the updated argument.
Sets the base file URL fortelegram.ext.Application.bot. If notcalled, will default to'https://api.telegram.org/file/bot'.
Changed in version 21.11:Supports callable input and string formatting.
base_file_url (str | Callable[[str],str]) – The URL orinput for the URL as accepted bytelegram.Bot.base_file_url.
The same builder with the updated argument.
Sets the base URL fortelegram.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.
base_url (str | Callable[[str],str]) – The URL orinput for the URL as accepted bytelegram.Bot.base_url.
The same builder with the updated argument.
Sets atelegram.Bot instance fortelegram.ext.Application.bot. Instances of subclasses liketelegram.ext.ExtBot are also valid.
bot (telegram.Bot) – The bot.
The same builder with the updated argument.
Builds atelegram.ext.Application with the provided arguments.
Callstelegram.ext.JobQueue.set_application() andtelegram.ext.BasePersistence.set_bot() if appropriate.
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 liketelegram.ext.ConversationHandler are used. Only use this if you are surethat your bot does not (explicitly or implicitly) rely on updates being processedsequentially.
Tip
When making requests to the Bot API in an asynchronous fashion (e.g. viablock=False,Application.create_task,concurrent_updates() or theJobQueue), it can happen that more requestsare 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 pooltimeouts.You should therefore setconcurrent_updates(),connection_pool_size() andpool_timeout() to values that make sense for your setup.
concurrent_updates (bool |int |BaseUpdateProcessor) –
PassingTrue will allow for256 updates to be processed concurrently usingtelegram.ext.SimpleUpdateProcessor. Pass an integer to specify a differentnumber of updates that may be processed concurrently. Pass an instance oftelegram.ext.BaseUpdateProcessor to use that instance for handling updatesconcurrently.
Changed in version 20.4:Now acceptsBaseUpdateProcessor instances.
The same builder with the updated argument.
Sets the connection attempt timeout for theconnect_timeout parameter oftelegram.Bot.request. Defaults to5.0.
See also
connect_timeout (float) – Seetelegram.request.HTTPXRequest.connect_timeout for more information.
The same builder with the updated argument.
Sets the size of the connection pool for theconnection_pool_size parameter oftelegram.Bot.request. Defaults to256.
Tip
When making requests to the Bot API in an asynchronous fashion (e.g. viablock=False,Application.create_task,concurrent_updates() or theJobQueue), it can happen that more requestsare 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 pooltimeouts.You should therefore setconcurrent_updates(),connection_pool_size() andpool_timeout() to values that make sense for your setup.
connection_pool_size (int) – The size of the connection pool.
The same builder with the updated argument.
Sets atelegram.ext.ContextTypes instance fortelegram.ext.Application.context_types.
Examples
context_types (telegram.ext.ContextTypes) – The context types.
The same builder with the updated argument.
Sets thetelegram.ext.Defaults instance fortelegram.ext.Application.bot.
See also
defaults (telegram.ext.Defaults) – The defaults instance.
The same builder with the updated argument.
Sets the connection attempt timeout for thetelegram.request.HTTPXRequest.connect_timeout parameter which is used forthetelegram.Bot.get_updates() request. Defaults to5.0.
See also
get_updates_connect_timeout (float) – Seetelegram.request.HTTPXRequest.connect_timeout for more information.
The same builder with the updated argument.
Sets the size of the connection pool for thetelegram.request.HTTPXRequest.connection_pool_size parameter which is usedfor thetelegram.Bot.get_updates() request. Defaults to1.
See also
get_updates_connection_pool_size (int) – The size of the connection pool.
The same builder with the updated argument.
Sets the HTTP protocol version which is used for thehttp_version parameter 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 theh2library handles cancellations ofkeepalive connections. See#3556 for a discussion.
You will also need to install the http2 dependency. Keep in mind that the HTTP/1.1implementation may be considered the“more robust option at this time”.
pipinstallhttpx[http2]
Added in version 20.1.
Changed in version 20.2:Reset the default version to 1.1.
get_updates_http_version (str) –
Pass"2" or"2.0" if you’d like to useHTTP/2 for making requests to Telegram. Defaults to"1.1", in which caseHTTP/1.1 is used.
Changed in version 20.5:Accept"2" as a valid value.
The same builder with the updated argument.
Sets the connection pool’s connection freeing timeout for thepool_timeout parameter which is used for thetelegram.Bot.get_updates() request. Defaults to1.0.
See also
get_updates_pool_timeout (float) – Seetelegram.request.HTTPXRequest.pool_timeout for more information.
The same builder with the updated argument.
Sets the proxy for thetelegram.request.HTTPXRequest.proxyparameter which is used fortelegram.Bot.get_updates(). Defaults toNone.
See also
Added in version 20.7.
proxy (str |httpx.Proxy |httpx.URL) – The URL to a proxy server,ahttpx.Proxy object or ahttpx.URL object. Seetelegram.request.HTTPXRequest.proxy for more information.
The same builder with the updated argument.
Sets the waiting timeout for thetelegram.request.HTTPXRequest.read_timeout parameter which is used for thetelegram.Bot.get_updates() request. Defaults to5.0.
See also
get_updates_read_timeout (float) – Seetelegram.request.HTTPXRequest.read_timeout for more information.
The same builder with the updated argument.
Sets atelegram.request.BaseRequest instance for theget_updates_request parameter oftelegram.ext.Application.bot.
See also
get_updates_request (telegram.request.BaseRequest) – The request instance.
The same builder with the updated argument.
Sets the options for thesocket_optionsparameter oftelegram.Bot.get_updates_request. Defaults toNone.
See also
Added in version 20.7.
get_updates_socket_options (Collection[tuple], optional) – Socket options. Seetelegram.request.HTTPXRequest.socket_options for more information.
The same builder with the updated argument.
Sets the write operation timeout for thetelegram.request.HTTPXRequest.write_timeout parameter which is used forthetelegram.Bot.get_updates() request. Defaults to5.0.
See also
get_updates_write_timeout (float) – Seetelegram.request.HTTPXRequest.write_timeout for more information.
The same builder with the updated argument.
Sets the HTTP protocol version which is used for thehttp_version parameter 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 theh2library handles cancellations ofkeepalive connections. See#3556 for a discussion.
If you want to use HTTP/2, you must install PTB with the optional requirementhttp2, i.e.
pipinstall"python-telegram-bot[http2]"Keep in mind that the HTTP/1.1 implementation may be considered the“morerobust option at this time”.
Added in version 20.1.
Changed in version 20.2:Reset the default version to 1.1.
http_version (str) –
Pass"2" or"2.0" if you’d like to use HTTP/2 formaking 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.
The same builder with the updated argument.
Sets atelegram.ext.JobQueue instance fortelegram.ext.Application.job_queue. If not called, a job queue will beinstantiated if the requirements oftelegram.ext.JobQueue are installed.
Examples
See also
Note
telegram.ext.JobQueue.set_application() will be called automatically bybuild().
The job queue will be automatically started and stopped bytelegram.ext.Application.start() andtelegram.ext.Application.stop(),respectively.
When passingNone or when the requirements oftelegram.ext.JobQueueare not installed,telegram.ext.ConversationHandler.conversation_timeoutcan not be used, as this usestelegram.ext.Application.job_queue internally.
job_queue (telegram.ext.JobQueue) – The job queue. PassNone if youdon’t want to use a job queue.
The same builder with the updated argument.
Specifies the value forlocal_mode for thetelegram.ext.Application.bot.If not called, will default toFalse.
See also
local_mode (bool) – Whether the bot should run in local mode.
The same builder with the updated argument.
Sets the media write operation timeout for themedia_write_timeout parameter oftelegram.Bot.request. Defaults to20.
Added in version 21.0.
media_write_timeout (float) – Seetelegram.request.HTTPXRequest.media_write_timeout for more information.
The same builder with the updated argument.
Sets atelegram.ext.BasePersistence instance fortelegram.ext.Application.persistence.
Note
When using a persistence, note that alldata stored incontext.user_data,context.chat_data,context.bot_data andintelegram.ext.ExtBot.callback_data_cache must be copyable withcopy.deepcopy(). This is due to the data being deep copied before handing it overto the persistence in order to avoid race conditions.
Examples
See also
Warning
If atelegram.ext.ContextTypes instance is set viacontext_types(),the persistence instance must use the same types!
persistence (telegram.ext.BasePersistence) – The persistence instance.
The same builder with the updated argument.
Sets the connection pool’s connection freeing timeout for thepool_timeout parameter oftelegram.Bot.request. Defaults to1.0.
Tip
When making requests to the Bot API in an asynchronous fashion (e.g. viablock=False,Application.create_task,concurrent_updates() or theJobQueue), it can happen that more requestsare 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 pooltimeouts.You should therefore setconcurrent_updates(),connection_pool_size() andpool_timeout() to values that make sense for your setup.
See also
pool_timeout (float) – Seetelegram.request.HTTPXRequest.pool_timeout for more information.
The same builder with the updated argument.
Sets a callback to be executed byApplication.run_polling() andApplication.run_webhook()after executingApplication.initialize() butbefore 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 viaset_my_commands().
Example
asyncdefpost_init(application:Application)->None:awaitapplication.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 willnot be usingApplication’s methodsrun_polling() orrun_webhook() to run your application (like it’s done inCustom Webhook Bot Example), the callback you set in this methodwill not be called automatically. So instead of setting a callback with this method, you have to explicitlyawait the function that you want to run at this stage of your application’s life (in theexample mentioned above, that would be inasyncwithapplication context manager).
See also
post_init (coroutine function) –
The custom callback. Must be acoroutine function and must accept exactly one positional argument, whichis theApplication:
asyncdefpost_init(application:Application)->None:
The same builder with the updated argument.
Sets a callback to be executed byApplication.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
asyncdefpost_shutdown(application:Application)->None:awaitapplication.bot_data['database'].close()application=Application.builder().token("TOKEN").post_shutdown(post_shutdown).build()
Note
If you implement custom logic that implies that you willnot be usingApplication’s methodsrun_polling() orrun_webhook() to run your application (like it’s done inCustom Webhook Bot Example), the callback you set in this methodwill not be called automatically. So instead of setting a callback with this method, you have to explicitlyawait the function that you want to run at this stage of your application’s life (in theexample mentioned above, that would be inasyncwithapplication context manager).
See also
post_shutdown (coroutine function) –
The custom callback. Must be acoroutine function and must accept exactly one positional argument, whichis theApplication:
asyncdefpost_shutdown(application:Application)->None:
The same builder with the updated argument.
Sets a callback to be executed byApplication.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, ifApplication.stop() was indeed calledsuccessfully. For example, if the application is stopped early by callingApplication.stop_running() withinpost_init(), then the set callback willnot be called.
Example
asyncdefpost_stop(application:Application)->None:awaitapplication.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 willnot be usingApplication’s methodsrun_polling() orrun_webhook() to run your application (like it’s done inCustom Webhook Bot Example), the callback you set in this methodwill not be called automatically. So instead of setting a callback with this method, you have to explicitlyawait the function that you want to run at this stage of your application’s life (in theexample mentioned above, that would be inasyncwithapplication context manager).
See also
post_stop (coroutine function) –
The custom callback. Must be acoroutine function and must accept exactly one positional argument, whichis theApplication:
asyncdefpost_stop(application:Application)->None:
The same builder with the updated argument.
Sets the private key and corresponding password for decryption of telegram passport datafortelegram.ext.Application.bot.
Examples
See also
private_key (bytes |str |pathlib.Path) – The private key or thefile path of a file that contains the key. In the latter case, the file’s contentwill be read automatically.
password (bytes |str |pathlib.Path, optional) – The correspondingpassword or the file path of a file that contains the password. In the latter case,the file’s content will be read automatically.
The same builder with the updated argument.
Sets the proxy for theproxyparameter oftelegram.Bot.request. Defaults toNone.
See also
Added in version 20.7.
proxy (str |httpx.Proxy |httpx.URL) – The URL to a proxyserver, ahttpx.Proxy object or ahttpx.URL object. Seetelegram.request.HTTPXRequest.proxy for more information.
The same builder with the updated argument.
Sets atelegram.ext.BaseRateLimiter instance for thetelegram.ext.ExtBot.rate_limiter parameter oftelegram.ext.Application.bot.
rate_limiter (telegram.ext.BaseRateLimiter) – The rate limiter.
The same builder with the updated argument.
Sets the waiting timeout for theread_timeout parameter oftelegram.Bot.request. Defaults to5.0.
See also
read_timeout (float) – Seetelegram.request.HTTPXRequest.read_timeout for more information.
The same builder with the updated argument.
Sets atelegram.request.BaseRequest instance for thetelegram.Bot.request parameter oftelegram.ext.Application.bot.
See also
request (telegram.request.BaseRequest) – The request instance.
The same builder with the updated argument.
Sets the options for thesocket_optionsparameter oftelegram.Bot.request. Defaults toNone.
See also
Added in version 20.7.
socket_options (Collection[tuple], optional) – Socket options. Seetelegram.request.HTTPXRequest.socket_options for more information.
The same builder with the updated argument.
Sets the token fortelegram.ext.Application.bot.
The same builder with the updated argument.
Sets aasyncio.Queue instance fortelegram.ext.Application.update_queue, i.e. the queue that the application willfetch updates from. Will also be used for thetelegram.ext.Application.updater.If not called, a queue will be instantiated.
update_queue (asyncio.Queue) – The queue.
The same builder with the updated argument.
Sets atelegram.ext.Updater instance fortelegram.ext.Application.updater. Thetelegram.ext.Updater.bot andtelegram.ext.Updater.update_queue will be used fortelegram.ext.Application.bot andtelegram.ext.Application.update_queue,respectively.
updater (telegram.ext.Updater |None) – The updater instance orNone if no updater should be used.
The same builder with the updated argument.
Sets the write operation timeout for thewrite_timeout parameter oftelegram.Bot.request. Defaults to5.0.
See also
write_timeout (float) – Seetelegram.request.HTTPXRequest.write_timeout for more information.
The same builder with the updated argument.
ApplicationBuilderApplicationBuilder.application_class()ApplicationBuilder.arbitrary_callback_data()ApplicationBuilder.base_file_url()ApplicationBuilder.base_url()ApplicationBuilder.bot()ApplicationBuilder.build()ApplicationBuilder.concurrent_updates()ApplicationBuilder.connect_timeout()ApplicationBuilder.connection_pool_size()ApplicationBuilder.context_types()ApplicationBuilder.defaults()ApplicationBuilder.get_updates_connect_timeout()ApplicationBuilder.get_updates_connection_pool_size()ApplicationBuilder.get_updates_http_version()ApplicationBuilder.get_updates_pool_timeout()ApplicationBuilder.get_updates_proxy()ApplicationBuilder.get_updates_read_timeout()ApplicationBuilder.get_updates_request()ApplicationBuilder.get_updates_socket_options()ApplicationBuilder.get_updates_write_timeout()ApplicationBuilder.http_version()ApplicationBuilder.job_queue()ApplicationBuilder.local_mode()ApplicationBuilder.media_write_timeout()ApplicationBuilder.persistence()ApplicationBuilder.pool_timeout()ApplicationBuilder.post_init()ApplicationBuilder.post_shutdown()ApplicationBuilder.post_stop()ApplicationBuilder.private_key()ApplicationBuilder.proxy()ApplicationBuilder.rate_limiter()ApplicationBuilder.read_timeout()ApplicationBuilder.request()ApplicationBuilder.socket_options()ApplicationBuilder.token()ApplicationBuilder.update_queue()ApplicationBuilder.updater()ApplicationBuilder.write_timeout()