telegram.ext package

Module contents

Extensions over the Telegram Bot API to facilitate bot making

class telegram.ext.Dispatcher(bot, update_queue, workers=4, exception_event=None, job_queue=None)

Bases: object

This class dispatches all kinds of updates to its registered handlers.

Parameters:
  • bot (telegram.Bot) – The bot object that should be passed to the handlers
  • update_queue (Queue) – The synchronized queue that will contain the updates.
  • job_queue (Optional[telegram.ext.JobQueue]) – The JobQueue instance to pass onto handler callbacks
  • workers (Optional[int]) – Number of maximum concurrent worker threads for the @run_async decorator
add_error_handler(callback)

Registers an error handler in the Dispatcher.

Parameters:handler (function) – A function that takes Bot, Update, TelegramError as arguments.
add_handler(handler, group=0)

Register a handler.

TL;DR: Order and priority counts. 0 or 1 handlers per group will be used.

A handler must be an instance of a subclass of telegram.ext.Handler. 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.

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 should handle an 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.
Parameters:
  • handler (telegram.ext.Handler) – A Handler instance
  • group (Optional[int]) – The group identifier. Default is 0
dispatch_error(update, error)

Dispatches an error.

Parameters:
  • update (object) – The update that caused the error
  • error (telegram.TelegramError) – The Telegram error that was raised.
classmethod get_instance()

Get the singleton instance of this class.

Returns:Dispatcher
has_running_threads
logger = <logging.Logger object>
process_update(update)

Processes a single update.

Parameters:update (object) –
remove_error_handler(callback)

De-registers an error handler.

Parameters:handler (function) –
remove_handler(handler, group=0)

Remove a handler from the specified group

Parameters:
  • handler (telegram.ext.Handler) – A Handler instance
  • group (optional[object]) – The group identifier. Default is 0
run_async(func, *args, **kwargs)

Queue a function (with given args/kwargs) to be run asynchronously.

Parameters:
  • func (function) – The function to run in the thread.
  • args (Optional[tuple]) – Arguments to func.
  • kwargs (Optional[dict]) – Keyword arguments to func.
Returns:

Promise

start()

Thread target of thread ‘dispatcher’. Runs in background and processes the update queue.

stop()

Stops the thread

class telegram.ext.JobQueue(bot, prevent_autostart=None)

Bases: object

This class allows you to periodically perform tasks with the bot.

queue

PriorityQueue

bot

telegram.Bot

Parameters:bot (telegram.Bot) – The bot instance that should be passed to the jobs
Deprecated: 5.2
prevent_autostart (Optional[bool]): Thread does not start during initialisation. Use start method instead.
jobs()

Returns a tuple of all jobs that are currently in the JobQueue

put(job, next_t=None)

Queue a new job.

Parameters:
  • job (telegram.ext.Job) – The Job instance representing the new job
  • next_t (Optional[int, float, datetime.timedelta, datetime.datetime, datetime.time]) – Time in or at which the job should run for the first time. This parameter will be interpreted depending on its type. int or float will be interpreted as “seconds from now” in which the job should run. datetime.timedelta will be interpreted as “time from now” in which the job should run. datetime.datetime will be interpreted as a specific date and time at which the job should run. datetime.time will be interpreted as a specific time at which the job should run. This could be either today or, if the time has already passed, tomorrow.
run_daily(callback, time, days=(0, 1, 2, 3, 4, 5, 6), context=None, name=None)

Creates a new Job that runs once and adds it to the queue.

Parameters:
  • callback (function) – The callback function that should be executed by the new job. It should take two parameters bot and job, where job is the Job instance. It can be used to access it’s context or terminate the job.
  • time (datetime.time) – Time of day at which the job should run.
  • days (Optional[tuple[int]]) – Defines on which days of the week the job should run.
  • to Days.EVERY_DAY (Defaults) –
  • context (Optional[object]) – Additional data needed for the callback function. Can be accessed through job.context in the callback. Defaults to None
  • name (Optional[str]) – The name of the new job. Defaults to callback.__name__
Returns:

The new Job instance that has been added to the job queue.

Return type:

Job

run_once(callback, when, context=None, name=None)

Creates a new Job that runs once and adds it to the queue.

Parameters:
  • callback (function) – The callback function that should be executed by the new job. It should take two parameters bot and job, where job is the Job instance. It can be used to access it’s context or change it to a repeating job.
  • when (int, float, datetime.timedelta, datetime.datetime, datetime.time) –

    Time in or at which the job should run. This parameter will be interpreted depending on its type.

    • int or float will be interpreted as “seconds from now” in which the job should run.
    • datetime.timedelta will be interpreted as “time from now” in which the job should run.
    • datetime.datetime will be interpreted as a specific date and time at which the job should run.
    • datetime.time will be interpreted as a specific time of day at which the job should run. This could be either today or, if the time has already passed, tomorrow.
  • context (Optional[object]) – Additional data needed for the callback function. Can be accessed through job.context in the callback. Defaults to None
  • name (Optional[str]) – The name of the new job. Defaults to callback.__name__
Returns:

The new Job instance that has been added to the job queue.

Return type:

Job

run_repeating(callback, interval, first=None, context=None, name=None)

Creates a new Job that runs once and adds it to the queue.

Parameters:
  • callback (function) – The callback function that should be executed by the new job. It should take two parameters bot and job, where job is the Job instance. It can be used to access it’s context, terminate the job or change its interval.
  • interval (int, float, datetime.timedelta) – The interval in which the job will run. If it is an int or a float, it will be interpreted as seconds.
  • first (int, float, datetime.timedelta, datetime.datetime, datetime.time) –
    • int or float will be interpreted as “seconds from now” in which the job should run.
    • datetime.timedelta will be interpreted as “time from now” in which the job should run.
    • datetime.datetime will be interpreted as a specific date and time at which the job should run.
    • datetime.time will be interpreted as a specific time of day at which the job should run. This could be either today or, if the time has already passed, tomorrow.

    Defaults to interval

  • context (Optional[object]) – Additional data needed for the callback function. Can be accessed through job.context in the callback. Defaults to None
  • name (Optional[str]) – The name of the new job. Defaults to callback.__name__
Returns:

The new Job instance that has been added to the job queue.

Return type:

Job

start()

Starts the job_queue thread.

stop()

Stops the thread

tick()

Run all jobs that are due and re-enqueue them with their interval.

class telegram.ext.Job(callback, interval=None, repeat=True, context=None, days=(0, 1, 2, 3, 4, 5, 6), name=None, job_queue=None)

Bases: object

This class encapsulates a Job

callback

function – The function that the job executes when it’s due

interval

int, float, datetime.timedelta – The interval in which the job runs

days

tuple[int] – A tuple of int values that determine on which days of the week the job runs

repeat

bool – If the job runs periodically or only once

name

str – The name of this job

job_queue

JobQueue – The JobQueue this job belongs to

enabled

bool – Boolean property that decides if this job is currently active

Parameters:
  • callback (function) – The callback function that should be executed by the Job. It should take two parameters bot and job, where job is the Job instance. It can be used to terminate the job or modify its interval.
  • interval (Optional[int, float, datetime.timedelta]) – The interval in which the job will execute its callback function. int and float will be interpreted as seconds. If you don’t set this value, you must set repeat=False and specify next_t when you put the job into the job queue.
  • repeat (Optional[bool]) – If this job should be periodically execute its callback function (True) or only once (False). Defaults to True
  • context (Optional[object]) – Additional data needed for the callback function. Can be accessed through job.context in the callback. Defaults to None
  • days (Optional[tuple[int]]) – Defines on which days of the week the job should run. Defaults to Days.EVERY_DAY
  • name (Optional[str]) – The name of this job. Defaults to callback.__name__
  • (Optional[class (job_queue) – telegram.ext.JobQueue]): The JobQueue this job belongs to. Only optional for backward compatibility with JobQueue.put().
days
enabled
interval
interval_seconds
job_queue

rtype – JobQueue

removed
repeat
run(bot)

Executes the callback function

schedule_removal()

Schedules this job for removal from the JobQueue. It will be removed without executing its callback function again.

class telegram.ext.Updater(token=None, base_url=None, workers=4, bot=None, user_sig_handler=None, request_kwargs=None)

Bases: object

This class, which employs the Dispatcher class, provides a frontend to telegram.Bot to the programmer, so they can focus on coding the bot. Its purpose is to receive the updates from Telegram and to deliver them to said dispatcher. It also runs in a separate thread, so the user can interact with the bot, for example on the command line. The dispatcher supports handlers for different kinds of data: Updates from Telegram, basic text commands and even arbitrary types. The updater can be started as a polling service or, for production, use a webhook to receive updates. This is achieved using the WebhookServer and WebhookHandler classes.

Attributes:

Parameters:
  • token (Optional[str]) – The bot’s token given by the @BotFather
  • base_url (Optional[str]) –
  • workers (Optional[int]) – Amount of threads in the thread pool for functions decorated with @run_async
  • bot (Optional[Bot]) – A pre-initialized bot instance. If a pre-initizlied bot is used, it is the user’s responsibility to create it using a Request instance with a large enough connection pool.
  • user_sig_handler (Optional[function]) – Takes signum, frame as positional arguments. This will be called when a signal is received, defaults are (SIGINT, SIGTERM, SIGABRT) setable with Updater.idle(stop_signals=(signals))
  • request_kwargs (Optional[dict]) – Keyword args to control the creation of a request object (ignored if bot argument is used).
Raises:

ValueError – If both token and bot are passed or none of them.

idle(stop_signals=(2, 15, 6))

Blocks until one of the signals are received and stops the updater

Parameters:stop_signals – Iterable containing signals from the signal module that should be subscribed to. Updater.stop() will be called on receiving one of those signals. Defaults to (SIGINT, SIGTERM, SIGABRT)
signal_handler(signum, frame)
start_polling(poll_interval=0.0, timeout=10, network_delay=None, clean=False, bootstrap_retries=0, read_latency=2.0, allowed_updates=None)

Starts polling updates from Telegram.

Parameters:
  • poll_interval (Optional[float]) – Time to wait between polling updates from Telegram in
  • Default is 0.0 (seconds.) –
  • timeout (Optional[float]) – Passed to Bot.getUpdates
  • network_delay – Deprecated. Will be honoured as read_latency for a while but will be removed in the future.
  • clean (Optional[bool]) – Whether to clean any pending updates on Telegram servers before actually starting to poll. Default is False.
  • bootstrap_retries (Optional[int]) –

    Whether the bootstrapping phase of the Updater will retry on failures on the Telegram server.

    < 0 - retry indefinitely
    0 - no retries (default)
    > 0 - retry up to X times
  • allowed_updates (Optional[list[str]]) – Passed to Bot.getUpdates
  • read_latency (Optional[float|int]) – Grace time in seconds for receiving the reply from server. Will be added to the timeout value and used as the read timeout from server (Default: 2).
Returns:

The update queue that can be filled from the main thread

Return type:

Queue

start_webhook(listen='127.0.0.1', port=80, url_path='', cert=None, key=None, clean=False, bootstrap_retries=0, webhook_url=None, allowed_updates=None)

Starts a small http server to listen for updates via webhook. 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

Parameters:
  • listen (Optional[str]) – IP-Address to listen on
  • port (Optional[int]) – Port the bot should be listening on
  • url_path (Optional[str]) – Path inside url
  • cert (Optional[str]) – Path to the SSL certificate file
  • key (Optional[str]) – Path to the SSL key file
  • clean (Optional[bool]) – Whether to clean any pending updates on Telegram servers before actually starting the webhook. Default is False.
  • bootstrap_retries (Optional[int[) –

    Whether the bootstrapping phase of the Updater will retry on failures on the Telegram server.

    < 0 - retry indefinitely
    0 - no retries (default)
    > 0 - retry up to X times
  • webhook_url (Optional[str]) – Explicitly specify the webhook url. Useful behind NAT, reverse proxy, etc. Default is derived from listen, port & url_path.
  • allowed_updates (Optional[list[str]]) – Passed to Bot.setWebhook
Returns:

The update queue that can be filled from the main thread

Return type:

Queue

stop()

Stops the polling/webhook thread, the dispatcher and the job queue

class telegram.ext.CallbackQueryHandler(callback, pass_update_queue=False, pass_job_queue=False, pattern=None, pass_groups=False, pass_groupdict=False, pass_user_data=False, pass_chat_data=False)

Bases: telegram.ext.handler.Handler

Handler class to handle Telegram callback queries. Optionally based on a regex. Read the documentation of the re module for more information.

Parameters:
  • callback (function) – A function that takes bot, update as positional arguments. It will be called when the check_update has determined that an update should be processed by this handler.
  • pass_update_queue (optional[bool]) – If set to True, a keyword argument called update_queue will be passed to the callback function. It will be the Queue instance used by the Updater and Dispatcher that contains new updates which can be used to insert updates. Default is False.
  • pass_job_queue (optional[bool]) – If set to True, a keyword argument called job_queue will be passed to the callback function. It will be a JobQueue instance created by the Updater which can be used to schedule new jobs. Default is False.
  • pattern (optional[str or Pattern]) – Optional regex pattern. If not None re.match is used to determine if an update should be handled by this handler.
  • pass_groups (optional[bool]) – If the callback should be passed the result of re.match(pattern, data).groups() as a keyword argument called groups. Default is False
  • pass_groupdict (optional[bool]) – If the callback should be passed the result of re.match(pattern, data).groupdict() as a keyword argument called groupdict. Default is False
  • pass_user_data (optional[bool]) – If set to True, a keyword argument called user_data will be passed to the callback function. It will be a dict you can use to keep any data related to the user that sent the update. For each update of the same user, it will be the same dict. Default is False.
  • pass_chat_data (optional[bool]) – If set to True, a keyword argument called chat_data will be passed to the callback function. It will be a dict you can use to keep any data related to the chat that the update was sent in. For each update in the same chat, it will be the same dict. Default is False.
check_update(update)
handle_update(update, dispatcher)
class telegram.ext.ChosenInlineResultHandler(callback, pass_update_queue=False, pass_job_queue=False, pass_user_data=False, pass_chat_data=False)

Bases: telegram.ext.handler.Handler

Handler class to handle Telegram updates that contain a chosen inline result.

Parameters:
  • callback (function) – A function that takes bot, update as positional arguments. It will be called when the check_update has determined that an update should be processed by this handler.
  • pass_update_queue (optional[bool]) – If set to True, a keyword argument called update_queue will be passed to the callback function. It will be the Queue instance used by the Updater and Dispatcher that contains new updates which can be used to insert updates. Default is False.
  • pass_job_queue (optional[bool]) – If set to True, a keyword argument called job_queue will be passed to the callback function. It will be a JobQueue instance created by the Updater which can be used to schedule new jobs. Default is False.
  • pass_user_data (optional[bool]) – If set to True, a keyword argument called user_data will be passed to the callback function. It will be a dict you can use to keep any data related to the user that sent the update. For each update of the same user, it will be the same dict. Default is False.
  • pass_chat_data (optional[bool]) – If set to True, a keyword argument called chat_data will be passed to the callback function. It will be a dict you can use to keep any data related to the chat that the update was sent in. For each update in the same chat, it will be the same dict. Default is False.
checkUpdate(*args, **kwargs)
check_update(update)
handleUpdate(*args, **kwargs)
handle_update(update, dispatcher)
m = 'telegram.ChosenInlineResultHandler.'
class telegram.ext.CommandHandler(command, callback, filters=None, allow_edited=False, pass_args=False, pass_update_queue=False, pass_job_queue=False, pass_user_data=False, pass_chat_data=False)

Bases: telegram.ext.handler.Handler

Handler class to handle Telegram commands. Commands are Telegram messages that start with /, optionally followed by an @ and the bot’s name and/or some additional text.

Parameters:
  • command (str|list) – The name of the command or list of command this handler should listen for.
  • callback (function) – A function that takes bot, update as positional arguments. It will be called when the check_update has determined that an update should be processed by this handler.
  • filters (telegram.ext.BaseFilter) – A filter inheriting from telegram.ext.filters.BaseFilter. Standard filters can be found in telegram.ext.filters.Filters. Filters can be combined using bitwise operators (& for and, | for or).
  • allow_edited (Optional[bool]) – If the handler should also accept edited messages. Default is False
  • pass_args (optional[bool]) – If the handler should be passed the arguments passed to the command as a keyword argument called ` args. It will contain a list of strings, which is the text following the command split on single or consecutive whitespace characters. Default is False
  • pass_update_queue (optional[bool]) – If set to True, a keyword argument called update_queue will be passed to the callback function. It will be the Queue instance used by the Updater and Dispatcher that contains new updates which can be used to insert updates. Default is False.
  • pass_job_queue (optional[bool]) – If set to True, a keyword argument called job_queue will be passed to the callback function. It will be a JobQueue instance created by the Updater which can be used to schedule new jobs. Default is False.
  • pass_user_data (optional[bool]) – If set to True, a keyword argument called user_data will be passed to the callback function. It will be a dict you can use to keep any data related to the user that sent the update. For each update of the same user, it will be the same dict. Default is False.
  • pass_chat_data (optional[bool]) – If set to True, a keyword argument called chat_data will be passed to the callback function. It will be a dict you can use to keep any data related to the chat that the update was sent in. For each update in the same chat, it will be the same dict. Default is False.
check_update(update)
handle_update(update, dispatcher)
class telegram.ext.Handler(callback, pass_update_queue=False, pass_job_queue=False, pass_user_data=False, pass_chat_data=False)

Bases: object

The base class for all update handlers. You can create your own handlers by inheriting from this class.

Parameters:
  • callback (function) – A function that takes bot, update as positional arguments. It will be called when the check_update has determined that an update should be processed by this handler.
  • pass_update_queue (optional[bool]) – If set to True, a keyword argument called update_queue will be passed to the callback function. It will be the Queue instance used by the Updater and Dispatcher that contains new updates which can be used to insert updates. Default is False.
  • pass_job_queue (optional[bool]) – If set to True, a keyword argument called job_queue will be passed to the callback function. It will be a JobQueue instance created by the Updater which can be used to schedule new jobs. Default is False.
  • pass_user_data (optional[bool]) – If set to True, a keyword argument called user_data will be passed to the callback function. It will be a dict you can use to keep any data related to the user that sent the update. For each update of the same user, it will be the same dict. Default is False.
  • pass_chat_data (optional[bool]) – If set to True, a keyword argument called chat_data will be passed to the callback function. It will be a dict you can use to keep any data related to the chat that the update was sent in. For each update in the same chat, it will be the same dict. Default is False.
check_update(update)

This method is called to determine if an update should be handled by this handler instance. It should always be overridden.

Parameters:update (object) – The update to be tested
Returns:bool
collect_optional_args(dispatcher, update=None)

Prepares the optional arguments that are the same for all types of handlers

Parameters:dispatcher (telegram.ext.Dispatcher) –
handle_update(update, dispatcher)

This method is called if it was determined that an update should indeed be handled by this instance. It should also be overridden, but in most cases call self.callback(dispatcher.bot, update), possibly along with optional arguments. To work with the ConversationHandler, this method should return the value returned from self.callback

Parameters:
  • update (object) – The update to be handled
  • dispatcher (telegram.ext.Dispatcher) – The dispatcher to collect optional args
class telegram.ext.InlineQueryHandler(callback, pass_update_queue=False, pass_job_queue=False, pattern=None, pass_groups=False, pass_groupdict=False, pass_user_data=False, pass_chat_data=False)

Bases: telegram.ext.handler.Handler

Handler class to handle Telegram inline queries. Optionally based on a regex. Read the documentation of the re module for more information.

Parameters:
  • callback (function) – A function that takes bot, update as positional arguments. It will be called when the check_update has determined that an update should be processed by this handler.
  • pass_update_queue (optional[bool]) – If set to True, a keyword argument called update_queue will be passed to the callback function. It will be the Queue instance used by the Updater and Dispatcher that contains new updates which can be used to insert updates. Default is False.
  • pass_job_queue (optional[bool]) – If set to True, a keyword argument called job_queue will be passed to the callback function. It will be a JobQueue instance created by the Updater which can be used to schedule new jobs. Default is False.
  • pattern (optional[str or Pattern]) – Optional regex pattern. If not None re.match is used to determine if an update should be handled by this handler.
  • pass_groups (optional[bool]) – If the callback should be passed the result of re.match(pattern, query).groups() as a keyword argument called groups. Default is False
  • pass_groupdict (optional[bool]) – If the callback should be passed the result of re.match(pattern, query).groupdict() as a keyword argument called groupdict. Default is False
  • pass_user_data (optional[bool]) – If set to True, a keyword argument called user_data will be passed to the callback function. It will be a dict you can use to keep any data related to the user that sent the update. For each update of the same user, it will be the same dict. Default is False.
  • pass_chat_data (optional[bool]) – If set to True, a keyword argument called chat_data will be passed to the callback function. It will be a dict you can use to keep any data related to the chat that the update was sent in. For each update in the same chat, it will be the same dict. Default is False.
checkUpdate(*args, **kwargs)
check_update(update)
handleUpdate(*args, **kwargs)
handle_update(update, dispatcher)
m = 'telegram.InlineQueryHandler.'
class telegram.ext.MessageHandler(filters, callback, allow_edited=False, pass_update_queue=False, pass_job_queue=False, pass_user_data=False, pass_chat_data=False, message_updates=True, channel_post_updates=True, edited_updates=False)

Bases: telegram.ext.handler.Handler

Handler class to handle telegram messages. Messages are Telegram Updates that do not contain a command. They might contain text, media or status updates.

Parameters:
  • filters (telegram.ext.BaseFilter) – A filter inheriting from telegram.ext.filters.BaseFilter. Standard filters can be found in telegram.ext.filters.Filters. Filters can be combined using bitwise operators (& for and, | for or).
  • callback (function) – A function that takes bot, update as positional arguments. It will be called when the check_update has determined that an update should be processed by this handler.
  • pass_update_queue (optional[bool]) – If the handler should be passed the update queue as a keyword argument called update_queue. It can be used to insert updates. Default is False
  • pass_user_data (optional[bool]) – If set to True, a keyword argument called user_data will be passed to the callback function. It will be a dict you can use to keep any data related to the user that sent the update. For each update of the same user, it will be the same dict. Default is False.
  • pass_chat_data (optional[bool]) – If set to True, a keyword argument called chat_data will be passed to the callback function. It will be a dict you can use to keep any data related to the chat that the update was sent in. For each update in the same chat, it will be the same dict. Default is False.
  • message_updates (Optional[bool]) – Should “normal” message updates be handled? Default is True.
  • allow_edited (Optional[bool]) – If the handler should also accept edited messages. Default is False - Deprecated. use edited updates instead.
  • channel_post_updates (Optional[bool]) – Should channel posts updates be handled? Default is True.
  • edited_updates (Optional[bool]) – Should “edited” message updates be handled? Default is False.
check_update(update)
handle_update(update, dispatcher)
class telegram.ext.BaseFilter

Bases: object

Base class for all Message Filters

Subclassing from this class filters to be combined using bitwise operators:

And:

>>> (Filters.text & Filters.entity(MENTION))

Or:

>>> (Filters.audio | Filters.video)

Not:

>>> ~ Filters.command

Also works with more than two filters:

>>> (Filters.text & (Filters.entity(URL) | Filters.entity(TEXT_LINK)))
>>> Filters.text & (~ Filters.forwarded)

If you want to create your own filters create a class inheriting from this class and implement a filter method that returns a boolean: True if the message should be handled, False otherwise. Note that the filters work only as class instances, not actual class objects (so remember to initialize your filter classes).

filter(message)
class telegram.ext.Filters

Bases: object

Predefined filters for use with the filter argument of telegram.ext.MessageHandler.

all = <telegram.ext.filters._All object>
audio = <telegram.ext.filters._Audio object>
command = <telegram.ext.filters._Command object>
contact = <telegram.ext.filters._Contact object>
document = <telegram.ext.filters._Document object>
class entity(entity_type)

Bases: telegram.ext.filters.BaseFilter

Filters messages to only allow those which have a telegram.MessageEntity where their type matches entity_type.

Parameters:entity_type – Entity type to check for. All types can be found as constants in telegram.MessageEntity.

Returns: function to use as filter

filter(message)
Filters.forwarded = <telegram.ext.filters._Forwarded object>
Filters.game = <telegram.ext.filters._Game object>
Filters.group = <telegram.ext.filters._Group object>
class Filters.language(lang)

Bases: telegram.ext.filters.BaseFilter

Filters messages to only allow those which are from users with a certain language code. Note that according to telegrams documentation, every single user does not have the language_code attribute.

Parameters:lang (str|list) – Which language code(s) to allow through. This will be matched using .startswith meaning that ‘en’ will match both ‘en_US’ and ‘en_GB’
filter(message)
Filters.location = <telegram.ext.filters._Location object>
Filters.photo = <telegram.ext.filters._Photo object>
Filters.private = <telegram.ext.filters._Private object>
Filters.reply = <telegram.ext.filters._Reply object>
Filters.status_update = <telegram.ext.filters._StatusUpdate object>
Filters.sticker = <telegram.ext.filters._Sticker object>
Filters.text = <telegram.ext.filters._Text object>
Filters.venue = <telegram.ext.filters._Venue object>
Filters.video = <telegram.ext.filters._Video object>
Filters.voice = <telegram.ext.filters._Voice object>
class telegram.ext.RegexHandler(pattern, callback, pass_groups=False, pass_groupdict=False, pass_update_queue=False, pass_job_queue=False, pass_user_data=False, pass_chat_data=False, allow_edited=False, message_updates=True, channel_post_updates=False)

Bases: telegram.ext.handler.Handler

Handler class to handle Telegram updates based on a regex. It uses a regular expression to check text messages. Read the documentation of the re module for more information. The re.match function is used to determine if an update should be handled by this handler.

Parameters:
  • pattern (str or Pattern) – The regex pattern.
  • callback (function) – A function that takes bot, update as positional arguments. It will be called when the check_update has determined that an update should be processed by this handler.
  • pass_groups (optional[bool]) – If the callback should be passed the result of re.match(pattern, text).groups() as a keyword argument called groups. Default is False
  • pass_groupdict (optional[bool]) – If the callback should be passed the result of re.match(pattern, text).groupdict() as a keyword argument called groupdict. Default is False
  • pass_update_queue (optional[bool]) – If set to True, a keyword argument called update_queue will be passed to the callback function. It will be the Queue instance used by the Updater and Dispatcher that contains new updates which can be used to insert updates. Default is False.
  • pass_job_queue (optional[bool]) – If set to True, a keyword argument called job_queue will be passed to the callback function. It will be a JobQueue instance created by the Updater which can be used to schedule new jobs. Default is False.
  • pass_user_data (optional[bool]) – If set to True, a keyword argument called user_data will be passed to the callback function. It will be a dict you can use to keep any data related to the user that sent the update. For each update of the same user, it will be the same dict. Default is False.
  • pass_chat_data (optional[bool]) – If set to True, a keyword argument called chat_data will be passed to the callback function. It will be a dict you can use to keep any data related to the chat that the update was sent in. For each update in the same chat, it will be the same dict. Default is False.
checkUpdate(*args, **kwargs)
check_update(update)
handleUpdate(*args, **kwargs)
handle_update(update, dispatcher)
m = 'telegram.RegexHandler.'
class telegram.ext.StringCommandHandler(command, callback, pass_args=False, pass_update_queue=False, pass_job_queue=False)

Bases: telegram.ext.handler.Handler

Handler class to handle string commands. Commands are string updates that start with /.

Parameters:
  • command (str) – The name of the command this handler should listen for.
  • callback (function) – A function that takes bot, update as positional arguments. It will be called when the check_update has determined that an update should be processed by this handler.
  • pass_args (optional[bool]) – If the handler should be passed the arguments passed to the command as a keyword argument called ` args. It will contain a list of strings, which is the text following the command split on single or consecutive whitespace characters. Default is False
  • pass_update_queue (optional[bool]) – If set to True, a keyword argument called update_queue will be passed to the callback function. It will be the Queue instance used by the Updater and Dispatcher that contains new updates which can be used to insert updates. Default is False.
  • pass_job_queue (optional[bool]) – If set to True, a keyword argument called job_queue will be passed to the callback function. It will be a JobQueue instance created by the Updater which can be used to schedule new jobs. Default is False.
check_update(update)
handle_update(update, dispatcher)
class telegram.ext.StringRegexHandler(pattern, callback, pass_groups=False, pass_groupdict=False, pass_update_queue=False, pass_job_queue=False)

Bases: telegram.ext.handler.Handler

Handler class to handle string updates based on a regex. It uses a regular expression to check update content. Read the documentation of the re module for more information. The re.match function is used to determine if an update should be handled by this handler.

Parameters:
  • pattern (str or Pattern) – The regex pattern.
  • callback (function) – A function that takes bot, update as positional arguments. It will be called when the check_update has determined that an update should be processed by this handler.
  • pass_groups (optional[bool]) – If the callback should be passed the result of re.match(pattern, update).groups() as a keyword argument called groups. Default is False
  • pass_groupdict (optional[bool]) – If the callback should be passed the result of re.match(pattern, update).groupdict() as a keyword argument called groupdict. Default is False
  • pass_update_queue (optional[bool]) – If set to True, a keyword argument called update_queue will be passed to the callback function. It will be the Queue instance used by the Updater and Dispatcher that contains new updates which can be used to insert updates. Default is False.
  • pass_job_queue (optional[bool]) – If set to True, a keyword argument called job_queue will be passed to the callback function. It will be a JobQueue instance created by the Updater which can be used to schedule new jobs. Default is False.
check_update(update)
handle_update(update, dispatcher)
class telegram.ext.TypeHandler(type, callback, strict=False, pass_update_queue=False, pass_job_queue=False)

Bases: telegram.ext.handler.Handler

Handler class to handle updates of custom types.

Parameters:
  • type (type) – The type of updates this handler should process, as determined by isinstance
  • callback (function) – A function that takes bot, update as positional arguments. It will be called when the check_update has determined that an update should be processed by this handler.
  • strict (optional[bool]) – Use type instead of isinstance. Default is False
  • pass_update_queue (optional[bool]) – If set to True, a keyword argument called update_queue will be passed to the callback function. It will be the Queue instance used by the Updater and Dispatcher that contains new updates which can be used to insert updates. Default is False.
  • pass_job_queue (optional[bool]) – If set to True, a keyword argument called job_queue will be passed to the callback function. It will be a JobQueue instance created by the Updater which can be used to schedule new jobs. Default is False.
checkUpdate(*args, **kwargs)
check_update(update)
handleUpdate(*args, **kwargs)
handle_update(update, dispatcher)
m = 'telegram.TypeHandler.'
class telegram.ext.ConversationHandler(entry_points, states, fallbacks, allow_reentry=False, run_async_timeout=None, timed_out_behavior=None, per_chat=True, per_user=True, per_message=False)

Bases: telegram.ext.handler.Handler

A handler to hold a conversation with a single user by managing four collections of other handlers. Note that neither posts in Telegram Channels, nor group interactions with multiple users are managed by instances of this class.

The first collection, a list named entry_points, is used to initiate the conversation, for example with a CommandHandler or RegexHandler.

The second collection, a dict named states, contains the different conversation steps and one or more associated handlers that should be used if the user sends a message when the conversation with them is currently in that state. You will probably use mostly MessageHandler and RegexHandler here.

The third collection, a list named fallbacks, is used if the user is currently in a conversation but the state has either no associated handler or the handler that is associated to the state is inappropriate for the update, for example if the update contains a command, but a regular text message is expected. You could use this for a /cancel command or to let the user know their message was not recognized.

The fourth, optional collection of handlers, a list named timed_out_behavior is used if the wait for run_async takes longer than defined in run_async_timeout. For example, you can let the user know that they should wait for a bit before they can continue.

To change the state of conversation, the callback function of a handler must return the new state after responding to the user. If it does not return anything (returning None by default), the state will not change. To end the conversation, the callback function must return CallbackHandler.END or -1.

Parameters:
  • entry_points (list) – A list of Handler objects that can trigger the start of the conversation. The first handler which check_update method returns True will be used. If all return False, the update is not handled.
  • states (dict) – A dict[object: list[Handler]] that defines the different states of conversation a user can be in and one or more associated Handler objects that should be used in that state. The first handler which check_update method returns True will be used.
  • fallbacks (list) – A list of handlers that might be used if the user is in a conversation, but every handler for their current state returned False on check_update. The first handler which check_update method returns True will be used. If all return False, the update is not handled.
  • allow_reentry (Optional[bool]) – If set to True, a user that is currently in a conversation can restart the conversation by triggering one of the entry points.
  • run_async_timeout (Optional[float]) – If the previous handler for this user was running asynchronously using the run_async decorator, it might not be finished when the next message arrives. This timeout defines how long the conversation handler should wait for the next state to be computed. The default is None which means it will wait indefinitely.
  • timed_out_behavior (Optional[list]) – A list of handlers that might be used if the wait for run_async timed out. The first handler which check_update method returns True will be used. If all return False, the update is not handled.
END = -1
check_update(update)
handle_update(update, dispatcher)
update_state(new_state, key)