Module contents

Modules that work with the data section

class spotted.data.Application(*, bot, update_queue, updater, job_queue, update_processor, persistence, context_types, post_init, post_shutdown, post_stop)[source]

Bases: AbstractAsyncContextManager[Application], Generic[BT, CCT, UD, CD, BD, JQ]

This class dispatches all kinds of updates to its registered handlers, and is the entry point to a PTB application.

Tip

This class may not be initialized directly. Use telegram.ext.ApplicationBuilder or builder() (for convenience).

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()

See also

__aenter__() and __aexit__().

This class is a Generic class and accepts six type variables:

  1. The type of bot. Must be telegram.Bot or a subclass of that class.

  2. 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.

  3. The type of the values of user_data.

  4. The type of the values of chat_data.

  5. The type of bot_data.

  6. The type of job_queue. Must either be telegram.ext.JobQueue or a subclass of that or None.

Examples

Echo Bot

See also

Your First Bot <Extensions---Your-first-Bot>, Architecture Overview <Architecture>

Changed in version 20.0:

bot

The bot object that should be passed to the handlers.

Type:

telegram.Bot

update_queue

The synchronized queue that will contain the updates.

Type:

asyncio.Queue

updater

Optional. The updater used by this application.

Type:

telegram.ext.Updater

chat_data

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().

Type:

types.MappingProxyType

user_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().

Type:

types.MappingProxyType

bot_data

A dictionary handlers can use to store data for the bot.

Type:

dict

persistence

The persistence class to store data that should be persistent over restarts.

Type:

telegram.ext.BasePersistence

handlers

A dictionary mapping each handler group to the list of handlers registered to that group.

Type:

dict[int, list[telegram.ext.BaseHandler]]

error_handlers

A dictionary where the keys are error handlers and the values indicate whether they are to be run blocking.

Type:

dict[coroutine function, bool]

context_types

Specifies the types used by this dispatcher for the context argument of handler and job callbacks.

Type:

telegram.ext.ContextTypes

post_init

Optional. A callback that will be executed by Application.run_polling() and Application.run_webhook() after initializing the application via initialize().

Type:

coroutine function

post_shutdown

Optional. A callback that will be executed by Application.run_polling() and Application.run_webhook() after shutting down the application via shutdown().

Type:

coroutine function

post_stop

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.

Type:

coroutine function

add_error_handler(callback, block=True)[source]

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.

Examples

Errorhandler Bot

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.

See also

Exceptions, Warnings and Logging <Exceptions%2C-Warnings-and-Logging>

Parameters:
  • callback (Callable[[object, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])], Coroutine[Any, Any, None]]) –

    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 | DefaultValue[DVValueType], default: True) – Determines whether the return value of the callback should be awaited before processing the next error handler in process_error(). Defaults to True.

Return type:

None

add_handler(handler, group=0)[source]

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.

Parameters:
  • handler (BaseHandler[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any]) – A BaseHandler instance.

  • group (int, default: 0) – The group identifier. Default is 0.

Return type:

None

add_handlers(handlers, group=0)[source]

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.

Parameters:
  • handlers (Sequence[BaseHandler[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any]] | dict[int, Sequence[BaseHandler[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any]]]) –

    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 | DefaultValue[int], default: 0) – Specify which group the sequence of handlers should be added to. Defaults to 0.

Return type:

None

Example:

app.add_handlers(handlers={
    -1: [MessageHandler(...)],
    1: [CallbackQueryHandler(...), CommandHandler(...)]
}
Raises:

TypeError – If the combination of arguments is invalid.

bot: BT
bot_data: BD
static builder()[source]

Convenience method. Returns a new telegram.ext.ApplicationBuilder.

Added in version 20.0.

Return type:

ApplicationBuilder[ExtBot[None], CallbackContext[ExtBot[None], dict[Any, Any], dict[Any, Any], dict[Any, Any]], dict[Any, Any], dict[Any, Any], dict[Any, Any], JobQueue[CallbackContext[ExtBot[None], dict[Any, Any], dict[Any, Any], dict[Any, Any]]]]

chat_data: Mapping[int, CD]
property concurrent_updates: int

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.

See also

Concurrency

Type:

int

context_types: ContextTypes[CCT, UD, CD, BD]
create_task(coroutine, update=None, *, name=None)[source]

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().

See also

Concurrency

Parameters:
  • coroutine (Awaitable[TypeVar(RT)]) –

    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 | None, default: None) – 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.

Keyword Arguments:

name (str, optional) –

The name of the task.

Added in version 20.4.

Returns:

The created task.

Returns:

Task[TypeVar(RT)]

drop_chat_data(chat_id)[source]

Drops the corresponding entry from the chat_data. Will also be deleted from the persistence on the next run of update_persistence(), if applicable.

Warning

When using concurrent_updates or the job_queue, process_update() or telegram.ext.Job.run() may re-create this entry due to the asynchronous nature of these features. Please make sure that your program can avoid or handle such situations.

Added in version 20.0.

Parameters:

chat_id (int) – The chat id to delete. The entry will be deleted even if it is not empty.

Return type:

None

drop_user_data(user_id)[source]

Drops the corresponding entry from the user_data. Will also be deleted from the persistence on the next run of update_persistence(), if applicable.

Warning

When using concurrent_updates or the job_queue, process_update() or telegram.ext.Job.run() may re-create this entry due to the asynchronous nature of these features. Please make sure that your program can avoid or handle such situations.

Added in version 20.0.

Parameters:

user_id (int) – The user id to delete. The entry will be deleted even if it is not empty.

Return type:

None

error_handlers: dict[Callable[[object, CCT], Coroutine[Any, Any, None]], bool | DefaultValue[bool]]
handlers: dict[int, list[BaseHandler[Any, CCT, Any]]]
async initialize()[source]

Initializes the Application by initializing:

Does not call post_init - that is only done by run_polling() and run_webhook().

See also

shutdown()

Return type:

None

property job_queue: JobQueue[CCT] | None
The JobQueue used by the

telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

mark_data_for_update_persistence(chat_ids=None, user_ids=None)[source]

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.

Parameters:
Return type:

None

migrate_chat_data(message=None, old_chat_id=None, new_chat_id=None)[source]

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().

Warning

When using concurrent_updates or the job_queue, process_update() or telegram.ext.Job.run() may re-create the old entry due to the asynchronous nature of these features. Please make sure that your program can avoid or handle such situations.

See also

Storing Bot, User and Chat Related Data            <Storing-bot%2C-user-and-chat-related-data>

Parameters:
Raises:

ValueError – Raised if the input is invalid.

Return type:

None

persistence: BasePersistence[UD, CD, BD] | None
post_init: Callable[[Application[BT, CCT, UD, CD, BD, JQ]], Coroutine[Any, Any, None]] | None
post_shutdown: Callable[[Application[BT, CCT, UD, CD, BD, JQ]], Coroutine[Any, Any, None]] | None
post_stop: Callable[[Application[BT, CCT, UD, CD, BD, JQ]], Coroutine[Any, Any, None]] | None
async process_error(update, error, job=None, coroutine=None)[source]

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.

Changed in version 20.0:

Parameters:
  • update (object | None) – The update that caused the error.

  • error (Exception) – The error that was raised.

  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])] | None, default: None) –

    The job that caused the error.

    Added in version 20.0.

  • coroutine (Awaitable[TypeVar(RT)] | None, default: None) – The coroutine that caused the error.

Returns:

True, if one of the error handlers raised telegram.ext.ApplicationHandlerStop. False, otherwise.

Returns:

bool

async process_update(update)[source]

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().

See also

Concurrency

Changed in version 20.0: Persistence is now updated in an interval set by telegram.ext.BasePersistence.update_interval.

Parameters:

update (object) – The update to process.

Raises:

RuntimeError – If the application was not initialized.

Return type:

None

remove_error_handler(callback)[source]

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.

Parameters:

callback (Callable[[object, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])], Coroutine[Any, Any, None]]) – The error handler to remove.

Return type:

None

remove_handler(handler, group=0)[source]

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.

Parameters:
Return type:

None

run_polling(poll_interval=0.0, timeout=datetime.timedelta(seconds=10), bootstrap_retries=0, allowed_updates=None, drop_pending_updates=None, close_loop=True, stop_signals=None)[source]

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.

|app_run_shutdown| stop_signals.

The order of execution by run_polling() is roughly as follows:

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

For more information on running a Telegram bot application, see the python-telegram-bot documentation.

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.

Parameters:
Raises:

RuntimeError – If the Application does not have an telegram.ext.Updater.

Return type:

None

run_webhook(listen='127.0.0.1', port=80, url_path='', cert=None, key=None, bootstrap_retries=0, webhook_url=None, allowed_updates=None, drop_pending_updates=None, ip_address=None, max_connections=40, close_loop=True, stop_signals=None, secret_token=None, unix=None)[source]

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.

|app_run_shutdown| 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:

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

For more information on running a Telegram bot application, see the python-telegram-bot documentation.

See also

Webhooks

Parameters:
  • listen (str | DefaultValue[DVValueType], default: '127.0.0.1') – IP-Address to listen on. Defaults to 127.0.0.1.

  • port (int | DefaultValue[DVValueType], default: 80) – 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, default: '') – Path inside url. Defaults to `` ‘’ ``

  • cert (str | Path | None, default: None) – Path to the SSL certificate file.

  • key (str | Path | None, default: None) – Path to the SSL key file.

  • bootstrap_retries (int, default: 0) –

    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 | None, default: None) – 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] | None, default: None) –

    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 | None, default: None) – Whether to clean any pending updates on Telegram servers before actually starting to poll. Default is False.

  • ip_address (str | None, default: None) – Passed to telegram.Bot.set_webhook().

  • max_connections (int, default: 40) – Passed to telegram.Bot.set_webhook(). Defaults to 40.

  • close_loop (bool, default: True) –

    If True, the current event loop will be closed upon shutdown. Defaults to True.

  • stop_signals (DefaultValue[DVValueType] | Sequence[int] | DefaultValue[None] | None, default: None) –

    Signals that will shut down the app. Pass None to not use stop signals. Defaults to signal.SIGINT, signal.SIGTERM and signal.SIGABRT.

    Caution

    Not every asyncio.AbstractEventLoop implements asyncio.loop.add_signal_handler(). Most notably, the standard event loop on Windows, asyncio.ProactorEventLoop, does not implement this method. If this method is not available, stop signals can not be set.

  • secret_token (str | None, default: None) –

    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 (str | Path | socket | None, default: None) –

    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.

Return type:

None

property running: bool

Indicates if this application is running.

See also

start(), stop()

Type:

bool

async shutdown()[source]

Shuts down the Application by shutting down:

Does not call post_shutdown - that is only done by run_polling() and run_webhook().

See also

initialize()

Raises:

RuntimeError – If the application is still running.

Return type:

None

async start()[source]

Starts

Note

This does not start fetching updates from Telegram. To fetch updates, you need to either start updater manually or use one of run_polling() or run_webhook().

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.

See also

stop()

Raises:

RuntimeError – If the application is already running or was not initialized.

Return type:

None

async stop()[source]

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.

See also

start()

Note

Raises:

RuntimeError – If the application is not running.

Return type:

None

stop_running()[source]

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().

Return type:

None

async update_persistence()[source]

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.

Return type:

None

property update_processor: BaseUpdateProcessor

The update processor used by this application.

See also

Concurrency

Added in version 20.4.

Type:

telegram.ext.BaseUpdateProcessor

update_queue: Queue[object]
updater: Updater | None
user_data: Mapping[int, UD]
class spotted.data.Config[source]

Bases: object

Configurations

AUTOREPLIES_PATH = 'autoreplies.yaml'
DEFAULT_AUTOREPLIES_PATH = '/opt/hostedtoolcache/Python/3.14.3/x64/lib/python3.14/site-packages/spotted/config/yaml/autoreplies.yaml'
DEFAULT_SETTINGS_PATH = '/opt/hostedtoolcache/Python/3.14.3/x64/lib/python3.14/site-packages/spotted/config/yaml/settings.yaml'
SETTINGS_PATH = 'settings.yaml'
classmethod autoreplies_get(*keys, default=None)[source]

Get the value of the specified key in the autoreplies configuration dictionary. If the key is a tuple, it will return the value of the nested key. If the key is not present, it will return the default value.

Parameters:
  • key – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

dict – value of the key or default value

classmethod debug_get(key, default=None)[source]

Get the value of the specified key in the configuration under the ‘debug’ section. If the key is not present, it will return the default value.

Parameters:
  • key (Literal['local_log', 'reset_on_load', 'log_file', 'log_error_file', 'db_file', 'backup_chat_id', 'backup_keep_pending', 'crypto_key', 'zip_backup']) – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

Any – value of the key or default value

classmethod override_settings(config)[source]

Overrides the settings with the configuration provided in the config dict.

Parameters:

config (dict) – configuration dict used to override the current settings

classmethod post_get(key, default=None)[source]

Get the value of the specified key in the configuration under the ‘post’ section. If the key is not present, it will return the default value.

Parameters:
  • key (Literal['community_group_id', 'channel_id', 'channel_tag', 'comments', 'admin_group_id', 'n_votes', 'remove_after_h', 'report', 'report_wait_mins', 'replace_anonymous_comments', 'delete_anonymous_comments', 'blacklist_messages', 'max_n_warns', 'warn_expiration_days', 'mute_default_duration_days', 'autoreplies_per_page', 'reject_after_autoreply']) – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

Any – value of the key or default value

classmethod reload(force_reload=False)[source]

Reset the configuration. The next time a setting parameter is required, the whole configuration will be reloaded. If force_reload is True, the configuration will be reloaded immediately.

Parameters:

force_reload (bool, default: False) – if True, the configuration will be reloaded immediately

classmethod settings_get(*keys, default=None)[source]

Get the value of the specified key in the configuration. If the key is a tuple, it will return the value of the nested key. If the key is not present, it will return the default value.

Parameters:
  • key – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

Any – value of the key or default value

class spotted.data.DbManager[source]

Bases: object

Class that handles the management of databases

classmethod count_from(table_name, select='*', where='', where_args=None)[source]

Returns the number of rows found with the query. Executes “SELECT COUNT(select) FROM table_name [WHERE where (with where_args)]”

Parameters:
  • table_name (str) – name of the table used in the FROM

  • select (str, default: '*') – columns considered for the query

  • where (str, default: '') – where clause, with %s placeholders for the where_args

  • where_args (tuple | None, default: None) – args used in the where clause

Returns:

int – number of rows

classmethod delete_from(table_name, where='', where_args=None)[source]

Deletes the rows from the specified table, where the condition, when set, is satisfied. Executes “DELETE FROM table_name [WHERE where (with where_args)]”

Parameters:
  • table_name (str) – name of the table used in the DELETE FROM

  • where (str, default: '') – where clause, with %s placeholders for the where args

  • where_args (tuple | None, default: None) – args used in the where clause

classmethod get_db()[source]

Creates the connection to the database. It can be sqlite or postgres

Returns:

tuple[Connection, Cursor] – sqlite database connection and cursor

classmethod insert_into(table_name, values, columns='', multiple_rows=False)[source]

Inserts the specified values in the database. Executes “INSERT INTO table_name ([columns]) VALUES (placeholders)”

Parameters:
  • table_name (str) – name of the table used in the INSERT INTO

  • values (tuple) – values to be inserted. If multiple_rows is true, tuple of tuples of values to be inserted

  • columns (tuple | str, default: '') – columns that will be inserted, as a tuple of strings

  • multiple_rows (bool, default: False) – whether or not multiple rows will be inserted at the same time

classmethod query_from_file(*file_path)[source]

Commits all the queries in the specified file. The queries must be separated by a —– string Should not be used to select something

Parameters:

file_path (str) – path of the text file containing the queries

classmethod query_from_string(*queries)[source]

Commits all the queries in the string Should not be used to select something

Parameters:

queries (str) – tuple of queries

static register_adapters_and_converters()[source]

Registers the adapter and converters for the datetime type. Needed from python 3.12 onwards, as the default option has been deprecated

static row_factory(cursor, row)[source]

Converts the rows from the database into a dictionary

Parameters:
  • cursor (Cursor) – database cursor

  • row (dict) – row from the database

Returns:

dict – dictionary containing the row. The keys are the column names

classmethod select_from(table_name, select='*', where='', where_args=None, group_by='', order_by='')[source]

Returns the results of a query. Executes “SELECT select FROM table_name [WHERE where (with where_args)] [GROUP_BY group_by] [ORDER BY order_by]”

Parameters:
  • table_name (str) – name of the table used in the FROM

  • select (str, default: '*') – columns considered for the query

  • where (str, default: '') – where clause, with %s placeholders for the where_args

  • where_args (tuple | None, default: None) – args used in the where clause

  • group_by (str, default: '') – group by clause

  • order_by (str, default: '') – order by clause

Returns:

list – rows from the select

classmethod update_from(table_name, set_clause, where='', args=None)[source]

Updates the rows from the specified table, where the condition, when set, is satisfied. Executes “UPDATE table_name SET set_clause (with args) [WHERE where (with args)]”

Parameters:
  • table_name (str) – name of the table used in the DELETE FROM

  • set_clause (str) – set clause, with %s placeholders

  • where (str, default: '') – where clause, with %s placeholders for the where args

  • args (tuple | None, default: None) – args used both in the set clause and in the where clause, in this order

class spotted.data.PendingPost(user_id, u_message_id, g_message_id, admin_group_id, date, credit_username=None)[source]

Bases: object

Class that represents a pending post

Parameters:
  • user_id (int) – id of the user that sent the post

  • u_message_id (int) – id of the original message of the post

  • g_message_id (int) – id of the post in the group

  • admin_group_id (int) – id of the admin group

  • credit_username (str | None, default: None) – username of the user that sent the post if it’s a credit post

  • date (datetime) – when the post was sent

admin_group_id: int
classmethod create(user_message, g_message_id, admin_group_id, credit_username=None)[source]

Creates a new post and inserts it in the table of pending posts

Parameters:
  • user_message (Message) – message sent by the user that contains the post

  • g_message_id (int) – id of the post in the group

  • admin_group_id (int) – id of the admin group

  • credit_username (str | None, default: None) – username of the user that sent the post if it’s a credit post

Returns:

PendingPost – instance of the class

credit_username: str | None = None
date: datetime
delete_post()[source]

Removes all entries on a post that is no longer pending

classmethod from_group(g_message_id, admin_group_id)[source]

Retrieves a pending post from the info related to the admin group

Parameters:
  • g_message_id (int) – id of the post in the group

  • admin_group_id (int) – id of the admin group

Returns:

PendingPost | None – instance of the class

classmethod from_user(user_id)[source]

Retrieves a pending post from the user_id

Parameters:

user_id (int) – id of the author of the post

Returns:

PendingPost | None – instance of the class

g_message_id: int
static get_all(admin_group_id, before=None)[source]

Gets the list of pending posts in the specified admin group. If before is specified, returns only the one sent before that timestamp

Parameters:
  • admin_group_id (int) – id of the admin group

  • before (datetime | None, default: None) – timestamp before which messages will be considered

Returns:

list[PendingPost] – list of ids of pending posts

get_credit_username()[source]

Gets the username of the user that credited the post

Returns:

str | None – username of the user that credited the post, or None if the post is not credited

get_list_admin_votes(vote=None)[source]

Gets the list of admins that approved or rejected the post

Parameters:

vote (bool | None, default: None) – whether you look for the approve or reject votes, or None if you want all the votes

Returns:

list[int] | list[tuple[int, bool]] – list of admins that approved or rejected a pending post

get_votes(vote)[source]

Gets all the votes of a specific kind (approve or reject)

Parameters:

vote (bool) – whether you look for the approve or reject votes

Returns:

int – number of votes

save_post()[source]

Saves the pending_post in the database

Return type:

PendingPost

set_admin_vote(admin_id, approval)[source]

Adds the vote of the admin on a specific post, or update the existing vote, if needed

Parameters:
  • admin_id (int) – id of the admin that voted

  • approval (bool) – whether the vote is approval or reject

Returns:

int – number of similar votes (all the approve or the reject), or -1 if the vote wasn’t updated

u_message_id: int
user_id: int
class spotted.data.PostData[source]

Bases: object

Class that handles the management of persistent data fetch or manipulation in the post bot

static get_n_posts()[source]

Gets the total number of posts

Returns:

int – total number of posts

class spotted.data.PublishedPost(channel_id, c_message_id, date)[source]

Bases: object

Class that represents a published post

Parameters:
  • channel_id (int) – id of the channel

  • c_message_id (int) – id of the post in the channel

c_message_id: int
channel_id: int
classmethod create(channel_id, c_message_id)[source]

Inserts a new post in the table of published posts

Parameters:
  • channel_id (int) – id of the channel

  • c_message_id (int) – id of the post in the channel

Returns:

PublishedPost – instance of the class

date: datetime
classmethod from_channel(channel_id, c_message_id)[source]

Retrieves a published post from the info related to the channel

Parameters:
  • channel_id (int) – id of the channel

  • c_message_id (int) – id of the post in the channel

Returns:

PublishedPost | None – instance of the class

save_post()[source]

Saves the published_post in the database

Return type:

PublishedPost

class spotted.data.Report(user_id, admin_group_id, g_message_id, channel_id=None, c_message_id=None, target_username=None, date=None)[source]

Bases: object

Class that represents a report

Parameters:
  • user_id (int) – id of the user that reported

  • admin_group_id (int) – id of the admin group

  • g_message_id (int) – id of the post in the group

  • channel_id (int | None, default: None) – id of the channel

  • c_message_id (int | None, default: None) – id of the post in question in the channel

  • target_username (str | None, default: None) – username of the reported user

  • date (datetime | None, default: None) – when the report happened

admin_group_id: int
c_message_id: int | None = None
channel_id: int | None = None
classmethod create_post_report(user_id, channel_id, c_message_id, admin_message)[source]

Adds the report of the user on a specific post

Parameters:
  • user_id (int) – id of the user that reported

  • channel_id (int) – id of the channel

  • c_message_id (int) – id of the post in question in the channel

  • admin_message (Message) – message received in the admin group that references the report

Returns:

Report | None – instance of the class or None if the report was not created

classmethod create_user_report(user_id, target_username, admin_message)[source]

Adds the report of the user targeting another user

Parameters:
  • user_id (int) – id of the user that reported

  • target_username (str) – username of reported user

  • admin_message (Message) – message received in the admin group that references the report

Returns:

Report – instance of the class

date: datetime | None = None
classmethod from_group(admin_group_id, g_message_id)[source]

Gets a report of any type related to the specified message in the admin group

Parameters:
  • admin_group_id (int) – id of the admin group

  • g_message_id (int) – id of the report in the group

Returns:

Report | None – instance of the class or None if the report was not present

g_message_id: int
classmethod get_last_user_report(user_id)[source]

Gets the last user report of a specific user

Parameters:

user_id (int) – id of the user that reported

Returns:

Report | None – instance of the class or None if the report was not present

classmethod get_post_report(user_id, channel_id, c_message_id)[source]

Gets the report of a specific user on a published post

Parameters:
  • user_id (int) – id of the user that reported

  • channel_id (int) – id of the channel

  • c_message_id (int) – id of the post in question in the channel

Returns:

Report | None – instance of the class or None if the report was not present

property minutes_passed: float

Amount of minutes elapsed from when the report was submitted, if applicable

Type:

float

save_report()[source]

Saves the report in the database

Return type:

Report

target_username: str | None = None
user_id: int
class spotted.data.User(user_id, private_message_id=None, ban_date=None, mute_date=None, mute_expire_date=None, follow_date=None)[source]

Bases: object

Class that represents a user

Parameters:
  • user_id (int) – id of the user

  • private_message_id (int | None, default: None) – id of the private message sent by the user to the bot. Only used for following

  • ban_date (datetime | None, default: None) – datetime of when the user was banned. Only used for banned users

  • follow_date (datetime | None, default: None) – datetime of when the user started following a post. Only used for following users

ban()[source]

Adds the user to the banned list

ban_date: datetime | None = None
classmethod banned_users()[source]

Returns a list of all the banned users

Return type:

list[User]

become_anonym()[source]

Removes the user from the credited list, if he was present

Returns:

bool – whether the user was already anonym

become_credited()[source]

Adds the user to the credited list, if he wasn’t already credited

Returns:

bool – whether the user was already credited

classmethod credited_users()[source]

Returns a list of all the credited users

Return type:

list[User]

follow_date: datetime | None = None
classmethod following_users(message_id)[source]

Returns a list of all the users following the post with the associated private message id used by the bot to send updates about the post by replying to it

Parameters:

message_id (int) – id of the post the users are following

Returns:

list[User] – list of users with private_message_id set to the id of the private message in the user’s conversation with the bot

get_follow_private_message_id(message_id)[source]

Verifies if the user is following a post

Parameters:

message_id (int) – id of the post

Returns:

int | None – whether the user is following the post or not

get_n_warns()[source]

Returns the count of consecutive warns of the user

Return type:

int

async get_user_sign(bot)[source]

Generates a sign for the user. It will be a random name for an anonym user

Parameters:

bot (Bot) – telegram bot

Returns:

str – the sign of the user

property is_banned: bool

If the user is banned or not

property is_credited: bool

If the user is in the credited list

is_following(message_id)[source]

Verifies if the user is following a post

Parameters:

message_id (int) – id of the post

Returns:

bool – whether the user is following the post or not

property is_muted: bool

If the user is muted or not

property is_pending: bool

If the user has a post already pending or not

property is_warn_bannable: bool

If the user is bannable due to warns

async mute(bot, days)[source]

Mute a user restricting its actions inside the community group

Parameters:
  • bot (Bot | None) – the telegram bot

  • days (int) – The number of days the user should be muted for.

mute_date: datetime | None = None
mute_expire_date: datetime | None = None
classmethod muted_users()[source]

Returns a list of all the muted users

Return type:

list[User]

private_message_id: int | None = None
sban()[source]

Removes the user from the banned list

Returns:

bool – whether the user was present in the banned list before the sban or not

set_follow(message_id, private_message_id)[source]

Sets the follow status of the user. If the private_message_id is None, the user is not following the post anymore, and the record is deleted from the database. Otherwise, the user is following the post and a new record is created.

Parameters:
  • message_id (int) – id of the post

  • private_message_id (int | None) – id of the private message. If None, the record is deleted

async unmute(bot)[source]

Unmute a user taking back all restrictions

Parameters:

bot (Bot | None) – the telegram bot

Returns:

bool – whether the user was muted before the unmute or not

user_id: int
warn()[source]

Increase the number of warns of a user If the number of warns is greater than the maximum allowed, the user is banned

Parameters:

bot – the telegram bot

spotted.data.get_abs_path(*root_file_path)[source]

Get the abs path from the root directory of the project to the requested path

Parameters:

root_file_path (str) – path from the root project directory

Returns:

str – corresponding abs path

spotted.data.read_md(file_name)[source]

Read the contents of a markdown file. The path is data/markdown. It also will replace the following parts of the text:

  • {channel_tag} -> Config.settings[‘post’][‘channel_tag’]

  • {bot_tag} -> Config.settings[‘bot_tag’]

Parameters:

file_name (str) – name of the file

Returns:

str – contents of the file

spotted.data package

Submodules

spotted.data.config module

Read the bot configuration from the settings.yaml and the autoreplies.yaml files

class spotted.data.config.Any(*args, **kwargs)[source]

Bases: object

Special type indicating an unconstrained type.

  • Any is compatible with every type.

  • Any assumed to have all methods.

  • All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.

class spotted.data.config.Config[source]

Bases: object

Configurations

AUTOREPLIES_PATH = 'autoreplies.yaml'
DEFAULT_AUTOREPLIES_PATH = '/opt/hostedtoolcache/Python/3.14.3/x64/lib/python3.14/site-packages/spotted/config/yaml/autoreplies.yaml'
DEFAULT_SETTINGS_PATH = '/opt/hostedtoolcache/Python/3.14.3/x64/lib/python3.14/site-packages/spotted/config/yaml/settings.yaml'
SETTINGS_PATH = 'settings.yaml'
classmethod autoreplies_get(*keys, default=None)[source]

Get the value of the specified key in the autoreplies configuration dictionary. If the key is a tuple, it will return the value of the nested key. If the key is not present, it will return the default value.

Parameters:
  • key – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

dict – value of the key or default value

classmethod debug_get(key, default=None)[source]

Get the value of the specified key in the configuration under the ‘debug’ section. If the key is not present, it will return the default value.

Parameters:
  • key (Literal['local_log', 'reset_on_load', 'log_file', 'log_error_file', 'db_file', 'backup_chat_id', 'backup_keep_pending', 'crypto_key', 'zip_backup']) – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

Any – value of the key or default value

classmethod override_settings(config)[source]

Overrides the settings with the configuration provided in the config dict.

Parameters:

config (dict) – configuration dict used to override the current settings

classmethod post_get(key, default=None)[source]

Get the value of the specified key in the configuration under the ‘post’ section. If the key is not present, it will return the default value.

Parameters:
  • key (Literal['community_group_id', 'channel_id', 'channel_tag', 'comments', 'admin_group_id', 'n_votes', 'remove_after_h', 'report', 'report_wait_mins', 'replace_anonymous_comments', 'delete_anonymous_comments', 'blacklist_messages', 'max_n_warns', 'warn_expiration_days', 'mute_default_duration_days', 'autoreplies_per_page', 'reject_after_autoreply']) – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

Any – value of the key or default value

classmethod reload(force_reload=False)[source]

Reset the configuration. The next time a setting parameter is required, the whole configuration will be reloaded. If force_reload is True, the configuration will be reloaded immediately.

Parameters:

force_reload (bool, default: False) – if True, the configuration will be reloaded immediately

classmethod settings_get(*keys, default=None)[source]

Get the value of the specified key in the configuration. If the key is a tuple, it will return the value of the nested key. If the key is not present, it will return the default value.

Parameters:
  • key – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

Any – value of the key or default value

spotted.data.data_reader module

Read data from files

class spotted.data.data_reader.Config[source]

Bases: object

Configurations

AUTOREPLIES_PATH = 'autoreplies.yaml'
DEFAULT_AUTOREPLIES_PATH = '/opt/hostedtoolcache/Python/3.14.3/x64/lib/python3.14/site-packages/spotted/config/yaml/autoreplies.yaml'
DEFAULT_SETTINGS_PATH = '/opt/hostedtoolcache/Python/3.14.3/x64/lib/python3.14/site-packages/spotted/config/yaml/settings.yaml'
SETTINGS_PATH = 'settings.yaml'
classmethod autoreplies_get(*keys, default=None)[source]

Get the value of the specified key in the autoreplies configuration dictionary. If the key is a tuple, it will return the value of the nested key. If the key is not present, it will return the default value.

Parameters:
  • key – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

dict – value of the key or default value

classmethod debug_get(key, default=None)[source]

Get the value of the specified key in the configuration under the ‘debug’ section. If the key is not present, it will return the default value.

Parameters:
  • key (Literal['local_log', 'reset_on_load', 'log_file', 'log_error_file', 'db_file', 'backup_chat_id', 'backup_keep_pending', 'crypto_key', 'zip_backup']) – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

Any – value of the key or default value

classmethod override_settings(config)[source]

Overrides the settings with the configuration provided in the config dict.

Parameters:

config (dict) – configuration dict used to override the current settings

classmethod post_get(key, default=None)[source]

Get the value of the specified key in the configuration under the ‘post’ section. If the key is not present, it will return the default value.

Parameters:
  • key (Literal['community_group_id', 'channel_id', 'channel_tag', 'comments', 'admin_group_id', 'n_votes', 'remove_after_h', 'report', 'report_wait_mins', 'replace_anonymous_comments', 'delete_anonymous_comments', 'blacklist_messages', 'max_n_warns', 'warn_expiration_days', 'mute_default_duration_days', 'autoreplies_per_page', 'reject_after_autoreply']) – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

Any – value of the key or default value

classmethod reload(force_reload=False)[source]

Reset the configuration. The next time a setting parameter is required, the whole configuration will be reloaded. If force_reload is True, the configuration will be reloaded immediately.

Parameters:

force_reload (bool, default: False) – if True, the configuration will be reloaded immediately

classmethod settings_get(*keys, default=None)[source]

Get the value of the specified key in the configuration. If the key is a tuple, it will return the value of the nested key. If the key is not present, it will return the default value.

Parameters:
  • key – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

Any – value of the key or default value

spotted.data.data_reader.escape_markdown(text, version=1, entity_type=None)[source]

Helper function to escape telegram markup symbols.

Changed in version 20.3: Custom emoji entity escaping is now supported.

Parameters:
  • text (str) – The text.

  • version (Literal[1, 2], default: 1) – Use to specify the version of telegrams Markdown. Either 1 or 2. Defaults to 1.

  • entity_type (str | None, default: None) – For the entity types telegram.MessageEntity.PRE, telegram.MessageEntity.CODE and the link part of telegram.MessageEntity.TEXT_LINK and telegram.MessageEntity.CUSTOM_EMOJI, only certain characters need to be escaped in telegram.constants.ParseMode.MARKDOWN_V2. See the official API documentation for details. Only valid in combination with version=2, will be ignored else.

Return type:

str

spotted.data.data_reader.get_abs_path(*root_file_path)[source]

Get the abs path from the root directory of the project to the requested path

Parameters:

root_file_path (str) – path from the root project directory

Returns:

str – corresponding abs path

spotted.data.data_reader.read_file(*root_file_path)[source]

Read the contents of the file

Parameters:

root_file_path (str) – path of the file to read from the root project directory

Returns:

str – contents of the file

spotted.data.data_reader.read_md(file_name)[source]

Read the contents of a markdown file. The path is data/markdown. It also will replace the following parts of the text:

  • {channel_tag} -> Config.settings[‘post’][‘channel_tag’]

  • {bot_tag} -> Config.settings[‘bot_tag’]

Parameters:

file_name (str) – name of the file

Returns:

str – contents of the file

spotted.data.db_manager module

Handles the management of databases

class spotted.data.db_manager.Config[source]

Bases: object

Configurations

AUTOREPLIES_PATH = 'autoreplies.yaml'
DEFAULT_AUTOREPLIES_PATH = '/opt/hostedtoolcache/Python/3.14.3/x64/lib/python3.14/site-packages/spotted/config/yaml/autoreplies.yaml'
DEFAULT_SETTINGS_PATH = '/opt/hostedtoolcache/Python/3.14.3/x64/lib/python3.14/site-packages/spotted/config/yaml/settings.yaml'
SETTINGS_PATH = 'settings.yaml'
classmethod autoreplies_get(*keys, default=None)[source]

Get the value of the specified key in the autoreplies configuration dictionary. If the key is a tuple, it will return the value of the nested key. If the key is not present, it will return the default value.

Parameters:
  • key – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

dict – value of the key or default value

classmethod debug_get(key, default=None)[source]

Get the value of the specified key in the configuration under the ‘debug’ section. If the key is not present, it will return the default value.

Parameters:
  • key (Literal['local_log', 'reset_on_load', 'log_file', 'log_error_file', 'db_file', 'backup_chat_id', 'backup_keep_pending', 'crypto_key', 'zip_backup']) – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

Any – value of the key or default value

classmethod override_settings(config)[source]

Overrides the settings with the configuration provided in the config dict.

Parameters:

config (dict) – configuration dict used to override the current settings

classmethod post_get(key, default=None)[source]

Get the value of the specified key in the configuration under the ‘post’ section. If the key is not present, it will return the default value.

Parameters:
  • key (Literal['community_group_id', 'channel_id', 'channel_tag', 'comments', 'admin_group_id', 'n_votes', 'remove_after_h', 'report', 'report_wait_mins', 'replace_anonymous_comments', 'delete_anonymous_comments', 'blacklist_messages', 'max_n_warns', 'warn_expiration_days', 'mute_default_duration_days', 'autoreplies_per_page', 'reject_after_autoreply']) – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

Any – value of the key or default value

classmethod reload(force_reload=False)[source]

Reset the configuration. The next time a setting parameter is required, the whole configuration will be reloaded. If force_reload is True, the configuration will be reloaded immediately.

Parameters:

force_reload (bool, default: False) – if True, the configuration will be reloaded immediately

classmethod settings_get(*keys, default=None)[source]

Get the value of the specified key in the configuration. If the key is a tuple, it will return the value of the nested key. If the key is not present, it will return the default value.

Parameters:
  • key – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

Any – value of the key or default value

class spotted.data.db_manager.DbManager[source]

Bases: object

Class that handles the management of databases

classmethod count_from(table_name, select='*', where='', where_args=None)[source]

Returns the number of rows found with the query. Executes “SELECT COUNT(select) FROM table_name [WHERE where (with where_args)]”

Parameters:
  • table_name (str) – name of the table used in the FROM

  • select (str, default: '*') – columns considered for the query

  • where (str, default: '') – where clause, with %s placeholders for the where_args

  • where_args (tuple | None, default: None) – args used in the where clause

Returns:

int – number of rows

classmethod delete_from(table_name, where='', where_args=None)[source]

Deletes the rows from the specified table, where the condition, when set, is satisfied. Executes “DELETE FROM table_name [WHERE where (with where_args)]”

Parameters:
  • table_name (str) – name of the table used in the DELETE FROM

  • where (str, default: '') – where clause, with %s placeholders for the where args

  • where_args (tuple | None, default: None) – args used in the where clause

classmethod get_db()[source]

Creates the connection to the database. It can be sqlite or postgres

Returns:

tuple[Connection, Cursor] – sqlite database connection and cursor

classmethod insert_into(table_name, values, columns='', multiple_rows=False)[source]

Inserts the specified values in the database. Executes “INSERT INTO table_name ([columns]) VALUES (placeholders)”

Parameters:
  • table_name (str) – name of the table used in the INSERT INTO

  • values (tuple) – values to be inserted. If multiple_rows is true, tuple of tuples of values to be inserted

  • columns (tuple | str, default: '') – columns that will be inserted, as a tuple of strings

  • multiple_rows (bool, default: False) – whether or not multiple rows will be inserted at the same time

classmethod query_from_file(*file_path)[source]

Commits all the queries in the specified file. The queries must be separated by a —– string Should not be used to select something

Parameters:

file_path (str) – path of the text file containing the queries

classmethod query_from_string(*queries)[source]

Commits all the queries in the string Should not be used to select something

Parameters:

queries (str) – tuple of queries

static register_adapters_and_converters()[source]

Registers the adapter and converters for the datetime type. Needed from python 3.12 onwards, as the default option has been deprecated

static row_factory(cursor, row)[source]

Converts the rows from the database into a dictionary

Parameters:
  • cursor (Cursor) – database cursor

  • row (dict) – row from the database

Returns:

dict – dictionary containing the row. The keys are the column names

classmethod select_from(table_name, select='*', where='', where_args=None, group_by='', order_by='')[source]

Returns the results of a query. Executes “SELECT select FROM table_name [WHERE where (with where_args)] [GROUP_BY group_by] [ORDER BY order_by]”

Parameters:
  • table_name (str) – name of the table used in the FROM

  • select (str, default: '*') – columns considered for the query

  • where (str, default: '') – where clause, with %s placeholders for the where_args

  • where_args (tuple | None, default: None) – args used in the where clause

  • group_by (str, default: '') – group by clause

  • order_by (str, default: '') – order by clause

Returns:

list – rows from the select

classmethod update_from(table_name, set_clause, where='', args=None)[source]

Updates the rows from the specified table, where the condition, when set, is satisfied. Executes “UPDATE table_name SET set_clause (with args) [WHERE where (with args)]”

Parameters:
  • table_name (str) – name of the table used in the DELETE FROM

  • set_clause (str) – set clause, with %s placeholders

  • where (str, default: '') – where clause, with %s placeholders for the where args

  • args (tuple | None, default: None) – args used both in the set clause and in the where clause, in this order

spotted.data.db_manager.read_file(*root_file_path)[source]

Read the contents of the file

Parameters:

root_file_path (str) – path of the file to read from the root project directory

Returns:

str – contents of the file

spotted.data.pending_post module

Pending post management

class spotted.data.pending_post.DbManager[source]

Bases: object

Class that handles the management of databases

classmethod count_from(table_name, select='*', where='', where_args=None)[source]

Returns the number of rows found with the query. Executes “SELECT COUNT(select) FROM table_name [WHERE where (with where_args)]”

Parameters:
  • table_name (str) – name of the table used in the FROM

  • select (str, default: '*') – columns considered for the query

  • where (str, default: '') – where clause, with %s placeholders for the where_args

  • where_args (tuple | None, default: None) – args used in the where clause

Returns:

int – number of rows

classmethod delete_from(table_name, where='', where_args=None)[source]

Deletes the rows from the specified table, where the condition, when set, is satisfied. Executes “DELETE FROM table_name [WHERE where (with where_args)]”

Parameters:
  • table_name (str) – name of the table used in the DELETE FROM

  • where (str, default: '') – where clause, with %s placeholders for the where args

  • where_args (tuple | None, default: None) – args used in the where clause

classmethod get_db()[source]

Creates the connection to the database. It can be sqlite or postgres

Returns:

tuple[Connection, Cursor] – sqlite database connection and cursor

classmethod insert_into(table_name, values, columns='', multiple_rows=False)[source]

Inserts the specified values in the database. Executes “INSERT INTO table_name ([columns]) VALUES (placeholders)”

Parameters:
  • table_name (str) – name of the table used in the INSERT INTO

  • values (tuple) – values to be inserted. If multiple_rows is true, tuple of tuples of values to be inserted

  • columns (tuple | str, default: '') – columns that will be inserted, as a tuple of strings

  • multiple_rows (bool, default: False) – whether or not multiple rows will be inserted at the same time

classmethod query_from_file(*file_path)[source]

Commits all the queries in the specified file. The queries must be separated by a —– string Should not be used to select something

Parameters:

file_path (str) – path of the text file containing the queries

classmethod query_from_string(*queries)[source]

Commits all the queries in the string Should not be used to select something

Parameters:

queries (str) – tuple of queries

static register_adapters_and_converters()[source]

Registers the adapter and converters for the datetime type. Needed from python 3.12 onwards, as the default option has been deprecated

static row_factory(cursor, row)[source]

Converts the rows from the database into a dictionary

Parameters:
  • cursor (Cursor) – database cursor

  • row (dict) – row from the database

Returns:

dict – dictionary containing the row. The keys are the column names

classmethod select_from(table_name, select='*', where='', where_args=None, group_by='', order_by='')[source]

Returns the results of a query. Executes “SELECT select FROM table_name [WHERE where (with where_args)] [GROUP_BY group_by] [ORDER BY order_by]”

Parameters:
  • table_name (str) – name of the table used in the FROM

  • select (str, default: '*') – columns considered for the query

  • where (str, default: '') – where clause, with %s placeholders for the where_args

  • where_args (tuple | None, default: None) – args used in the where clause

  • group_by (str, default: '') – group by clause

  • order_by (str, default: '') – order by clause

Returns:

list – rows from the select

classmethod update_from(table_name, set_clause, where='', args=None)[source]

Updates the rows from the specified table, where the condition, when set, is satisfied. Executes “UPDATE table_name SET set_clause (with args) [WHERE where (with args)]”

Parameters:
  • table_name (str) – name of the table used in the DELETE FROM

  • set_clause (str) – set clause, with %s placeholders

  • where (str, default: '') – where clause, with %s placeholders for the where args

  • args (tuple | None, default: None) – args used both in the set clause and in the where clause, in this order

class spotted.data.pending_post.Message(message_id, date, chat, from_user=None, reply_to_message=None, edit_date=None, text=None, entities=None, caption_entities=None, audio=None, document=None, game=None, photo=None, sticker=None, video=None, voice=None, video_note=None, new_chat_members=None, caption=None, contact=None, location=None, venue=None, left_chat_member=None, new_chat_title=None, new_chat_photo=None, delete_chat_photo=None, group_chat_created=None, supergroup_chat_created=None, channel_chat_created=None, migrate_to_chat_id=None, migrate_from_chat_id=None, pinned_message=None, invoice=None, successful_payment=None, author_signature=None, media_group_id=None, connected_website=None, animation=None, passport_data=None, poll=None, reply_markup=None, dice=None, via_bot=None, proximity_alert_triggered=None, sender_chat=None, video_chat_started=None, video_chat_ended=None, video_chat_participants_invited=None, message_auto_delete_timer_changed=None, video_chat_scheduled=None, is_automatic_forward=None, has_protected_content=None, web_app_data=None, is_topic_message=None, message_thread_id=None, forum_topic_created=None, forum_topic_closed=None, forum_topic_reopened=None, forum_topic_edited=None, general_forum_topic_hidden=None, general_forum_topic_unhidden=None, write_access_allowed=None, has_media_spoiler=None, chat_shared=None, story=None, giveaway=None, giveaway_completed=None, giveaway_created=None, giveaway_winners=None, users_shared=None, link_preview_options=None, external_reply=None, quote=None, forward_origin=None, reply_to_story=None, boost_added=None, sender_boost_count=None, business_connection_id=None, sender_business_bot=None, is_from_offline=None, chat_background_set=None, effect_id=None, show_caption_above_media=None, paid_media=None, refunded_payment=None, gift=None, unique_gift=None, paid_message_price_changed=None, paid_star_count=None, direct_message_price_changed=None, checklist=None, checklist_tasks_done=None, checklist_tasks_added=None, is_paid_post=None, direct_messages_topic=None, reply_to_checklist_task_id=None, suggested_post_declined=None, suggested_post_paid=None, suggested_post_refunded=None, suggested_post_info=None, suggested_post_approved=None, suggested_post_approval_failed=None, *, api_kwargs=None)[source]

Bases: MaybeInaccessibleMessage

This object represents a message.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their message_id and chat are equal.

Note

In Python from is a reserved word. Use from_user instead.

Changed in version 21.0: Removed deprecated arguments and attributes user_shared, forward_from, forward_from_chat, forward_from_message_id, forward_signature, forward_sender_name and forward_date.

Changed in version 20.8: * This class is now a subclass of telegram.MaybeInaccessibleMessage. * The pinned_message now can be either telegram.Message or telegram.InaccessibleMessage.

Changed in version 20.0:

  • The arguments and attributes voice_chat_scheduled, voice_chat_started and voice_chat_ended, voice_chat_participants_invited were renamed to video_chat_scheduled/video_chat_scheduled, video_chat_started/video_chat_started, video_chat_ended/video_chat_ended and video_chat_participants_invited/video_chat_participants_invited, respectively, in accordance to Bot API 6.0.

  • The following are now keyword-only arguments in Bot methods: {read, write, connect, pool}_timeout, api_kwargs, contact, quote, filename, loaction, venue. Use a named argument for those, and notice that some positional arguments changed position as a result.

Parameters:
  • message_id (int) – Unique message identifier inside this chat. In specific instances (e.g., message containing a video sent to a big chat), the server might automatically schedule a message instead of sending it immediately. In such cases, this field will be 0 and the relevant message will be unusable until it is actually sent.

  • from_user (User | None, default: None) – Sender of the message; may be empty for messages sent to channels. For backward compatibility, if the message was sent on behalf of a chat, the field contains a fake sender user in non-channel chats.

  • sender_chat (Chat | None, default: None) – Sender of the message when sent on behalf of a chat. For example, the supergroup itself for messages sent by its anonymous administrators or a linked channel for messages automatically forwarded to the channel’s discussion group. For backward compatibility, if the message was sent on behalf of a chat, the field from contains a fake sender user in non-channel chats.

  • date (datetime) –

    Date the message was sent in Unix time. Converted to datetime.datetime.

    Changed in version 20.3: |datetime_localization|

  • chat (Chat) – Conversation the message belongs to.

  • is_automatic_forward (bool | None, default: None) –

    True, if the message is a channel post that was automatically forwarded to the connected discussion group.

    Added in version 13.9.

  • reply_to_message (Message | None, default: None) – For replies, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply.

  • edit_date (datetime | None, default: None) –

    Date the message was last edited in Unix time. Converted to datetime.datetime.

    Changed in version 20.3: |datetime_localization|

  • has_protected_content (bool | None, default: None) –

    True, if the message can’t be forwarded.

    Added in version 13.9.

  • is_from_offline (bool | None, default: None) –

    True, if the message was sent by an implicit action, for example, as an away or a greeting business message, or as a scheduled message.

    Added in version 21.1.

  • media_group_id (str | None, default: None) – The unique identifier of a media message group this message belongs to.

  • text (str | None, default: None) – For text messages, the actual UTF-8 text of the message, 0-telegram.constants.MessageLimit.MAX_TEXT_LENGTH characters.

  • entities (Sequence[MessageEntity] | None, default: None) –

    For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text. See parse_entity and parse_entities methods for how to use properly. This list is empty if the message does not contain entities.

    Changed in version 20.0: |sequenceclassargs|

  • link_preview_options (LinkPreviewOptions | None, default: None) –

    Options used for link preview generation for the message, if it is a text message and link preview options were changed.

    Added in version 20.8.

  • suggested_post_info (SuggestedPostInfo | None, default: None) –

    Information about suggested post parameters if the message is a suggested post in a channel direct messages chat. If the message is an approved or declined suggested post, then it can’t be edited.

    Added in version 22.4.

  • effect_id (str | None, default: None) –

    Unique identifier of the message effect added to the message.

    Added in version 21.3.

  • caption_entities (Sequence[MessageEntity] | None, default: None) –

    For messages with a Caption. Special entities like usernames, URLs, bot commands, etc. that appear in the caption. See Message.parse_caption_entity and parse_caption_entities methods for how to use properly. This list is empty if the message does not contain caption entities.

    Changed in version 20.0: |sequenceclassargs|

  • show_caption_above_media (bool | None, default: None) –

    |show_cap_above_med|

    Added in version 21.3.

  • audio (Audio | None, default: None) – Message is an audio file, information about the file.

  • document (Document | None, default: None) – Message is a general file, information about the file.

  • animation (Animation | None, default: None) – Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set.

  • game (Game | None, default: None) – Message is a game, information about the game. More about games >>.

  • photo (Sequence[PhotoSize] | None, default: None) –

    Message is a photo, available sizes of the photo. This list is empty if the message does not contain a photo.

    Changed in version 20.0: |sequenceclassargs|

  • sticker (Sticker | None, default: None) – Message is a sticker, information about the sticker.

  • story (Story | None, default: None) –

    Message is a forwarded story.

    Added in version 20.5.

  • video (Video | None, default: None) – Message is a video, information about the video.

  • voice (Voice | None, default: None) – Message is a voice message, information about the file.

  • video_note (VideoNote | None, default: None) – Message is a video note, information about the video message.

  • new_chat_members (Sequence[User] | None, default: None) –

    New members that were added to the group or supergroup and information about them (the bot itself may be one of these members). This list is empty if the message does not contain new chat members.

    Changed in version 20.0: |sequenceclassargs|

  • caption (str | None, default: None) – Caption for the animation, audio, document, paid media, photo, video or voice, 0-telegram.constants.MessageLimit.CAPTION_LENGTH characters.

  • contact (Contact | None, default: None) – Message is a shared contact, information about the contact.

  • location (Location | None, default: None) – Message is a shared location, information about the location.

  • venue (Venue | None, default: None) – Message is a venue, information about the venue. For backward compatibility, when this field is set, the location field will also be set.

  • left_chat_member (User | None, default: None) – A member was removed from the group, information about them (this member may be the bot itself).

  • new_chat_title (str | None, default: None) – A chat title was changed to this value.

  • new_chat_photo (Sequence[PhotoSize] | None, default: None) –

    A chat photo was changed to this value. This list is empty if the message does not contain a new chat photo.

    Changed in version 20.0: |sequenceclassargs|

  • delete_chat_photo (bool | None, default: None) – Service message: The chat photo was deleted.

  • group_chat_created (bool | None, default: None) – Service message: The group has been created.

  • supergroup_chat_created (bool | None, default: None) – Service message: The supergroup has been created. This field can’t be received in a message coming through updates, because bot can’t be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup.

  • channel_chat_created (bool | None, default: None) – Service message: The channel has been created. This field can’t be received in a message coming through updates, because bot can’t be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel.

  • message_auto_delete_timer_changed (MessageAutoDeleteTimerChanged | None, default: None) –

    Service message: auto-delete timer settings changed in the chat.

    Added in version 13.4.

  • migrate_to_chat_id (int | None, default: None) – The group has been migrated to a supergroup with the specified identifier.

  • migrate_from_chat_id (int | None, default: None) – The supergroup has been migrated from a group with the specified identifier.

  • pinned_message (MaybeInaccessibleMessage | None, default: None) –

    Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply.

    Changed in version 20.8: This attribute now is either telegram.Message or telegram.InaccessibleMessage.

  • invoice (Invoice | None, default: None) – Message is an invoice for a payment, information about the invoice. More about payments >>.

  • successful_payment (SuccessfulPayment | None, default: None) – Message is a service message about a successful payment, information about the payment. More about payments >>.

  • connected_website (str | None, default: None) – The domain name of the website on which the user has logged in. More about Telegram Login >>.

  • author_signature (str | None, default: None) – Signature of the post author for messages in channels, or the custom title of an anonymous group administrator.

  • paid_star_count (int | None, default: None) –

    The number of Telegram Stars that were paid by the sender of the message to send it

    Added in version 22.1.

  • passport_data (PassportData | None, default: None) – Telegram Passport data.

  • poll (Poll | None, default: None) – Message is a native poll, information about the poll.

  • dice (Dice | None, default: None) – Message is a dice with random value.

  • via_bot (User | None, default: None) – Bot through which message was sent.

  • proximity_alert_triggered (ProximityAlertTriggered | None, default: None) – Service message. A user in the chat triggered another user’s proximity alert while sharing Live Location.

  • video_chat_scheduled (VideoChatScheduled | None, default: None) –

    Service message: video chat scheduled.

    Added in version 20.0.

  • video_chat_started (VideoChatStarted | None, default: None) –

    Service message: video chat started.

    Added in version 20.0.

  • video_chat_ended (VideoChatEnded | None, default: None) –

    Service message: video chat ended.

    Added in version 20.0.

  • video_chat_participants_invited (VideoChatParticipantsInvited | None, default: None) –

    Service message: new participants invited to a video chat.

    Added in version 20.0.

  • web_app_data (WebAppData | None, default: None) –

    Service message: data sent by a Web App.

    Added in version 20.0.

  • reply_markup (InlineKeyboardMarkup | None, default: None) – Inline keyboard attached to the message. ~telegram.InlineKeyboardButton.login_url buttons are represented as ordinary url buttons.

  • is_topic_message (bool | None, default: None) –

    True, if the message is sent to a forum topic.

    Added in version 20.0.

  • message_thread_id (int | None, default: None) –

    Unique identifier of a message thread to which the message belongs; for supergroups only.

    Added in version 20.0.

  • forum_topic_created (ForumTopicCreated | None, default: None) –

    Service message: forum topic created.

    Added in version 20.0.

  • forum_topic_closed (ForumTopicClosed | None, default: None) –

    Service message: forum topic closed.

    Added in version 20.0.

  • forum_topic_reopened (ForumTopicReopened | None, default: None) –

    Service message: forum topic reopened.

    Added in version 20.0.

  • forum_topic_edited (ForumTopicEdited | None, default: None) –

    Service message: forum topic edited.

    Added in version 20.0.

  • general_forum_topic_hidden (GeneralForumTopicHidden | None, default: None) –

    Service message: General forum topic hidden.

    Added in version 20.0.

  • general_forum_topic_unhidden (GeneralForumTopicUnhidden | None, default: None) –

    Service message: General forum topic unhidden.

    Added in version 20.0.

  • write_access_allowed (WriteAccessAllowed | None, default: None) –

    Service message: the user allowed the bot to write messages after adding it to the attachment or side menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method requestWriteAccess.

    Added in version 20.0.

  • has_media_spoiler (bool | None, default: None) –

    True, if the message media is covered by a spoiler animation.

    Added in version 20.0.

  • checklist (Checklist | None, default: None) –

    Message is a checklist

    Added in version 22.3.

  • users_shared (UsersShared | None, default: None) –

    Service message: users were shared with the bot

    Added in version 20.8.

  • chat_shared (ChatShared | None, default: None) –

    Service message: a chat was shared with the bot.

    Added in version 20.1.

  • gift (GiftInfo | None, default: None) –

    Service message: a regular gift was sent or received.

    Added in version 22.1.

  • unique_gift (UniqueGiftInfo | None, default: None) –

    Service message: a unique gift was sent or received

    Added in version 22.1.

  • giveaway_created (GiveawayCreated | None, default: None) –

    Service message: a scheduled giveaway was created

    Added in version 20.8.

  • giveaway (Giveaway | None, default: None) –

    The message is a scheduled giveaway message

    Added in version 20.8.

  • giveaway_winners (GiveawayWinners | None, default: None) –

    A giveaway with public winners was completed

    Added in version 20.8.

  • giveaway_completed (GiveawayCompleted | None, default: None) –

    Service message: a giveaway without public winners was completed

    Added in version 20.8.

  • paid_message_price_changed (PaidMessagePriceChanged | None, default: None) –

    Service message: the price for paid messages has changed in the chat

    Added in version 22.1.

  • suggested_post_approved (SuggestedPostApproved | None, default: None) –

    Service message: a suggested post was approved.

    Added in version 22.4.

  • suggested_post_approval_failed (SuggestedPostApprovalFailed | None, default: None) –

    Service message: approval of a suggested post has failed.

    Added in version 22.4.

  • suggested_post_declined (SuggestedPostDeclined | None, default: None) –

    Service message: a suggested post was declined.

    Added in version 22.4.

  • suggested_post_paid (SuggestedPostPaid | None, default: None) –

    Service message: payment for a suggested post was received.

    Added in version 22.4.

  • suggested_post_refunded (SuggestedPostRefunded | None, default: None) –

    Service message: payment for a suggested post was refunded.

    Added in version 22.4.

  • external_reply (ExternalReplyInfo | None, default: None) –

    Information about the message that is being replied to, which may come from another chat or forum topic.

    Added in version 20.8.

  • quote (TextQuote | None, default: None) –

    For replies that quote part of the original message, the quoted part of the message.

    Added in version 20.8.

  • forward_origin (MessageOrigin | None, default: None) –

    Information about the original message for forwarded messages

    Added in version 20.8.

  • reply_to_story (Story | None, default: None) –

    For replies to a story, the original story.

    Added in version 21.0.

  • boost_added (ChatBoostAdded | None, default: None) –

    Service message: user boosted the chat.

    Added in version 21.0.

  • sender_boost_count (int | None, default: None) –

    If the sender of the message boosted the chat, the number of boosts added by the user.

    Added in version 21.0.

  • business_connection_id (str | None, default: None) –

    Unique identifier of the business connection from which the message was received. If non-empty, the message belongs to a chat of the corresponding business account that is independent from any potential bot chat which might share the same identifier.

    Added in version 21.1.

  • sender_business_bot (User | None, default: None) –

    The bot that actually sent the message on behalf of the business account. Available only for outgoing messages sent on behalf of the connected business account.

    Added in version 21.1.

  • chat_background_set (ChatBackground | None, default: None) –

    Service message: chat background set.

    Added in version 21.2.

  • checklist_tasks_done (ChecklistTasksDone | None, default: None) –

    Service message: some tasks in a checklist were marked as done or not done

    Added in version 22.3.

  • checklist_tasks_added (ChecklistTasksAdded | None, default: None) –

    Service message: tasks were added to a checklist

    Added in version 22.3.

  • paid_media (PaidMediaInfo | None, default: None) –

    Message contains paid media; information about the paid media.

    Added in version 21.4.

  • refunded_payment (RefundedPayment | None, default: None) –

    Message is a service message about a refunded payment, information about the payment.

    Added in version 21.4.

  • direct_message_price_changed (DirectMessagePriceChanged | None, default: None) –

    Service message: the price for paid messages in the corresponding direct messages chat of a channel has changed.

    Added in version 22.3.

  • is_paid_post (bool | None, default: None) –

    True, if the message is a paid post. Note that such posts must not be deleted for 24 hours to receive the payment and can’t be edited.

    Added in version 22.4.

  • direct_messages_topic (DirectMessagesTopic | None, default: None) –

    Information about the direct messages chat topic that contains the message.

    Added in version 22.4.

  • reply_to_checklist_task_id (int | None, default: None) –

    Identifier of the specific checklist task that is being replied to.

    Added in version 22.4.

message_id

Unique message identifier inside this chat. In specific instances (e.g., message containing a video sent to a big chat), the server might automatically schedule a message instead of sending it immediately. In such cases, this field will be 0 and the relevant message will be unusable until it is actually sent.

Type:

int

from_user

Optional. Sender of the message; may be empty for messages sent to channels. For backward compatibility, if the message was sent on behalf of a chat, the field contains a fake sender user in non-channel chats.

Type:

telegram.User

sender_chat

Optional. Sender of the message when sent on behalf of a chat. For example, the supergroup itself for messages sent by its anonymous administrators or a linked channel for messages automatically forwarded to the channel’s discussion group. For backward compatibility, if the message was sent on behalf of a chat, the field from contains a fake sender user in non-channel chats.

Type:

telegram.Chat

date

Date the message was sent in Unix time. Converted to datetime.datetime.

Changed in version 20.3: |datetime_localization|

Type:

datetime.datetime

chat

Conversation the message belongs to.

Type:

telegram.Chat

is_automatic_forward

Optional. True, if the message is a channel post that was automatically forwarded to the connected discussion group.

Added in version 13.9.

Type:

bool

reply_to_message

Optional. For replies, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply.

Type:

telegram.Message

edit_date

Optional. Date the message was last edited in Unix time. Converted to datetime.datetime.

Changed in version 20.3: |datetime_localization|

Type:

datetime.datetime

has_protected_content

Optional. True, if the message can’t be forwarded.

Added in version 13.9.

Type:

bool

is_from_offline

Optional. True, if the message was sent by an implicit action, for example, as an away or a greeting business message, or as a scheduled message.

Added in version 21.1.

Type:

bool

media_group_id

Optional. The unique identifier of a media message group this message belongs to.

Type:

str

text

Optional. For text messages, the actual UTF-8 text of the message, 0-telegram.constants.MessageLimit.MAX_TEXT_LENGTH characters.

Type:

str

entities

Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text. See parse_entity and parse_entities methods for how to use properly. This list is empty if the message does not contain entities.

Changed in version 20.0: |tupleclassattrs|

Type:

tuple[telegram.MessageEntity]

Optional. Options used for link preview generation for the message, if it is a text message and link preview options were changed.

Added in version 20.8.

Type:

telegram.LinkPreviewOptions

suggested_post_info

Optional. Information about suggested post parameters if the message is a suggested post in a channel direct messages chat. If the message is an approved or declined suggested post, then it can’t be edited.

Added in version 22.4.

Type:

telegram.SuggestedPostInfo

effect_id

Optional. Unique identifier of the message effect added to the message.

Added in version 21.3.

Type:

str

caption_entities

Optional. For messages with a Caption. Special entities like usernames, URLs, bot commands, etc. that appear in the caption. See Message.parse_caption_entity and parse_caption_entities methods for how to use properly. This list is empty if the message does not contain caption entities.

Changed in version 20.0: |tupleclassattrs|

Type:

tuple[telegram.MessageEntity]

show_caption_above_media

Optional. |show_cap_above_med|

Added in version 21.3.

Type:

bool

audio

Optional. Message is an audio file, information about the file.

See also

Working with Files and Media <Working-with-Files-and-Media>

Type:

telegram.Audio

document

Optional. Message is a general file, information about the file.

See also

Working with Files and Media <Working-with-Files-and-Media>

Type:

telegram.Document

animation

Optional. Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set.

See also

Working with Files and Media <Working-with-Files-and-Media>

Type:

telegram.Animation

game

Optional. Message is a game, information about the game. More about games >>.

Type:

telegram.Game

photo

Optional. Message is a photo, available sizes of the photo. This list is empty if the message does not contain a photo.

See also

Working with Files and Media <Working-with-Files-and-Media>

Changed in version 20.0: |tupleclassattrs|

Type:

tuple[telegram.PhotoSize]

sticker

Optional. Message is a sticker, information about the sticker.

See also

Working with Files and Media <Working-with-Files-and-Media>

Type:

telegram.Sticker

story

Optional. Message is a forwarded story.

Added in version 20.5.

Type:

telegram.Story

video

Optional. Message is a video, information about the video.

See also

Working with Files and Media <Working-with-Files-and-Media>

Type:

telegram.Video

voice

Optional. Message is a voice message, information about the file.

See also

Working with Files and Media <Working-with-Files-and-Media>

Type:

telegram.Voice

video_note

Optional. Message is a video note, information about the video message.

See also

Working with Files and Media <Working-with-Files-and-Media>

Type:

telegram.VideoNote

new_chat_members

Optional. New members that were added to the group or supergroup and information about them (the bot itself may be one of these members). This list is empty if the message does not contain new chat members.

Changed in version 20.0: |tupleclassattrs|

Type:

tuple[telegram.User]

caption

Optional. Caption for the animation, audio, document, paid media, photo, video or voice, 0-telegram.constants.MessageLimit.CAPTION_LENGTH characters.

Type:

str

contact

Optional. Message is a shared contact, information about the contact.

Type:

telegram.Contact

location

Optional. Message is a shared location, information about the location.

Type:

telegram.Location

venue

Optional. Message is a venue, information about the venue. For backward compatibility, when this field is set, the location field will also be set.

Type:

telegram.Venue

left_chat_member

Optional. A member was removed from the group, information about them (this member may be the bot itself).

Type:

telegram.User

new_chat_title

Optional. A chat title was changed to this value.

Type:

str

new_chat_photo

A chat photo was changed to this value. This list is empty if the message does not contain a new chat photo.

Changed in version 20.0: |tupleclassattrs|

Type:

tuple[telegram.PhotoSize]

delete_chat_photo

Optional. Service message: The chat photo was deleted.

Type:

bool

group_chat_created

Optional. Service message: The group has been created.

Type:

bool

supergroup_chat_created

Optional. Service message: The supergroup has been created. This field can’t be received in a message coming through updates, because bot can’t be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup.

Type:

bool

channel_chat_created

Optional. Service message: The channel has been created. This field can’t be received in a message coming through updates, because bot can’t be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel.

Type:

bool

message_auto_delete_timer_changed

Optional. Service message: auto-delete timer settings changed in the chat.

Added in version 13.4.

Type:

telegram.MessageAutoDeleteTimerChanged

migrate_to_chat_id

Optional. The group has been migrated to a supergroup with the specified identifier.

Type:

int

migrate_from_chat_id

Optional. The supergroup has been migrated from a group with the specified identifier.

Type:

int

pinned_message

Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply.

Changed in version 20.8: This attribute now is either telegram.Message or telegram.InaccessibleMessage.

Type:

telegram.MaybeInaccessibleMessage

invoice

Optional. Message is an invoice for a payment, information about the invoice. More about payments >>.

Type:

telegram.Invoice

successful_payment

Optional. Message is a service message about a successful payment, information about the payment. More about payments >>.

Type:

telegram.SuccessfulPayment

connected_website

Optional. The domain name of the website on which the user has logged in. More about Telegram Login >>.

Type:

str

author_signature

Optional. Signature of the post author for messages in channels, or the custom title of an anonymous group administrator.

Type:

str

paid_star_count

Optional. The number of Telegram Stars that were paid by the sender of the message to send it

Added in version 22.1.

Type:

int

passport_data

Optional. Telegram Passport data.

Examples

Passport Bot

Type:

telegram.PassportData

poll

Optional. Message is a native poll, information about the poll.

Type:

telegram.Poll

dice

Optional. Message is a dice with random value.

Type:

telegram.Dice

via_bot

Optional. Bot through which message was sent.

Type:

telegram.User

proximity_alert_triggered

Optional. Service message. A user in the chat triggered another user’s proximity alert while sharing Live Location.

Type:

telegram.ProximityAlertTriggered

video_chat_scheduled

Optional. Service message: video chat scheduled.

Added in version 20.0.

Type:

telegram.VideoChatScheduled

video_chat_started

Optional. Service message: video chat started.

Added in version 20.0.

Type:

telegram.VideoChatStarted

video_chat_ended

Optional. Service message: video chat ended.

Added in version 20.0.

Type:

telegram.VideoChatEnded

video_chat_participants_invited

Optional. Service message: new participants invited to a video chat.

Added in version 20.0.

Type:

telegram.VideoChatParticipantsInvited

web_app_data

Optional. Service message: data sent by a Web App.

Added in version 20.0.

Type:

telegram.WebAppData

reply_markup

Optional. Inline keyboard attached to the message. ~telegram.InlineKeyboardButton.login_url buttons are represented as ordinary url buttons.

Type:

telegram.InlineKeyboardMarkup

is_topic_message

Optional. True, if the message is sent to a forum topic.

Added in version 20.0.

Type:

bool

message_thread_id

Optional. Unique identifier of a message thread to which the message belongs; for supergroups only.

Added in version 20.0.

Type:

int

forum_topic_created

Optional. Service message: forum topic created.

Added in version 20.0.

Type:

telegram.ForumTopicCreated

forum_topic_closed

Optional. Service message: forum topic closed.

Added in version 20.0.

Type:

telegram.ForumTopicClosed

forum_topic_reopened

Optional. Service message: forum topic reopened.

Added in version 20.0.

Type:

telegram.ForumTopicReopened

forum_topic_edited

Optional. Service message: forum topic edited.

Added in version 20.0.

Type:

telegram.ForumTopicEdited

general_forum_topic_hidden

Optional. Service message: General forum topic hidden.

Added in version 20.0.

Type:

telegram.GeneralForumTopicHidden

general_forum_topic_unhidden

Optional. Service message: General forum topic unhidden.

Added in version 20.0.

Type:

telegram.GeneralForumTopicUnhidden

write_access_allowed

Optional. Service message: the user allowed the bot added to the attachment menu to write messages.

Added in version 20.0.

Type:

telegram.WriteAccessAllowed

has_media_spoiler

Optional. True, if the message media is covered by a spoiler animation.

Added in version 20.0.

Type:

bool

checklist

Optional. Message is a checklist

Added in version 22.3.

Type:

telegram.Checklist

users_shared

Optional. Service message: users were shared with the bot

Added in version 20.8.

Type:

telegram.UsersShared

chat_shared

Optional. Service message: a chat was shared with the bot.

Added in version 20.1.

Type:

telegram.ChatShared

gift

Optional. Service message: a regular gift was sent or received.

Added in version 22.1.

Type:

telegram.GiftInfo

unique_gift

Optional. Service message: a unique gift was sent or received

Added in version 22.1.

Type:

telegram.UniqueGiftInfo

giveaway_created

Optional. Service message: a scheduled giveaway was created

Added in version 20.8.

Type:

telegram.GiveawayCreated

giveaway

Optional. The message is a scheduled giveaway message

Added in version 20.8.

Type:

telegram.Giveaway

giveaway_winners

Optional. A giveaway with public winners was completed

Added in version 20.8.

Type:

telegram.GiveawayWinners

giveaway_completed

Optional. Service message: a giveaway without public winners was completed

Added in version 20.8.

Type:

telegram.GiveawayCompleted

paid_message_price_changed

Optional. Service message: the price for paid messages has changed in the chat

Added in version 22.1.

Type:

telegram.PaidMessagePriceChanged

suggested_post_approved

Optional. Service message: a suggested post was approved.

Added in version 22.4.

Type:

telegram.SuggestedPostApproved

suggested_post_approval_failed

Optional. Service message: approval of a suggested post has failed.

Added in version 22.4.

Type:

telegram.SuggestedPostApproved

suggested_post_declined

Optional. Service message: a suggested post was declined.

Added in version 22.4.

Type:

telegram.SuggestedPostDeclined

suggested_post_paid

Optional. Service message: payment for a suggested post was received.

Added in version 22.4.

Type:

telegram.SuggestedPostPaid

suggested_post_refunded

Optional. Service message: payment for a suggested post was refunded.

Added in version 22.4.

Type:

telegram.SuggestedPostRefunded

external_reply

Optional. Information about the message that is being replied to, which may come from another chat or forum topic.

Added in version 20.8.

Type:

telegram.ExternalReplyInfo

quote

Optional. For replies that quote part of the original message, the quoted part of the message.

Added in version 20.8.

Type:

telegram.TextQuote

forward_origin

Optional. Information about the original message for forwarded messages

Added in version 20.8.

Type:

telegram.MessageOrigin

reply_to_story

Optional. For replies to a story, the original story.

Added in version 21.0.

Type:

telegram.Story

boost_added

Optional. Service message: user boosted the chat.

Added in version 21.0.

Type:

telegram.ChatBoostAdded

sender_boost_count

Optional. If the sender of the message boosted the chat, the number of boosts added by the user.

Added in version 21.0.

Type:

int

business_connection_id

Optional. Unique identifier of the business connection from which the message was received. If non-empty, the message belongs to a chat of the corresponding business account that is independent from any potential bot chat which might share the same identifier.

Added in version 21.1.

Type:

str

sender_business_bot

Optional. The bot that actually sent the message on behalf of the business account. Available only for outgoing messages sent on behalf of the connected business account.

Added in version 21.1.

Type:

telegram.User

chat_background_set

Optional. Service message: chat background set

Added in version 21.2.

Type:

telegram.ChatBackground

checklist_tasks_done

Optional. Service message: some tasks in a checklist were marked as done or not done

Added in version 22.3.

Type:

telegram.ChecklistTasksDone

checklist_tasks_added

Optional. Service message: tasks were added to a checklist

Added in version 22.3.

Type:

telegram.ChecklistTasksAdded

paid_media

Optional. Message contains paid media; information about the paid media.

Added in version 21.4.

Type:

telegram.PaidMediaInfo

refunded_payment

Optional. Message is a service message about a refunded payment, information about the payment.

Added in version 21.4.

Type:

telegram.RefundedPayment

direct_message_price_changed

Optional. Service message: the price for paid messages in the corresponding direct messages chat of a channel has changed.

Added in version 22.3.

Type:

telegram.DirectMessagePriceChanged

is_paid_post

Optional. True, if the message is a paid post. Note that such posts must not be deleted for 24 hours to receive the payment and can’t be edited.

Added in version 22.4.

Type:

bool

direct_messages_topic

Optional. Information about the direct messages chat topic that contains the message.

Added in version 22.4.

Type:

telegram.DirectMessagesTopic

reply_to_checklist_task_id

Optional. Identifier of the specific checklist task that is being replied to.

Added in version 22.4.

Type:

int

animation: Animation | None
async approve_suggested_post(send_date=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.approve_suggested_post(
    chat_id=message.chat_id,
    message_id=message.message_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.approve_suggested_post().

Added in version 22.4.

Returns:

boolbool On success, True is returned.

audio: Audio | None
author_signature: str | None
boost_added: ChatBoostAdded | None
build_reply_arguments(quote=None, quote_index=None, target_chat_id=None, allow_sending_without_reply=None, message_thread_id=None)[source]

Builds a dictionary with the keys chat_id and reply_parameters. This dictionary can be used to reply to a message with the given quote and target chat.

Examples

Usage with telegram.Bot.send_message():

await bot.send_message(
    text="This is a reply",
    **message.build_reply_arguments(quote="Quoted Text")
)

Usage with reply_text(), replying in the same chat:

await message.reply_text(
    "This is a reply",
    do_quote=message.build_reply_arguments(quote="Quoted Text")
)

Usage with reply_text(), replying in a different chat:

await message.reply_text(
    "This is a reply",
    do_quote=message.build_reply_arguments(
        quote="Quoted Text",
        target_chat_id=-100123456789
    )
)

Added in version 20.8.

Parameters:
Returns:

_ReplyKwargs

business_connection_id: str | None
caption: str | None
caption_entities: tuple[MessageEntity, ...]
property caption_html: str

Creates an HTML-formatted string from the markup entities found in the message’s caption.

Use this if you want to retrieve the message caption with the caption entities formatted as HTML in the same way the original message was formatted.

Warning

|text_html|

Changed in version 13.10: Spoiler entities are now formatted as HTML.

Changed in version 20.3: Custom emoji entities are now supported.

Changed in version 20.8: Blockquote entities are now supported.

Returns:

Message caption with caption entities formatted as HTML.

Return type:

str

property caption_html_urled: str

Creates an HTML-formatted string from the markup entities found in the message’s caption.

Use this if you want to retrieve the message caption with the caption entities formatted as HTML. This also formats telegram.MessageEntity.URL as a hyperlink.

Warning

|text_html|

Changed in version 13.10: Spoiler entities are now formatted as HTML.

Changed in version 20.3: Custom emoji entities are now supported.

Changed in version 20.8: Blockquote entities are now supported.

Returns:

Message caption with caption entities formatted as HTML.

Return type:

str

property caption_markdown: str

Creates an Markdown-formatted string from the markup entities found in the message’s caption using telegram.constants.ParseMode.MARKDOWN.

Use this if you want to retrieve the message caption with the caption entities formatted as Markdown in the same way the original message was formatted.

Warning

|text_markdown|

Note

telegram.constants.ParseMode.MARKDOWN is a legacy mode, retained by Telegram for backward compatibility. You should use caption_markdown_v2()

Changed in version 20.5: Since custom emoji entities are not supported by MARKDOWN, this method now raises a ValueError when encountering a custom emoji.

Changed in version 20.8: Since block quotation entities are not supported by MARKDOWN, this method now raises a ValueError when encountering a block quotation.

Returns:

Message caption with caption entities formatted as Markdown.

Return type:

str

Raises:

ValueError – If the message contains underline, strikethrough, spoiler, blockquote or nested entities.

property caption_markdown_urled: str

Creates an Markdown-formatted string from the markup entities found in the message’s caption using telegram.constants.ParseMode.MARKDOWN.

Use this if you want to retrieve the message caption with the caption entities formatted as Markdown. This also formats telegram.MessageEntity.URL as a hyperlink.

Warning

|text_markdown|

Note

telegram.constants.ParseMode.MARKDOWN is a legacy mode, retained by Telegram for backward compatibility. You should use caption_markdown_v2_urled() instead.

Changed in version 20.5: Since custom emoji entities are not supported by MARKDOWN, this method now raises a ValueError when encountering a custom emoji.

Changed in version 20.8: Since block quotation entities are not supported by MARKDOWN, this method now raises a ValueError when encountering a block quotation.

Returns:

Message caption with caption entities formatted as Markdown.

Return type:

str

Raises:

ValueError – If the message contains underline, strikethrough, spoiler, blockquote or nested entities.

property caption_markdown_v2: str

Creates an Markdown-formatted string from the markup entities found in the message’s caption using telegram.constants.ParseMode.MARKDOWN_V2.

Use this if you want to retrieve the message caption with the caption entities formatted as Markdown in the same way the original message was formatted.

Warning

|text_markdown|

Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.

Changed in version 20.3: Custom emoji entities are now supported.

Changed in version 20.8: Blockquote entities are now supported.

Returns:

Message caption with caption entities formatted as Markdown.

Return type:

str

property caption_markdown_v2_urled: str

Creates an Markdown-formatted string from the markup entities found in the message’s caption using telegram.constants.ParseMode.MARKDOWN_V2.

Use this if you want to retrieve the message caption with the caption entities formatted as Markdown. This also formats telegram.MessageEntity.URL as a hyperlink.

Warning

|text_markdown|

Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.

Changed in version 20.3: Custom emoji entities are now supported.

Changed in version 20.8: Blockquote entities are now supported.

Returns:

Message caption with caption entities formatted as Markdown.

Return type:

str

channel_chat_created: bool | None
chat_background_set: ChatBackground | None
property chat_id: int

Shortcut for telegram.Chat.id for chat.

Type:

int

chat_shared: ChatShared | None
checklist: Checklist | None
checklist_tasks_added: ChecklistTasksAdded | None
checklist_tasks_done: ChecklistTasksDone | None
async close_forum_topic(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.close_forum_topic(
   chat_id=message.chat_id, message_thread_id=message.message_thread_id, *args,
   **kwargs
)

For the documentation of the arguments, please see telegram.Bot.close_forum_topic().

Added in version 20.0.

Returns:

On success, True is returned.

Returns:

bool

compute_quote_position_and_entities(quote, index=None)[source]

Use this function to compute position and entities of a quote in the message text or caption. Useful for filling the parameters ~telegram.ReplyParameters.quote_position and ~telegram.ReplyParameters.quote_entities of telegram.ReplyParameters when replying to a message.

Example

Given a message with the text "Hello, world! Hello, world!", the following code will return the position and entities of the second occurrence of "Hello, world!".

message.compute_quote_position_and_entities("Hello, world!", 1)

Added in version 20.8.

Parameters:
  • quote (str) – Part of the message which is to be quoted. This is expected to have plain text without formatting entities.

  • index (int | None, default: None) – 0-based index of the occurrence of the quote in the message. If not specified, the first occurrence is used.

Returns:

On success, a tuple containing information about quote position and entities is returned.

Returns:

tuple[int, tuple[MessageEntity, ...] | None]

Raises:
connected_website: str | None
contact: Contact | None
async copy(chat_id, caption=None, parse_mode=None, caption_entities=None, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, reply_parameters=None, show_caption_above_media=None, allow_paid_broadcast=None, video_start_timestamp=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.copy_message(
    chat_id=chat_id,
    from_chat_id=update.effective_message.chat_id,
    message_id=update.effective_message.message_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs
)

For the documentation of the arguments, please see telegram.Bot.copy_message().

Returns:

On success, returns the MessageId of the sent message.

Returns:

MessageId

classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Message

async decline_suggested_post(comment=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.decline_suggested_post(
    chat_id=message.chat_id,
    message_id=message.message_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.decline_suggested_post().

Added in version 22.4.

Returns:

boolbool On success, True is returned.

async delete(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for either:

await bot.delete_message(
    chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)

or:

await bot.delete_business_messages(
    business_connection_id=self.business_connection_id,
    message_ids=[self.message_id],
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.delete_message() and telegram.Bot.delete_business_messages().

Returns:

On success, True is returned.

Returns:

bool

delete_chat_photo: bool | None
async delete_forum_topic(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.delete_forum_topic(
   chat_id=message.chat_id, message_thread_id=message.message_thread_id, *args,
   **kwargs
)

For the documentation of the arguments, please see telegram.Bot.delete_forum_topic().

Added in version 20.0.

Returns:

On success, True is returned.

Returns:

bool

dice: Dice | None
direct_message_price_changed: DirectMessagePriceChanged | None
direct_messages_topic: DirectMessagesTopic | None
document: Document | None
async edit_caption(caption=None, reply_markup=None, parse_mode=None, caption_entities=None, show_caption_above_media=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.edit_message_caption(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.edit_message_caption().

Note

You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Changed in version 21.4: Now also passes business_connection_id.

Returns:

On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.

Returns:

Message | bool

async edit_checklist(checklist, reply_markup=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.edit_message_checklist(
    business_connection_id=message.business_connection_id,
    chat_id=message.chat_id,
    message_id=message.message_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.edit_message_checklist().

Added in version 22.3.

Note

You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Returns:

On success, the edited Message is returned.

Returns:

Message

edit_date: dtm.datetime | None
async edit_forum_topic(name=None, icon_custom_emoji_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.edit_forum_topic(
   chat_id=message.chat_id, message_thread_id=message.message_thread_id, *args,
   **kwargs
)

For the documentation of the arguments, please see telegram.Bot.edit_forum_topic().

Added in version 20.0.

Returns:

On success, True is returned.

Returns:

bool

async edit_live_location(latitude=None, longitude=None, reply_markup=None, horizontal_accuracy=None, heading=None, proximity_alert_radius=None, live_period=None, *, location=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.edit_message_live_location(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.edit_message_live_location().

Note

You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Changed in version 21.4: Now also passes business_connection_id.

Returns:

On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.

Returns:

Message | bool

async edit_media(media, reply_markup=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.edit_message_media(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.edit_message_media().

Note

You can only edit messages that the bot sent itself(i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Changed in version 21.4: Now also passes business_connection_id.

Returns:

On success, if edited message is not an inline message, the edited Message is returned, otherwise True is returned.

Returns:

Message | bool

async edit_reply_markup(reply_markup=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.edit_message_reply_markup(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.edit_message_reply_markup().

Note

You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Changed in version 21.4: Now also passes business_connection_id.

Returns:

On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.

Returns:

Message | bool

async edit_text(text, parse_mode=None, reply_markup=None, entities=None, link_preview_options=None, *, disable_web_page_preview=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.edit_message_text(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.edit_message_text().

Note

You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Changed in version 21.4: Now also passes business_connection_id.

Returns:

On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.

Returns:

Message | bool

effect_id: str | None
property effective_attachment: Animation | Audio | Contact | Dice | Document | Game | Invoice | Location | PassportData | Sequence[PhotoSize] | PaidMediaInfo | Poll | Sticker | Story | SuccessfulPayment | Venue | Video | VideoNote | Voice | None

If the message is a user generated content which is not a plain text message, this property is set to this content. It may be one of

Otherwise None is returned.

See also

Working with Files and Media <Working-with-Files-and-Media>

Changed in version 20.0: dice, passport_data and poll are now also considered to be an attachment.

Changed in version 21.4: paid_media is now also considered to be an attachment.

Deprecated since version 21.4: successful_payment will be removed in future major versions.

entities: tuple[MessageEntity, ...]
external_reply: ExternalReplyInfo | None
forum_topic_closed: ForumTopicClosed | None
forum_topic_created: ForumTopicCreated | None
forum_topic_edited: ForumTopicEdited | None
forum_topic_reopened: ForumTopicReopened | None
async forward(chat_id, disable_notification=None, protect_content=None, message_thread_id=None, video_start_timestamp=None, suggested_post_parameters=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.forward_message(
    from_chat_id=update.effective_message.chat_id,
    message_id=update.effective_message.message_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs
)

For the documentation of the arguments, please see telegram.Bot.forward_message().

Note

Since the release of Bot API 5.5 it can be impossible to forward messages from some chats. Use the attributes telegram.Message.has_protected_content and telegram.ChatFullInfo.has_protected_content to check this.

As a workaround, it is still possible to use copy(). However, this behaviour is undocumented and might be changed by Telegram.

Returns:

On success, instance representing the message forwarded.

Returns:

Message

forward_origin: MessageOrigin | None
from_user: User | None
game: Game | None
general_forum_topic_hidden: GeneralForumTopicHidden | None
general_forum_topic_unhidden: GeneralForumTopicUnhidden | None
async get_game_high_scores(user_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.get_game_high_scores(
    chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.get_game_high_scores().

Note

You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Returns:

tuple[GameHighScore, ...] – tuple[telegram.GameHighScore]

gift: GiftInfo | None
giveaway: Giveaway | None
giveaway_completed: GiveawayCompleted | None
giveaway_created: GiveawayCreated | None
giveaway_winners: GiveawayWinners | None
group_chat_created: bool | None
has_media_spoiler: bool | None
has_protected_content: bool | None
property id: int

Shortcut for message_id.

Added in version 20.0.

Type:

int

invoice: Invoice | None
is_automatic_forward: bool | None
is_from_offline: bool | None
is_paid_post: bool | None
is_topic_message: bool | None
left_chat_member: User | None

Convenience property. If the chat of the message is not a private chat or normal group, returns a t.me link of the message.

Changed in version 20.3: For messages that are replies or part of a forum topic, the link now points to the corresponding thread view.

Type:

str

link_preview_options: LinkPreviewOptions | None
location: Location | None
media_group_id: str | None
message_auto_delete_timer_changed: MessageAutoDeleteTimerChanged | None
message_thread_id: int | None
migrate_from_chat_id: int | None
migrate_to_chat_id: int | None
new_chat_members: tuple[User, ...]
new_chat_photo: tuple[PhotoSize, ...]
new_chat_title: str | None
paid_media: PaidMediaInfo | None
paid_message_price_changed: PaidMessagePriceChanged | None
paid_star_count: int | None
parse_caption_entities(types=None)[source]

Returns a dict that maps telegram.MessageEntity to str. It contains entities from this message’s caption filtered by their telegram.MessageEntity.type attribute as the key, and the text that each entity belongs to as the value of the dict.

Note

This method should always be used instead of the caption_entities attribute, since it calculates the correct substring from the message text based on UTF-16 codepoints. See parse_entity for more info.

Parameters:

types (list[str] | None, default: None) – List of telegram.MessageEntity types as strings. If the type attribute of an entity is contained in this list, it will be returned. Defaults to a list of all types. All types can be found as constants in telegram.MessageEntity.

Returns:

A dictionary of entities mapped to the text that belongs to them, calculated based on UTF-16 codepoints.

Returns:

dict[MessageEntity, str]

parse_caption_entity(entity)[source]

Returns the text from a given telegram.MessageEntity.

Note

This method is present because Telegram calculates the offset and length in UTF-16 codepoint pairs, which some versions of Python don’t handle automatically. (That is, you can’t just slice Message.caption with the offset and length.)

Parameters:

entity (MessageEntity) – The entity to extract the text from. It must be an entity that belongs to this message.

Returns:

The text of the given entity.

Returns:

str

Raises:

RuntimeError – If the message has no caption.

parse_entities(types=None)[source]

Returns a dict that maps telegram.MessageEntity to str. It contains entities from this message filtered by their telegram.MessageEntity.type attribute as the key, and the text that each entity belongs to as the value of the dict.

Note

This method should always be used instead of the entities attribute, since it calculates the correct substring from the message text based on UTF-16 codepoints. See parse_entity for more info.

Parameters:

types (list[str] | None, default: None) – List of telegram.MessageEntity types as strings. If the type attribute of an entity is contained in this list, it will be returned. Defaults to a list of all types. All types can be found as constants in telegram.MessageEntity.

Returns:

A dictionary of entities mapped to the text that belongs to them, calculated based on UTF-16 codepoints.

Returns:

dict[MessageEntity, str]

parse_entity(entity)[source]

Returns the text from a given telegram.MessageEntity.

Note

This method is present because Telegram calculates the offset and length in UTF-16 codepoint pairs, which some versions of Python don’t handle automatically. (That is, you can’t just slice Message.text with the offset and length.)

Parameters:

entity (MessageEntity) – The entity to extract the text from. It must be an entity that belongs to this message.

Returns:

The text of the given entity.

Returns:

str

Raises:

RuntimeError – If the message has no text.

passport_data: PassportData | None
photo: tuple[PhotoSize, ...]
async pin(disable_notification=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.pin_chat_message(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.pin_chat_message().

Changed in version 21.5: Now also passes business_connection_id to telegram.Bot.pin_chat_message().

Returns:

On success, True is returned.

Returns:

bool

pinned_message: MaybeInaccessibleMessage | None
poll: Poll | None
proximity_alert_triggered: ProximityAlertTriggered | None
quote: TextQuote | None
async read_business_message(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

 await bot.read_business_message(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.read_business_message().

Added in version 22.1.

Returns:

boolbool On success, True is returned.

refunded_payment: RefundedPayment | None
async reopen_forum_topic(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.reopen_forum_topic(
    chat_id=message.chat_id, message_thread_id=message.message_thread_id, *args,
    **kwargs
 )

For the documentation of the arguments, please see telegram.Bot.reopen_forum_topic().

Added in version 20.0.

Returns:

On success, True is returned.

Returns:

bool

async reply_animation(animation, duration=None, width=None, height=None, caption=None, parse_mode=None, disable_notification=None, reply_markup=None, caption_entities=None, protect_content=None, message_thread_id=None, has_spoiler=None, thumbnail=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, show_caption_above_media=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, filename=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_animation(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_animation().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_audio(audio, duration=None, performer=None, title=None, caption=None, disable_notification=None, reply_markup=None, parse_mode=None, caption_entities=None, protect_content=None, message_thread_id=None, thumbnail=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, filename=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_audio(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_audio().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_chat_action(action, message_thread_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_chat_action(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_chat_action().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Added in version 13.2.

Returns:

On success, True is returned.

Returns:

bool

async reply_checklist(checklist, disable_notification=None, protect_content=None, message_effect_id=None, reply_parameters=None, reply_markup=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_checklist(
    business_connection_id=self.business_connection_id,
    chat_id=update.effective_message.chat_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_checklist().

Added in version 22.3.

Keyword Arguments:

do_quote (bool | dict, optional) – |do_quote|

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_contact(phone_number=None, first_name=None, last_name=None, disable_notification=None, reply_markup=None, vcard=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, contact=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_contact(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_contact().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_copy(from_chat_id, message_id, caption=None, parse_mode=None, caption_entities=None, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, reply_parameters=None, show_caption_above_media=None, allow_paid_broadcast=None, video_start_timestamp=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.copy_message(
    chat_id=message.chat.id,
    message_thread_id=update.effective_message.message_thread_id,
    message_id=message_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs
)

For the documentation of the arguments, please see telegram.Bot.copy_message().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, returns the MessageId of the sent message.

Returns:

MessageId

async reply_dice(disable_notification=None, reply_markup=None, emoji=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_dice(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_dice().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_document(document, caption=None, disable_notification=None, reply_markup=None, parse_mode=None, disable_content_type_detection=None, caption_entities=None, protect_content=None, message_thread_id=None, thumbnail=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, filename=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_document(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_document().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_game(game_short_name, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_game(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_game().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Added in version 13.2.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_html(text, disable_notification=None, reply_markup=None, entities=None, protect_content=None, message_thread_id=None, link_preview_options=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, disable_web_page_preview=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_message(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    parse_mode=ParseMode.HTML,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    business_connection_id=self.business_connection_id,
    *args,
    **kwargs,
)

Sends a message with HTML formatting.

For the documentation of the arguments, please see telegram.Bot.send_message().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_invoice(title, description, payload, currency, prices, provider_token=None, start_parameter=None, photo_url=None, photo_size=None, photo_width=None, photo_height=None, need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, is_flexible=None, disable_notification=None, reply_markup=None, provider_data=None, send_phone_number_to_provider=None, send_email_to_provider=None, max_tip_amount=None, suggested_tip_amounts=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_invoice(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_invoice().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Warning

As of API 5.2 start_parameter <telegram.Bot.send_invoice.start_parameter> is an optional argument and therefore the order of the arguments had to be changed. Use keyword arguments to make sure that the arguments are passed correctly.

Added in version 13.2.

Changed in version 13.5: As of Bot API 5.2, the parameter start_parameter <telegram.Bot.send_invoice.start_parameter> is optional.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_location(latitude=None, longitude=None, disable_notification=None, reply_markup=None, live_period=None, horizontal_accuracy=None, heading=None, proximity_alert_radius=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, location=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_location(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_location().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_markdown(text, disable_notification=None, reply_markup=None, entities=None, protect_content=None, message_thread_id=None, link_preview_options=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, disable_web_page_preview=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_message(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    parse_mode=ParseMode.MARKDOWN,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

Sends a message with Markdown version 1 formatting.

For the documentation of the arguments, please see telegram.Bot.send_message().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Note

telegram.constants.ParseMode.MARKDOWN is a legacy mode, retained by Telegram for backward compatibility. You should use reply_markdown_v2() instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_markdown_v2(text, disable_notification=None, reply_markup=None, entities=None, protect_content=None, message_thread_id=None, link_preview_options=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, disable_web_page_preview=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_message(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    parse_mode=ParseMode.MARKDOWN_V2,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    business_connection_id=self.business_connection_id,
    *args,
    **kwargs,
)

Sends a message with markdown version 2 formatting.

For the documentation of the arguments, please see telegram.Bot.send_message().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

reply_markup: InlineKeyboardMarkup | None
async reply_media_group(media, disable_notification=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None, caption=None, parse_mode=None, caption_entities=None)[source]

Shortcut for:

await bot.send_media_group(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_media_group().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

An array of the sent Messages.

Returns:

tuple[Message, ...]

Raises:

telegram.error.TelegramError

async reply_paid_media(star_count, media, caption=None, parse_mode=None, caption_entities=None, show_caption_above_media=None, disable_notification=None, protect_content=None, reply_parameters=None, reply_markup=None, payload=None, allow_paid_broadcast=None, suggested_post_parameters=None, message_thread_id=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_paid_media(
    chat_id=message.chat.id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=message.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs
)

For the documentation of the arguments, please see telegram.Bot.send_paid_media().

Added in version 21.7.

Keyword Arguments:

do_quote (bool | dict, optional) – |do_quote|

Returns:

On success, the sent message is returned.

Returns:

Message

async reply_photo(photo, caption=None, disable_notification=None, reply_markup=None, parse_mode=None, caption_entities=None, protect_content=None, message_thread_id=None, has_spoiler=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, show_caption_above_media=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, filename=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_photo(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_photo().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_poll(question, options, is_anonymous=None, type=None, allows_multiple_answers=None, correct_option_id=None, is_closed=None, disable_notification=None, reply_markup=None, explanation=None, explanation_parse_mode=None, open_period=None, close_date=None, explanation_entities=None, protect_content=None, message_thread_id=None, reply_parameters=None, question_parse_mode=None, question_entities=None, message_effect_id=None, allow_paid_broadcast=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_poll(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_poll().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_sticker(sticker, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, emoji=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_sticker(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_sticker().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_text(text, parse_mode=None, disable_notification=None, reply_markup=None, entities=None, protect_content=None, message_thread_id=None, link_preview_options=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, disable_web_page_preview=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_message(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_message().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

reply_to_checklist_task_id: int | None
reply_to_message: Message | None
reply_to_story: Story | None
async reply_venue(latitude=None, longitude=None, title=None, address=None, foursquare_id=None, disable_notification=None, reply_markup=None, foursquare_type=None, google_place_id=None, google_place_type=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, venue=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_venue(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_venue().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_video(video, duration=None, caption=None, disable_notification=None, reply_markup=None, width=None, height=None, parse_mode=None, supports_streaming=None, caption_entities=None, protect_content=None, message_thread_id=None, has_spoiler=None, thumbnail=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, show_caption_above_media=None, cover=None, start_timestamp=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, filename=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_video(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_video().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_video_note(video_note, duration=None, length=None, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, thumbnail=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, filename=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_video_note(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_video_note().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_voice(voice, duration=None, caption=None, disable_notification=None, reply_markup=None, parse_mode=None, caption_entities=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, filename=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_voice(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_voice().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

sender_boost_count: int | None
sender_business_bot: User | None
sender_chat: Chat | None
async set_game_score(user_id, score, force=None, disable_edit_message=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.set_game_score(
    chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.set_game_score().

Note

You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Returns:

On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.

Returns:

Message | bool

async set_reaction(reaction=None, is_big=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.set_message_reaction(chat_id=message.chat_id, message_id=message.message_id,
   *args, **kwargs)

For the documentation of the arguments, please see telegram.Bot.set_message_reaction().

Added in version 20.8.

Returns:

boolbool On success, True is returned.

show_caption_above_media: bool | None
sticker: Sticker | None
async stop_live_location(reply_markup=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.stop_message_live_location(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.stop_message_live_location().

Note

You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Changed in version 21.4: Now also passes business_connection_id.

Returns:

On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.

Returns:

Message | bool

async stop_poll(reply_markup=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.stop_poll(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.stop_poll().

Changed in version 21.4: Now also passes business_connection_id.

Returns:

On success, the stopped Poll with the final results is returned.

Returns:

Poll

story: Story | None
successful_payment: SuccessfulPayment | None
suggested_post_approval_failed: SuggestedPostApprovalFailed | None
suggested_post_approved: SuggestedPostApproved | None
suggested_post_declined: SuggestedPostDeclined | None
suggested_post_info: SuggestedPostInfo | None
suggested_post_paid: SuggestedPostPaid | None
suggested_post_refunded: SuggestedPostRefunded | None
supergroup_chat_created: bool | None
text: str | None
property text_html: str

Creates an HTML-formatted string from the markup entities found in the message.

Use this if you want to retrieve the message text with the entities formatted as HTML in the same way the original message was formatted.

Warning

|text_html|

Changed in version 13.10: Spoiler entities are now formatted as HTML.

Changed in version 20.3: Custom emoji entities are now supported.

Changed in version 20.8: Blockquote entities are now supported.

Returns:

Message text with entities formatted as HTML.

Return type:

str

property text_html_urled: str

Creates an HTML-formatted string from the markup entities found in the message.

Use this if you want to retrieve the message text with the entities formatted as HTML. This also formats telegram.MessageEntity.URL as a hyperlink.

Warning

|text_html|

Changed in version 13.10: Spoiler entities are now formatted as HTML.

Changed in version 20.3: Custom emoji entities are now supported.

Changed in version 20.8: Blockquote entities are now supported.

Returns:

Message text with entities formatted as HTML.

Return type:

str

property text_markdown: str

Creates an Markdown-formatted string from the markup entities found in the message using telegram.constants.ParseMode.MARKDOWN.

Use this if you want to retrieve the message text with the entities formatted as Markdown in the same way the original message was formatted.

Warning

|text_markdown|

Note

telegram.constants.ParseMode.MARKDOWN is a legacy mode, retained by Telegram for backward compatibility. You should use text_markdown_v2() instead.

Changed in version 20.5: Since custom emoji entities are not supported by MARKDOWN, this method now raises a ValueError when encountering a custom emoji.

Changed in version 20.8: Since block quotation entities are not supported by MARKDOWN, this method now raises a ValueError when encountering a block quotation.

Returns:

Message text with entities formatted as Markdown.

Return type:

str

Raises:

ValueError – If the message contains underline, strikethrough, spoiler, blockquote or nested entities.

property text_markdown_urled: str

Creates an Markdown-formatted string from the markup entities found in the message using telegram.constants.ParseMode.MARKDOWN.

Use this if you want to retrieve the message text with the entities formatted as Markdown. This also formats telegram.MessageEntity.URL as a hyperlink.

Warning

|text_markdown|

Note

telegram.constants.ParseMode.MARKDOWN is a legacy mode, retained by Telegram for backward compatibility. You should use text_markdown_v2_urled() instead.

Changed in version 20.5: Since custom emoji entities are not supported by MARKDOWN, this method now raises a ValueError when encountering a custom emoji.

Changed in version 20.8: Since block quotation entities are not supported by MARKDOWN, this method now raises a ValueError when encountering a block quotation.

Returns:

Message text with entities formatted as Markdown.

Return type:

str

Raises:

ValueError – If the message contains underline, strikethrough, spoiler, blockquote or nested entities.

property text_markdown_v2: str

Creates an Markdown-formatted string from the markup entities found in the message using telegram.constants.ParseMode.MARKDOWN_V2.

Use this if you want to retrieve the message text with the entities formatted as Markdown in the same way the original message was formatted.

Warning

|text_markdown|

Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.

Changed in version 20.3: Custom emoji entities are now supported.

Changed in version 20.8: Blockquote entities are now supported.

Returns:

Message text with entities formatted as Markdown.

Return type:

str

property text_markdown_v2_urled: str

Creates an Markdown-formatted string from the markup entities found in the message using telegram.constants.ParseMode.MARKDOWN_V2.

Use this if you want to retrieve the message text with the entities formatted as Markdown. This also formats telegram.MessageEntity.URL as a hyperlink.

Warning

|text_markdown|

Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.

Changed in version 20.3: Custom emoji entities are now supported.

Changed in version 20.8: Blockquote entities are now supported.

Returns:

Message text with entities formatted as Markdown.

Return type:

str

unique_gift: UniqueGiftInfo | None
async unpin(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.unpin_chat_message(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.unpin_chat_message().

Changed in version 21.5: Now also passes business_connection_id to telegram.Bot.pin_chat_message().

Returns:

On success, True is returned.

Returns:

bool

async unpin_all_forum_topic_messages(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.unpin_all_forum_topic_messages(
   chat_id=message.chat_id, message_thread_id=message.message_thread_id, *args,
   **kwargs
)

For the documentation of the arguments, please see telegram.Bot.unpin_all_forum_topic_messages().

Added in version 20.0.

Returns:

On success, True is returned.

Returns:

bool

users_shared: UsersShared | None
venue: Venue | None
via_bot: User | None
video: Video | None
video_chat_ended: VideoChatEnded | None
video_chat_participants_invited: VideoChatParticipantsInvited | None
video_chat_scheduled: VideoChatScheduled | None
video_chat_started: VideoChatStarted | None
video_note: VideoNote | None
voice: Voice | None
web_app_data: WebAppData | None
write_access_allowed: WriteAccessAllowed | None
class spotted.data.pending_post.PendingPost(user_id, u_message_id, g_message_id, admin_group_id, date, credit_username=None)[source]

Bases: object

Class that represents a pending post

Parameters:
  • user_id (int) – id of the user that sent the post

  • u_message_id (int) – id of the original message of the post

  • g_message_id (int) – id of the post in the group

  • admin_group_id (int) – id of the admin group

  • credit_username (str | None, default: None) – username of the user that sent the post if it’s a credit post

  • date (datetime) – when the post was sent

admin_group_id: int
classmethod create(user_message, g_message_id, admin_group_id, credit_username=None)[source]

Creates a new post and inserts it in the table of pending posts

Parameters:
  • user_message (Message) – message sent by the user that contains the post

  • g_message_id (int) – id of the post in the group

  • admin_group_id (int) – id of the admin group

  • credit_username (str | None, default: None) – username of the user that sent the post if it’s a credit post

Returns:

PendingPost – instance of the class

credit_username: str | None = None
date: datetime
delete_post()[source]

Removes all entries on a post that is no longer pending

classmethod from_group(g_message_id, admin_group_id)[source]

Retrieves a pending post from the info related to the admin group

Parameters:
  • g_message_id (int) – id of the post in the group

  • admin_group_id (int) – id of the admin group

Returns:

PendingPost | None – instance of the class

classmethod from_user(user_id)[source]

Retrieves a pending post from the user_id

Parameters:

user_id (int) – id of the author of the post

Returns:

PendingPost | None – instance of the class

g_message_id: int
static get_all(admin_group_id, before=None)[source]

Gets the list of pending posts in the specified admin group. If before is specified, returns only the one sent before that timestamp

Parameters:
  • admin_group_id (int) – id of the admin group

  • before (datetime | None, default: None) – timestamp before which messages will be considered

Returns:

list[PendingPost] – list of ids of pending posts

get_credit_username()[source]

Gets the username of the user that credited the post

Returns:

str | None – username of the user that credited the post, or None if the post is not credited

get_list_admin_votes(vote=None)[source]

Gets the list of admins that approved or rejected the post

Parameters:

vote (bool | None, default: None) – whether you look for the approve or reject votes, or None if you want all the votes

Returns:

list[int] | list[tuple[int, bool]] – list of admins that approved or rejected a pending post

get_votes(vote)[source]

Gets all the votes of a specific kind (approve or reject)

Parameters:

vote (bool) – whether you look for the approve or reject votes

Returns:

int – number of votes

save_post()[source]

Saves the pending_post in the database

Return type:

PendingPost

set_admin_vote(admin_id, approval)[source]

Adds the vote of the admin on a specific post, or update the existing vote, if needed

Parameters:
  • admin_id (int) – id of the admin that voted

  • approval (bool) – whether the vote is approval or reject

Returns:

int – number of similar votes (all the approve or the reject), or -1 if the vote wasn’t updated

u_message_id: int
user_id: int
spotted.data.pending_post.dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

class spotted.data.pending_post.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])

Bases: date

The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints.

astimezone()

tz -> convert to local time in new timezone tz

classmethod combine()

date, time -> datetime with same date and time fields

ctime()

Return ctime() style string.

date()

Return date object with same year, month and day.

dst()

Return self.tzinfo.dst(self).

fold
classmethod fromisoformat(object, /)

string -> datetime from a string in most ISO 8601 formats

classmethod fromtimestamp()

timestamp[, tz] -> tz’s local time from POSIX timestamp.

hour
isoformat()

[sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM]. sep is used to separate the year from the time, and defaults to ‘T’. The optional argument timespec specifies the number of additional terms of the time to include. Valid options are ‘auto’, ‘hours’, ‘minutes’, ‘seconds’, ‘milliseconds’ and ‘microseconds’.

max = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
microsecond
min = datetime.datetime(1, 1, 1, 0, 0)
minute
classmethod now(tz=None)

Returns new datetime object representing current time local to tz.

tz

Timezone object.

If no tz is specified, uses local timezone.

replace()

Return datetime with new specified fields.

resolution = datetime.timedelta(microseconds=1)
second
classmethod strptime()

string, format -> new datetime parsed from a string (like time.strptime()).

time()

Return time object with same time but with tzinfo=None.

timestamp()

Return POSIX timestamp as float.

timetuple()

Return time tuple, compatible with time.localtime().

timetz()

Return time object with same time and tzinfo.

tzinfo
tzname()

Return self.tzinfo.tzname(self).

classmethod utcfromtimestamp()

Construct a naive UTC datetime from a POSIX timestamp.

classmethod utcnow()

Return a new datetime representing UTC day and time.

utcoffset()

Return self.tzinfo.utcoffset(self).

utctimetuple()

Return UTC time tuple, compatible with time.localtime().

class spotted.data.pending_post.timezone

Bases: tzinfo

Fixed offset from UTC implementation of tzinfo.

dst(object, /)

Return None.

fromutc(object, /)

datetime in UTC -> datetime in local time.

max = datetime.timezone(datetime.timedelta(seconds=86340))
min = datetime.timezone(datetime.timedelta(days=-1, seconds=60))
tzname(object, /)

If name is specified when timezone is created, returns the name. Otherwise returns offset as ‘UTC(+|-)HH:MM’.

utc = datetime.timezone.utc
utcoffset(object, /)

Return fixed offset.

spotted.data.post_data module

Data management for the bot

class spotted.data.post_data.DbManager[source]

Bases: object

Class that handles the management of databases

classmethod count_from(table_name, select='*', where='', where_args=None)[source]

Returns the number of rows found with the query. Executes “SELECT COUNT(select) FROM table_name [WHERE where (with where_args)]”

Parameters:
  • table_name (str) – name of the table used in the FROM

  • select (str, default: '*') – columns considered for the query

  • where (str, default: '') – where clause, with %s placeholders for the where_args

  • where_args (tuple | None, default: None) – args used in the where clause

Returns:

int – number of rows

classmethod delete_from(table_name, where='', where_args=None)[source]

Deletes the rows from the specified table, where the condition, when set, is satisfied. Executes “DELETE FROM table_name [WHERE where (with where_args)]”

Parameters:
  • table_name (str) – name of the table used in the DELETE FROM

  • where (str, default: '') – where clause, with %s placeholders for the where args

  • where_args (tuple | None, default: None) – args used in the where clause

classmethod get_db()[source]

Creates the connection to the database. It can be sqlite or postgres

Returns:

tuple[Connection, Cursor] – sqlite database connection and cursor

classmethod insert_into(table_name, values, columns='', multiple_rows=False)[source]

Inserts the specified values in the database. Executes “INSERT INTO table_name ([columns]) VALUES (placeholders)”

Parameters:
  • table_name (str) – name of the table used in the INSERT INTO

  • values (tuple) – values to be inserted. If multiple_rows is true, tuple of tuples of values to be inserted

  • columns (tuple | str, default: '') – columns that will be inserted, as a tuple of strings

  • multiple_rows (bool, default: False) – whether or not multiple rows will be inserted at the same time

classmethod query_from_file(*file_path)[source]

Commits all the queries in the specified file. The queries must be separated by a —– string Should not be used to select something

Parameters:

file_path (str) – path of the text file containing the queries

classmethod query_from_string(*queries)[source]

Commits all the queries in the string Should not be used to select something

Parameters:

queries (str) – tuple of queries

static register_adapters_and_converters()[source]

Registers the adapter and converters for the datetime type. Needed from python 3.12 onwards, as the default option has been deprecated

static row_factory(cursor, row)[source]

Converts the rows from the database into a dictionary

Parameters:
  • cursor (Cursor) – database cursor

  • row (dict) – row from the database

Returns:

dict – dictionary containing the row. The keys are the column names

classmethod select_from(table_name, select='*', where='', where_args=None, group_by='', order_by='')[source]

Returns the results of a query. Executes “SELECT select FROM table_name [WHERE where (with where_args)] [GROUP_BY group_by] [ORDER BY order_by]”

Parameters:
  • table_name (str) – name of the table used in the FROM

  • select (str, default: '*') – columns considered for the query

  • where (str, default: '') – where clause, with %s placeholders for the where_args

  • where_args (tuple | None, default: None) – args used in the where clause

  • group_by (str, default: '') – group by clause

  • order_by (str, default: '') – order by clause

Returns:

list – rows from the select

classmethod update_from(table_name, set_clause, where='', args=None)[source]

Updates the rows from the specified table, where the condition, when set, is satisfied. Executes “UPDATE table_name SET set_clause (with args) [WHERE where (with args)]”

Parameters:
  • table_name (str) – name of the table used in the DELETE FROM

  • set_clause (str) – set clause, with %s placeholders

  • where (str, default: '') – where clause, with %s placeholders for the where args

  • args (tuple | None, default: None) – args used both in the set clause and in the where clause, in this order

class spotted.data.post_data.PostData[source]

Bases: object

Class that handles the management of persistent data fetch or manipulation in the post bot

static get_n_posts()[source]

Gets the total number of posts

Returns:

int – total number of posts

spotted.data.published_post module

Published post management

class spotted.data.published_post.DbManager[source]

Bases: object

Class that handles the management of databases

classmethod count_from(table_name, select='*', where='', where_args=None)[source]

Returns the number of rows found with the query. Executes “SELECT COUNT(select) FROM table_name [WHERE where (with where_args)]”

Parameters:
  • table_name (str) – name of the table used in the FROM

  • select (str, default: '*') – columns considered for the query

  • where (str, default: '') – where clause, with %s placeholders for the where_args

  • where_args (tuple | None, default: None) – args used in the where clause

Returns:

int – number of rows

classmethod delete_from(table_name, where='', where_args=None)[source]

Deletes the rows from the specified table, where the condition, when set, is satisfied. Executes “DELETE FROM table_name [WHERE where (with where_args)]”

Parameters:
  • table_name (str) – name of the table used in the DELETE FROM

  • where (str, default: '') – where clause, with %s placeholders for the where args

  • where_args (tuple | None, default: None) – args used in the where clause

classmethod get_db()[source]

Creates the connection to the database. It can be sqlite or postgres

Returns:

tuple[Connection, Cursor] – sqlite database connection and cursor

classmethod insert_into(table_name, values, columns='', multiple_rows=False)[source]

Inserts the specified values in the database. Executes “INSERT INTO table_name ([columns]) VALUES (placeholders)”

Parameters:
  • table_name (str) – name of the table used in the INSERT INTO

  • values (tuple) – values to be inserted. If multiple_rows is true, tuple of tuples of values to be inserted

  • columns (tuple | str, default: '') – columns that will be inserted, as a tuple of strings

  • multiple_rows (bool, default: False) – whether or not multiple rows will be inserted at the same time

classmethod query_from_file(*file_path)[source]

Commits all the queries in the specified file. The queries must be separated by a —– string Should not be used to select something

Parameters:

file_path (str) – path of the text file containing the queries

classmethod query_from_string(*queries)[source]

Commits all the queries in the string Should not be used to select something

Parameters:

queries (str) – tuple of queries

static register_adapters_and_converters()[source]

Registers the adapter and converters for the datetime type. Needed from python 3.12 onwards, as the default option has been deprecated

static row_factory(cursor, row)[source]

Converts the rows from the database into a dictionary

Parameters:
  • cursor (Cursor) – database cursor

  • row (dict) – row from the database

Returns:

dict – dictionary containing the row. The keys are the column names

classmethod select_from(table_name, select='*', where='', where_args=None, group_by='', order_by='')[source]

Returns the results of a query. Executes “SELECT select FROM table_name [WHERE where (with where_args)] [GROUP_BY group_by] [ORDER BY order_by]”

Parameters:
  • table_name (str) – name of the table used in the FROM

  • select (str, default: '*') – columns considered for the query

  • where (str, default: '') – where clause, with %s placeholders for the where_args

  • where_args (tuple | None, default: None) – args used in the where clause

  • group_by (str, default: '') – group by clause

  • order_by (str, default: '') – order by clause

Returns:

list – rows from the select

classmethod update_from(table_name, set_clause, where='', args=None)[source]

Updates the rows from the specified table, where the condition, when set, is satisfied. Executes “UPDATE table_name SET set_clause (with args) [WHERE where (with args)]”

Parameters:
  • table_name (str) – name of the table used in the DELETE FROM

  • set_clause (str) – set clause, with %s placeholders

  • where (str, default: '') – where clause, with %s placeholders for the where args

  • args (tuple | None, default: None) – args used both in the set clause and in the where clause, in this order

class spotted.data.published_post.PublishedPost(channel_id, c_message_id, date)[source]

Bases: object

Class that represents a published post

Parameters:
  • channel_id (int) – id of the channel

  • c_message_id (int) – id of the post in the channel

c_message_id: int
channel_id: int
classmethod create(channel_id, c_message_id)[source]

Inserts a new post in the table of published posts

Parameters:
  • channel_id (int) – id of the channel

  • c_message_id (int) – id of the post in the channel

Returns:

PublishedPost – instance of the class

date: datetime
classmethod from_channel(channel_id, c_message_id)[source]

Retrieves a published post from the info related to the channel

Parameters:
  • channel_id (int) – id of the channel

  • c_message_id (int) – id of the post in the channel

Returns:

PublishedPost | None – instance of the class

save_post()[source]

Saves the published_post in the database

Return type:

PublishedPost

spotted.data.published_post.dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

class spotted.data.published_post.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])

Bases: date

The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints.

astimezone()

tz -> convert to local time in new timezone tz

classmethod combine()

date, time -> datetime with same date and time fields

ctime()

Return ctime() style string.

date()

Return date object with same year, month and day.

dst()

Return self.tzinfo.dst(self).

fold
classmethod fromisoformat(object, /)

string -> datetime from a string in most ISO 8601 formats

classmethod fromtimestamp()

timestamp[, tz] -> tz’s local time from POSIX timestamp.

hour
isoformat()

[sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM]. sep is used to separate the year from the time, and defaults to ‘T’. The optional argument timespec specifies the number of additional terms of the time to include. Valid options are ‘auto’, ‘hours’, ‘minutes’, ‘seconds’, ‘milliseconds’ and ‘microseconds’.

max = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
microsecond
min = datetime.datetime(1, 1, 1, 0, 0)
minute
classmethod now(tz=None)

Returns new datetime object representing current time local to tz.

tz

Timezone object.

If no tz is specified, uses local timezone.

replace()

Return datetime with new specified fields.

resolution = datetime.timedelta(microseconds=1)
second
classmethod strptime()

string, format -> new datetime parsed from a string (like time.strptime()).

time()

Return time object with same time but with tzinfo=None.

timestamp()

Return POSIX timestamp as float.

timetuple()

Return time tuple, compatible with time.localtime().

timetz()

Return time object with same time and tzinfo.

tzinfo
tzname()

Return self.tzinfo.tzname(self).

classmethod utcfromtimestamp()

Construct a naive UTC datetime from a POSIX timestamp.

classmethod utcnow()

Return a new datetime representing UTC day and time.

utcoffset()

Return self.tzinfo.utcoffset(self).

utctimetuple()

Return UTC time tuple, compatible with time.localtime().

spotted.data.report module

Reports management

class spotted.data.report.DbManager[source]

Bases: object

Class that handles the management of databases

classmethod count_from(table_name, select='*', where='', where_args=None)[source]

Returns the number of rows found with the query. Executes “SELECT COUNT(select) FROM table_name [WHERE where (with where_args)]”

Parameters:
  • table_name (str) – name of the table used in the FROM

  • select (str, default: '*') – columns considered for the query

  • where (str, default: '') – where clause, with %s placeholders for the where_args

  • where_args (tuple | None, default: None) – args used in the where clause

Returns:

int – number of rows

classmethod delete_from(table_name, where='', where_args=None)[source]

Deletes the rows from the specified table, where the condition, when set, is satisfied. Executes “DELETE FROM table_name [WHERE where (with where_args)]”

Parameters:
  • table_name (str) – name of the table used in the DELETE FROM

  • where (str, default: '') – where clause, with %s placeholders for the where args

  • where_args (tuple | None, default: None) – args used in the where clause

classmethod get_db()[source]

Creates the connection to the database. It can be sqlite or postgres

Returns:

tuple[Connection, Cursor] – sqlite database connection and cursor

classmethod insert_into(table_name, values, columns='', multiple_rows=False)[source]

Inserts the specified values in the database. Executes “INSERT INTO table_name ([columns]) VALUES (placeholders)”

Parameters:
  • table_name (str) – name of the table used in the INSERT INTO

  • values (tuple) – values to be inserted. If multiple_rows is true, tuple of tuples of values to be inserted

  • columns (tuple | str, default: '') – columns that will be inserted, as a tuple of strings

  • multiple_rows (bool, default: False) – whether or not multiple rows will be inserted at the same time

classmethod query_from_file(*file_path)[source]

Commits all the queries in the specified file. The queries must be separated by a —– string Should not be used to select something

Parameters:

file_path (str) – path of the text file containing the queries

classmethod query_from_string(*queries)[source]

Commits all the queries in the string Should not be used to select something

Parameters:

queries (str) – tuple of queries

static register_adapters_and_converters()[source]

Registers the adapter and converters for the datetime type. Needed from python 3.12 onwards, as the default option has been deprecated

static row_factory(cursor, row)[source]

Converts the rows from the database into a dictionary

Parameters:
  • cursor (Cursor) – database cursor

  • row (dict) – row from the database

Returns:

dict – dictionary containing the row. The keys are the column names

classmethod select_from(table_name, select='*', where='', where_args=None, group_by='', order_by='')[source]

Returns the results of a query. Executes “SELECT select FROM table_name [WHERE where (with where_args)] [GROUP_BY group_by] [ORDER BY order_by]”

Parameters:
  • table_name (str) – name of the table used in the FROM

  • select (str, default: '*') – columns considered for the query

  • where (str, default: '') – where clause, with %s placeholders for the where_args

  • where_args (tuple | None, default: None) – args used in the where clause

  • group_by (str, default: '') – group by clause

  • order_by (str, default: '') – order by clause

Returns:

list – rows from the select

classmethod update_from(table_name, set_clause, where='', args=None)[source]

Updates the rows from the specified table, where the condition, when set, is satisfied. Executes “UPDATE table_name SET set_clause (with args) [WHERE where (with args)]”

Parameters:
  • table_name (str) – name of the table used in the DELETE FROM

  • set_clause (str) – set clause, with %s placeholders

  • where (str, default: '') – where clause, with %s placeholders for the where args

  • args (tuple | None, default: None) – args used both in the set clause and in the where clause, in this order

class spotted.data.report.Message(message_id, date, chat, from_user=None, reply_to_message=None, edit_date=None, text=None, entities=None, caption_entities=None, audio=None, document=None, game=None, photo=None, sticker=None, video=None, voice=None, video_note=None, new_chat_members=None, caption=None, contact=None, location=None, venue=None, left_chat_member=None, new_chat_title=None, new_chat_photo=None, delete_chat_photo=None, group_chat_created=None, supergroup_chat_created=None, channel_chat_created=None, migrate_to_chat_id=None, migrate_from_chat_id=None, pinned_message=None, invoice=None, successful_payment=None, author_signature=None, media_group_id=None, connected_website=None, animation=None, passport_data=None, poll=None, reply_markup=None, dice=None, via_bot=None, proximity_alert_triggered=None, sender_chat=None, video_chat_started=None, video_chat_ended=None, video_chat_participants_invited=None, message_auto_delete_timer_changed=None, video_chat_scheduled=None, is_automatic_forward=None, has_protected_content=None, web_app_data=None, is_topic_message=None, message_thread_id=None, forum_topic_created=None, forum_topic_closed=None, forum_topic_reopened=None, forum_topic_edited=None, general_forum_topic_hidden=None, general_forum_topic_unhidden=None, write_access_allowed=None, has_media_spoiler=None, chat_shared=None, story=None, giveaway=None, giveaway_completed=None, giveaway_created=None, giveaway_winners=None, users_shared=None, link_preview_options=None, external_reply=None, quote=None, forward_origin=None, reply_to_story=None, boost_added=None, sender_boost_count=None, business_connection_id=None, sender_business_bot=None, is_from_offline=None, chat_background_set=None, effect_id=None, show_caption_above_media=None, paid_media=None, refunded_payment=None, gift=None, unique_gift=None, paid_message_price_changed=None, paid_star_count=None, direct_message_price_changed=None, checklist=None, checklist_tasks_done=None, checklist_tasks_added=None, is_paid_post=None, direct_messages_topic=None, reply_to_checklist_task_id=None, suggested_post_declined=None, suggested_post_paid=None, suggested_post_refunded=None, suggested_post_info=None, suggested_post_approved=None, suggested_post_approval_failed=None, *, api_kwargs=None)[source]

Bases: MaybeInaccessibleMessage

This object represents a message.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their message_id and chat are equal.

Note

In Python from is a reserved word. Use from_user instead.

Changed in version 21.0: Removed deprecated arguments and attributes user_shared, forward_from, forward_from_chat, forward_from_message_id, forward_signature, forward_sender_name and forward_date.

Changed in version 20.8: * This class is now a subclass of telegram.MaybeInaccessibleMessage. * The pinned_message now can be either telegram.Message or telegram.InaccessibleMessage.

Changed in version 20.0:

  • The arguments and attributes voice_chat_scheduled, voice_chat_started and voice_chat_ended, voice_chat_participants_invited were renamed to video_chat_scheduled/video_chat_scheduled, video_chat_started/video_chat_started, video_chat_ended/video_chat_ended and video_chat_participants_invited/video_chat_participants_invited, respectively, in accordance to Bot API 6.0.

  • The following are now keyword-only arguments in Bot methods: {read, write, connect, pool}_timeout, api_kwargs, contact, quote, filename, loaction, venue. Use a named argument for those, and notice that some positional arguments changed position as a result.

Parameters:
  • message_id (int) – Unique message identifier inside this chat. In specific instances (e.g., message containing a video sent to a big chat), the server might automatically schedule a message instead of sending it immediately. In such cases, this field will be 0 and the relevant message will be unusable until it is actually sent.

  • from_user (User | None, default: None) – Sender of the message; may be empty for messages sent to channels. For backward compatibility, if the message was sent on behalf of a chat, the field contains a fake sender user in non-channel chats.

  • sender_chat (Chat | None, default: None) – Sender of the message when sent on behalf of a chat. For example, the supergroup itself for messages sent by its anonymous administrators or a linked channel for messages automatically forwarded to the channel’s discussion group. For backward compatibility, if the message was sent on behalf of a chat, the field from contains a fake sender user in non-channel chats.

  • date (datetime) –

    Date the message was sent in Unix time. Converted to datetime.datetime.

    Changed in version 20.3: |datetime_localization|

  • chat (Chat) – Conversation the message belongs to.

  • is_automatic_forward (bool | None, default: None) –

    True, if the message is a channel post that was automatically forwarded to the connected discussion group.

    Added in version 13.9.

  • reply_to_message (Message | None, default: None) – For replies, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply.

  • edit_date (datetime | None, default: None) –

    Date the message was last edited in Unix time. Converted to datetime.datetime.

    Changed in version 20.3: |datetime_localization|

  • has_protected_content (bool | None, default: None) –

    True, if the message can’t be forwarded.

    Added in version 13.9.

  • is_from_offline (bool | None, default: None) –

    True, if the message was sent by an implicit action, for example, as an away or a greeting business message, or as a scheduled message.

    Added in version 21.1.

  • media_group_id (str | None, default: None) – The unique identifier of a media message group this message belongs to.

  • text (str | None, default: None) – For text messages, the actual UTF-8 text of the message, 0-telegram.constants.MessageLimit.MAX_TEXT_LENGTH characters.

  • entities (Sequence[MessageEntity] | None, default: None) –

    For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text. See parse_entity and parse_entities methods for how to use properly. This list is empty if the message does not contain entities.

    Changed in version 20.0: |sequenceclassargs|

  • link_preview_options (LinkPreviewOptions | None, default: None) –

    Options used for link preview generation for the message, if it is a text message and link preview options were changed.

    Added in version 20.8.

  • suggested_post_info (SuggestedPostInfo | None, default: None) –

    Information about suggested post parameters if the message is a suggested post in a channel direct messages chat. If the message is an approved or declined suggested post, then it can’t be edited.

    Added in version 22.4.

  • effect_id (str | None, default: None) –

    Unique identifier of the message effect added to the message.

    Added in version 21.3.

  • caption_entities (Sequence[MessageEntity] | None, default: None) –

    For messages with a Caption. Special entities like usernames, URLs, bot commands, etc. that appear in the caption. See Message.parse_caption_entity and parse_caption_entities methods for how to use properly. This list is empty if the message does not contain caption entities.

    Changed in version 20.0: |sequenceclassargs|

  • show_caption_above_media (bool | None, default: None) –

    |show_cap_above_med|

    Added in version 21.3.

  • audio (Audio | None, default: None) – Message is an audio file, information about the file.

  • document (Document | None, default: None) – Message is a general file, information about the file.

  • animation (Animation | None, default: None) – Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set.

  • game (Game | None, default: None) – Message is a game, information about the game. More about games >>.

  • photo (Sequence[PhotoSize] | None, default: None) –

    Message is a photo, available sizes of the photo. This list is empty if the message does not contain a photo.

    Changed in version 20.0: |sequenceclassargs|

  • sticker (Sticker | None, default: None) – Message is a sticker, information about the sticker.

  • story (Story | None, default: None) –

    Message is a forwarded story.

    Added in version 20.5.

  • video (Video | None, default: None) – Message is a video, information about the video.

  • voice (Voice | None, default: None) – Message is a voice message, information about the file.

  • video_note (VideoNote | None, default: None) –

    Message is a video note, information about the video message.

  • new_chat_members (Sequence[User] | None, default: None) –

    New members that were added to the group or supergroup and information about them (the bot itself may be one of these members). This list is empty if the message does not contain new chat members.

    Changed in version 20.0: |sequenceclassargs|

  • caption (str | None, default: None) – Caption for the animation, audio, document, paid media, photo, video or voice, 0-telegram.constants.MessageLimit.CAPTION_LENGTH characters.

  • contact (Contact | None, default: None) – Message is a shared contact, information about the contact.

  • location (Location | None, default: None) – Message is a shared location, information about the location.

  • venue (Venue | None, default: None) – Message is a venue, information about the venue. For backward compatibility, when this field is set, the location field will also be set.

  • left_chat_member (User | None, default: None) – A member was removed from the group, information about them (this member may be the bot itself).

  • new_chat_title (str | None, default: None) – A chat title was changed to this value.

  • new_chat_photo (Sequence[PhotoSize] | None, default: None) –

    A chat photo was changed to this value. This list is empty if the message does not contain a new chat photo.

    Changed in version 20.0: |sequenceclassargs|

  • delete_chat_photo (bool | None, default: None) – Service message: The chat photo was deleted.

  • group_chat_created (bool | None, default: None) – Service message: The group has been created.

  • supergroup_chat_created (bool | None, default: None) – Service message: The supergroup has been created. This field can’t be received in a message coming through updates, because bot can’t be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup.

  • channel_chat_created (bool | None, default: None) – Service message: The channel has been created. This field can’t be received in a message coming through updates, because bot can’t be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel.

  • message_auto_delete_timer_changed (MessageAutoDeleteTimerChanged | None, default: None) –

    Service message: auto-delete timer settings changed in the chat.

    Added in version 13.4.

  • migrate_to_chat_id (int | None, default: None) – The group has been migrated to a supergroup with the specified identifier.

  • migrate_from_chat_id (int | None, default: None) – The supergroup has been migrated from a group with the specified identifier.

  • pinned_message (MaybeInaccessibleMessage | None, default: None) –

    Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply.

    Changed in version 20.8: This attribute now is either telegram.Message or telegram.InaccessibleMessage.

  • invoice (Invoice | None, default: None) – Message is an invoice for a payment, information about the invoice. More about payments >>.

  • successful_payment (SuccessfulPayment | None, default: None) – Message is a service message about a successful payment, information about the payment. More about payments >>.

  • connected_website (str | None, default: None) –

    The domain name of the website on which the user has logged in. More about Telegram Login >>.

  • author_signature (str | None, default: None) – Signature of the post author for messages in channels, or the custom title of an anonymous group administrator.

  • paid_star_count (int | None, default: None) –

    The number of Telegram Stars that were paid by the sender of the message to send it

    Added in version 22.1.

  • passport_data (PassportData | None, default: None) – Telegram Passport data.

  • poll (Poll | None, default: None) – Message is a native poll, information about the poll.

  • dice (Dice | None, default: None) – Message is a dice with random value.

  • via_bot (User | None, default: None) – Bot through which message was sent.

  • proximity_alert_triggered (ProximityAlertTriggered | None, default: None) – Service message. A user in the chat triggered another user’s proximity alert while sharing Live Location.

  • video_chat_scheduled (VideoChatScheduled | None, default: None) –

    Service message: video chat scheduled.

    Added in version 20.0.

  • video_chat_started (VideoChatStarted | None, default: None) –

    Service message: video chat started.

    Added in version 20.0.

  • video_chat_ended (VideoChatEnded | None, default: None) –

    Service message: video chat ended.

    Added in version 20.0.

  • video_chat_participants_invited (VideoChatParticipantsInvited | None, default: None) –

    Service message: new participants invited to a video chat.

    Added in version 20.0.

  • web_app_data (WebAppData | None, default: None) –

    Service message: data sent by a Web App.

    Added in version 20.0.

  • reply_markup (InlineKeyboardMarkup | None, default: None) – Inline keyboard attached to the message. ~telegram.InlineKeyboardButton.login_url buttons are represented as ordinary url buttons.

  • is_topic_message (bool | None, default: None) –

    True, if the message is sent to a forum topic.

    Added in version 20.0.

  • message_thread_id (int | None, default: None) –

    Unique identifier of a message thread to which the message belongs; for supergroups only.

    Added in version 20.0.

  • forum_topic_created (ForumTopicCreated | None, default: None) –

    Service message: forum topic created.

    Added in version 20.0.

  • forum_topic_closed (ForumTopicClosed | None, default: None) –

    Service message: forum topic closed.

    Added in version 20.0.

  • forum_topic_reopened (ForumTopicReopened | None, default: None) –

    Service message: forum topic reopened.

    Added in version 20.0.

  • forum_topic_edited (ForumTopicEdited | None, default: None) –

    Service message: forum topic edited.

    Added in version 20.0.

  • general_forum_topic_hidden (GeneralForumTopicHidden | None, default: None) –

    Service message: General forum topic hidden.

    Added in version 20.0.

  • general_forum_topic_unhidden (GeneralForumTopicUnhidden | None, default: None) –

    Service message: General forum topic unhidden.

    Added in version 20.0.

  • write_access_allowed (WriteAccessAllowed | None, default: None) –

    Service message: the user allowed the bot to write messages after adding it to the attachment or side menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method requestWriteAccess.

    Added in version 20.0.

  • has_media_spoiler (bool | None, default: None) –

    True, if the message media is covered by a spoiler animation.

    Added in version 20.0.

  • checklist (Checklist | None, default: None) –

    Message is a checklist

    Added in version 22.3.

  • users_shared (UsersShared | None, default: None) –

    Service message: users were shared with the bot

    Added in version 20.8.

  • chat_shared (ChatShared | None, default: None) –

    Service message: a chat was shared with the bot.

    Added in version 20.1.

  • gift (GiftInfo | None, default: None) –

    Service message: a regular gift was sent or received.

    Added in version 22.1.

  • unique_gift (UniqueGiftInfo | None, default: None) –

    Service message: a unique gift was sent or received

    Added in version 22.1.

  • giveaway_created (GiveawayCreated | None, default: None) –

    Service message: a scheduled giveaway was created

    Added in version 20.8.

  • giveaway (Giveaway | None, default: None) –

    The message is a scheduled giveaway message

    Added in version 20.8.

  • giveaway_winners (GiveawayWinners | None, default: None) –

    A giveaway with public winners was completed

    Added in version 20.8.

  • giveaway_completed (GiveawayCompleted | None, default: None) –

    Service message: a giveaway without public winners was completed

    Added in version 20.8.

  • paid_message_price_changed (PaidMessagePriceChanged | None, default: None) –

    Service message: the price for paid messages has changed in the chat

    Added in version 22.1.

  • suggested_post_approved (SuggestedPostApproved | None, default: None) –

    Service message: a suggested post was approved.

    Added in version 22.4.

  • suggested_post_approval_failed (SuggestedPostApprovalFailed | None, default: None) –

    Service message: approval of a suggested post has failed.

    Added in version 22.4.

  • suggested_post_declined (SuggestedPostDeclined | None, default: None) –

    Service message: a suggested post was declined.

    Added in version 22.4.

  • suggested_post_paid (SuggestedPostPaid | None, default: None) –

    Service message: payment for a suggested post was received.

    Added in version 22.4.

  • suggested_post_refunded (SuggestedPostRefunded | None, default: None) –

    Service message: payment for a suggested post was refunded.

    Added in version 22.4.

  • external_reply (ExternalReplyInfo | None, default: None) –

    Information about the message that is being replied to, which may come from another chat or forum topic.

    Added in version 20.8.

  • quote (TextQuote | None, default: None) –

    For replies that quote part of the original message, the quoted part of the message.

    Added in version 20.8.

  • forward_origin (MessageOrigin | None, default: None) –

    Information about the original message for forwarded messages

    Added in version 20.8.

  • reply_to_story (Story | None, default: None) –

    For replies to a story, the original story.

    Added in version 21.0.

  • boost_added (ChatBoostAdded | None, default: None) –

    Service message: user boosted the chat.

    Added in version 21.0.

  • sender_boost_count (int | None, default: None) –

    If the sender of the message boosted the chat, the number of boosts added by the user.

    Added in version 21.0.

  • business_connection_id (str | None, default: None) –

    Unique identifier of the business connection from which the message was received. If non-empty, the message belongs to a chat of the corresponding business account that is independent from any potential bot chat which might share the same identifier.

    Added in version 21.1.

  • sender_business_bot (User | None, default: None) –

    The bot that actually sent the message on behalf of the business account. Available only for outgoing messages sent on behalf of the connected business account.

    Added in version 21.1.

  • chat_background_set (ChatBackground | None, default: None) –

    Service message: chat background set.

    Added in version 21.2.

  • checklist_tasks_done (ChecklistTasksDone | None, default: None) –

    Service message: some tasks in a checklist were marked as done or not done

    Added in version 22.3.

  • checklist_tasks_added (ChecklistTasksAdded | None, default: None) –

    Service message: tasks were added to a checklist

    Added in version 22.3.

  • paid_media (PaidMediaInfo | None, default: None) –

    Message contains paid media; information about the paid media.

    Added in version 21.4.

  • refunded_payment (RefundedPayment | None, default: None) –

    Message is a service message about a refunded payment, information about the payment.

    Added in version 21.4.

  • direct_message_price_changed (DirectMessagePriceChanged | None, default: None) –

    Service message: the price for paid messages in the corresponding direct messages chat of a channel has changed.

    Added in version 22.3.

  • is_paid_post (bool | None, default: None) –

    True, if the message is a paid post. Note that such posts must not be deleted for 24 hours to receive the payment and can’t be edited.

    Added in version 22.4.

  • direct_messages_topic (DirectMessagesTopic | None, default: None) –

    Information about the direct messages chat topic that contains the message.

    Added in version 22.4.

  • reply_to_checklist_task_id (int | None, default: None) –

    Identifier of the specific checklist task that is being replied to.

    Added in version 22.4.

message_id

Unique message identifier inside this chat. In specific instances (e.g., message containing a video sent to a big chat), the server might automatically schedule a message instead of sending it immediately. In such cases, this field will be 0 and the relevant message will be unusable until it is actually sent.

Type:

int

from_user

Optional. Sender of the message; may be empty for messages sent to channels. For backward compatibility, if the message was sent on behalf of a chat, the field contains a fake sender user in non-channel chats.

Type:

telegram.User

sender_chat

Optional. Sender of the message when sent on behalf of a chat. For example, the supergroup itself for messages sent by its anonymous administrators or a linked channel for messages automatically forwarded to the channel’s discussion group. For backward compatibility, if the message was sent on behalf of a chat, the field from contains a fake sender user in non-channel chats.

Type:

telegram.Chat

date

Date the message was sent in Unix time. Converted to datetime.datetime.

Changed in version 20.3: |datetime_localization|

Type:

datetime.datetime

chat

Conversation the message belongs to.

Type:

telegram.Chat

is_automatic_forward

Optional. True, if the message is a channel post that was automatically forwarded to the connected discussion group.

Added in version 13.9.

Type:

bool

reply_to_message

Optional. For replies, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply.

Type:

telegram.Message

edit_date

Optional. Date the message was last edited in Unix time. Converted to datetime.datetime.

Changed in version 20.3: |datetime_localization|

Type:

datetime.datetime

has_protected_content

Optional. True, if the message can’t be forwarded.

Added in version 13.9.

Type:

bool

is_from_offline

Optional. True, if the message was sent by an implicit action, for example, as an away or a greeting business message, or as a scheduled message.

Added in version 21.1.

Type:

bool

media_group_id

Optional. The unique identifier of a media message group this message belongs to.

Type:

str

text

Optional. For text messages, the actual UTF-8 text of the message, 0-telegram.constants.MessageLimit.MAX_TEXT_LENGTH characters.

Type:

str

entities

Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text. See parse_entity and parse_entities methods for how to use properly. This list is empty if the message does not contain entities.

Changed in version 20.0: |tupleclassattrs|

Type:

tuple[telegram.MessageEntity]

Optional. Options used for link preview generation for the message, if it is a text message and link preview options were changed.

Added in version 20.8.

Type:

telegram.LinkPreviewOptions

suggested_post_info

Optional. Information about suggested post parameters if the message is a suggested post in a channel direct messages chat. If the message is an approved or declined suggested post, then it can’t be edited.

Added in version 22.4.

Type:

telegram.SuggestedPostInfo

effect_id

Optional. Unique identifier of the message effect added to the message.

Added in version 21.3.

Type:

str

caption_entities

Optional. For messages with a Caption. Special entities like usernames, URLs, bot commands, etc. that appear in the caption. See Message.parse_caption_entity and parse_caption_entities methods for how to use properly. This list is empty if the message does not contain caption entities.

Changed in version 20.0: |tupleclassattrs|

Type:

tuple[telegram.MessageEntity]

show_caption_above_media

Optional. |show_cap_above_med|

Added in version 21.3.

Type:

bool

audio

Optional. Message is an audio file, information about the file.

See also

Working with Files and Media <Working-with-Files-and-Media>

Type:

telegram.Audio

document

Optional. Message is a general file, information about the file.

See also

Working with Files and Media <Working-with-Files-and-Media>

Type:

telegram.Document

animation

Optional. Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set.

See also

Working with Files and Media <Working-with-Files-and-Media>

Type:

telegram.Animation

game

Optional. Message is a game, information about the game. More about games >>.

Type:

telegram.Game

photo

Optional. Message is a photo, available sizes of the photo. This list is empty if the message does not contain a photo.

See also

Working with Files and Media <Working-with-Files-and-Media>

Changed in version 20.0: |tupleclassattrs|

Type:

tuple[telegram.PhotoSize]

sticker

Optional. Message is a sticker, information about the sticker.

See also

Working with Files and Media <Working-with-Files-and-Media>

Type:

telegram.Sticker

story

Optional. Message is a forwarded story.

Added in version 20.5.

Type:

telegram.Story

video

Optional. Message is a video, information about the video.

See also

Working with Files and Media <Working-with-Files-and-Media>

Type:

telegram.Video

voice

Optional. Message is a voice message, information about the file.

See also

Working with Files and Media <Working-with-Files-and-Media>

Type:

telegram.Voice

video_note

Optional. Message is a video note, information about the video message.

See also

Working with Files and Media <Working-with-Files-and-Media>

Type:

telegram.VideoNote

new_chat_members

Optional. New members that were added to the group or supergroup and information about them (the bot itself may be one of these members). This list is empty if the message does not contain new chat members.

Changed in version 20.0: |tupleclassattrs|

Type:

tuple[telegram.User]

caption

Optional. Caption for the animation, audio, document, paid media, photo, video or voice, 0-telegram.constants.MessageLimit.CAPTION_LENGTH characters.

Type:

str

contact

Optional. Message is a shared contact, information about the contact.

Type:

telegram.Contact

location

Optional. Message is a shared location, information about the location.

Type:

telegram.Location

venue

Optional. Message is a venue, information about the venue. For backward compatibility, when this field is set, the location field will also be set.

Type:

telegram.Venue

left_chat_member

Optional. A member was removed from the group, information about them (this member may be the bot itself).

Type:

telegram.User

new_chat_title

Optional. A chat title was changed to this value.

Type:

str

new_chat_photo

A chat photo was changed to this value. This list is empty if the message does not contain a new chat photo.

Changed in version 20.0: |tupleclassattrs|

Type:

tuple[telegram.PhotoSize]

delete_chat_photo

Optional. Service message: The chat photo was deleted.

Type:

bool

group_chat_created

Optional. Service message: The group has been created.

Type:

bool

supergroup_chat_created

Optional. Service message: The supergroup has been created. This field can’t be received in a message coming through updates, because bot can’t be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup.

Type:

bool

channel_chat_created

Optional. Service message: The channel has been created. This field can’t be received in a message coming through updates, because bot can’t be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel.

Type:

bool

message_auto_delete_timer_changed

Optional. Service message: auto-delete timer settings changed in the chat.

Added in version 13.4.

Type:

telegram.MessageAutoDeleteTimerChanged

migrate_to_chat_id

Optional. The group has been migrated to a supergroup with the specified identifier.

Type:

int

migrate_from_chat_id

Optional. The supergroup has been migrated from a group with the specified identifier.

Type:

int

pinned_message

Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply.

Changed in version 20.8: This attribute now is either telegram.Message or telegram.InaccessibleMessage.

Type:

telegram.MaybeInaccessibleMessage

invoice

Optional. Message is an invoice for a payment, information about the invoice. More about payments >>.

Type:

telegram.Invoice

successful_payment

Optional. Message is a service message about a successful payment, information about the payment. More about payments >>.

Type:

telegram.SuccessfulPayment

connected_website

Optional. The domain name of the website on which the user has logged in. More about Telegram Login >>.

Type:

str

author_signature

Optional. Signature of the post author for messages in channels, or the custom title of an anonymous group administrator.

Type:

str

paid_star_count

Optional. The number of Telegram Stars that were paid by the sender of the message to send it

Added in version 22.1.

Type:

int

passport_data

Optional. Telegram Passport data.

Examples

Passport Bot

Type:

telegram.PassportData

poll

Optional. Message is a native poll, information about the poll.

Type:

telegram.Poll

dice

Optional. Message is a dice with random value.

Type:

telegram.Dice

via_bot

Optional. Bot through which message was sent.

Type:

telegram.User

proximity_alert_triggered

Optional. Service message. A user in the chat triggered another user’s proximity alert while sharing Live Location.

Type:

telegram.ProximityAlertTriggered

video_chat_scheduled

Optional. Service message: video chat scheduled.

Added in version 20.0.

Type:

telegram.VideoChatScheduled

video_chat_started

Optional. Service message: video chat started.

Added in version 20.0.

Type:

telegram.VideoChatStarted

video_chat_ended

Optional. Service message: video chat ended.

Added in version 20.0.

Type:

telegram.VideoChatEnded

video_chat_participants_invited

Optional. Service message: new participants invited to a video chat.

Added in version 20.0.

Type:

telegram.VideoChatParticipantsInvited

web_app_data

Optional. Service message: data sent by a Web App.

Added in version 20.0.

Type:

telegram.WebAppData

reply_markup

Optional. Inline keyboard attached to the message. ~telegram.InlineKeyboardButton.login_url buttons are represented as ordinary url buttons.

Type:

telegram.InlineKeyboardMarkup

is_topic_message

Optional. True, if the message is sent to a forum topic.

Added in version 20.0.

Type:

bool

message_thread_id

Optional. Unique identifier of a message thread to which the message belongs; for supergroups only.

Added in version 20.0.

Type:

int

forum_topic_created

Optional. Service message: forum topic created.

Added in version 20.0.

Type:

telegram.ForumTopicCreated

forum_topic_closed

Optional. Service message: forum topic closed.

Added in version 20.0.

Type:

telegram.ForumTopicClosed

forum_topic_reopened

Optional. Service message: forum topic reopened.

Added in version 20.0.

Type:

telegram.ForumTopicReopened

forum_topic_edited

Optional. Service message: forum topic edited.

Added in version 20.0.

Type:

telegram.ForumTopicEdited

general_forum_topic_hidden

Optional. Service message: General forum topic hidden.

Added in version 20.0.

Type:

telegram.GeneralForumTopicHidden

general_forum_topic_unhidden

Optional. Service message: General forum topic unhidden.

Added in version 20.0.

Type:

telegram.GeneralForumTopicUnhidden

write_access_allowed

Optional. Service message: the user allowed the bot added to the attachment menu to write messages.

Added in version 20.0.

Type:

telegram.WriteAccessAllowed

has_media_spoiler

Optional. True, if the message media is covered by a spoiler animation.

Added in version 20.0.

Type:

bool

checklist

Optional. Message is a checklist

Added in version 22.3.

Type:

telegram.Checklist

users_shared

Optional. Service message: users were shared with the bot

Added in version 20.8.

Type:

telegram.UsersShared

chat_shared

Optional. Service message: a chat was shared with the bot.

Added in version 20.1.

Type:

telegram.ChatShared

gift

Optional. Service message: a regular gift was sent or received.

Added in version 22.1.

Type:

telegram.GiftInfo

unique_gift

Optional. Service message: a unique gift was sent or received

Added in version 22.1.

Type:

telegram.UniqueGiftInfo

giveaway_created

Optional. Service message: a scheduled giveaway was created

Added in version 20.8.

Type:

telegram.GiveawayCreated

giveaway

Optional. The message is a scheduled giveaway message

Added in version 20.8.

Type:

telegram.Giveaway

giveaway_winners

Optional. A giveaway with public winners was completed

Added in version 20.8.

Type:

telegram.GiveawayWinners

giveaway_completed

Optional. Service message: a giveaway without public winners was completed

Added in version 20.8.

Type:

telegram.GiveawayCompleted

paid_message_price_changed

Optional. Service message: the price for paid messages has changed in the chat

Added in version 22.1.

Type:

telegram.PaidMessagePriceChanged

suggested_post_approved

Optional. Service message: a suggested post was approved.

Added in version 22.4.

Type:

telegram.SuggestedPostApproved

suggested_post_approval_failed

Optional. Service message: approval of a suggested post has failed.

Added in version 22.4.

Type:

telegram.SuggestedPostApproved

suggested_post_declined

Optional. Service message: a suggested post was declined.

Added in version 22.4.

Type:

telegram.SuggestedPostDeclined

suggested_post_paid

Optional. Service message: payment for a suggested post was received.

Added in version 22.4.

Type:

telegram.SuggestedPostPaid

suggested_post_refunded

Optional. Service message: payment for a suggested post was refunded.

Added in version 22.4.

Type:

telegram.SuggestedPostRefunded

external_reply

Optional. Information about the message that is being replied to, which may come from another chat or forum topic.

Added in version 20.8.

Type:

telegram.ExternalReplyInfo

quote

Optional. For replies that quote part of the original message, the quoted part of the message.

Added in version 20.8.

Type:

telegram.TextQuote

forward_origin

Optional. Information about the original message for forwarded messages

Added in version 20.8.

Type:

telegram.MessageOrigin

reply_to_story

Optional. For replies to a story, the original story.

Added in version 21.0.

Type:

telegram.Story

boost_added

Optional. Service message: user boosted the chat.

Added in version 21.0.

Type:

telegram.ChatBoostAdded

sender_boost_count

Optional. If the sender of the message boosted the chat, the number of boosts added by the user.

Added in version 21.0.

Type:

int

business_connection_id

Optional. Unique identifier of the business connection from which the message was received. If non-empty, the message belongs to a chat of the corresponding business account that is independent from any potential bot chat which might share the same identifier.

Added in version 21.1.

Type:

str

sender_business_bot

Optional. The bot that actually sent the message on behalf of the business account. Available only for outgoing messages sent on behalf of the connected business account.

Added in version 21.1.

Type:

telegram.User

chat_background_set

Optional. Service message: chat background set

Added in version 21.2.

Type:

telegram.ChatBackground

checklist_tasks_done

Optional. Service message: some tasks in a checklist were marked as done or not done

Added in version 22.3.

Type:

telegram.ChecklistTasksDone

checklist_tasks_added

Optional. Service message: tasks were added to a checklist

Added in version 22.3.

Type:

telegram.ChecklistTasksAdded

paid_media

Optional. Message contains paid media; information about the paid media.

Added in version 21.4.

Type:

telegram.PaidMediaInfo

refunded_payment

Optional. Message is a service message about a refunded payment, information about the payment.

Added in version 21.4.

Type:

telegram.RefundedPayment

direct_message_price_changed

Optional. Service message: the price for paid messages in the corresponding direct messages chat of a channel has changed.

Added in version 22.3.

Type:

telegram.DirectMessagePriceChanged

is_paid_post

Optional. True, if the message is a paid post. Note that such posts must not be deleted for 24 hours to receive the payment and can’t be edited.

Added in version 22.4.

Type:

bool

direct_messages_topic

Optional. Information about the direct messages chat topic that contains the message.

Added in version 22.4.

Type:

telegram.DirectMessagesTopic

reply_to_checklist_task_id

Optional. Identifier of the specific checklist task that is being replied to.

Added in version 22.4.

Type:

int

animation: Animation | None
async approve_suggested_post(send_date=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.approve_suggested_post(
    chat_id=message.chat_id,
    message_id=message.message_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.approve_suggested_post().

Added in version 22.4.

Returns:

boolbool On success, True is returned.

audio: Audio | None
author_signature: str | None
boost_added: ChatBoostAdded | None
build_reply_arguments(quote=None, quote_index=None, target_chat_id=None, allow_sending_without_reply=None, message_thread_id=None)[source]

Builds a dictionary with the keys chat_id and reply_parameters. This dictionary can be used to reply to a message with the given quote and target chat.

Examples

Usage with telegram.Bot.send_message():

await bot.send_message(
    text="This is a reply",
    **message.build_reply_arguments(quote="Quoted Text")
)

Usage with reply_text(), replying in the same chat:

await message.reply_text(
    "This is a reply",
    do_quote=message.build_reply_arguments(quote="Quoted Text")
)

Usage with reply_text(), replying in a different chat:

await message.reply_text(
    "This is a reply",
    do_quote=message.build_reply_arguments(
        quote="Quoted Text",
        target_chat_id=-100123456789
    )
)

Added in version 20.8.

Parameters:
Returns:

_ReplyKwargs

business_connection_id: str | None
caption: str | None
caption_entities: tuple[MessageEntity, ...]
property caption_html: str

Creates an HTML-formatted string from the markup entities found in the message’s caption.

Use this if you want to retrieve the message caption with the caption entities formatted as HTML in the same way the original message was formatted.

Warning

|text_html|

Changed in version 13.10: Spoiler entities are now formatted as HTML.

Changed in version 20.3: Custom emoji entities are now supported.

Changed in version 20.8: Blockquote entities are now supported.

Returns:

Message caption with caption entities formatted as HTML.

Return type:

str

property caption_html_urled: str

Creates an HTML-formatted string from the markup entities found in the message’s caption.

Use this if you want to retrieve the message caption with the caption entities formatted as HTML. This also formats telegram.MessageEntity.URL as a hyperlink.

Warning

|text_html|

Changed in version 13.10: Spoiler entities are now formatted as HTML.

Changed in version 20.3: Custom emoji entities are now supported.

Changed in version 20.8: Blockquote entities are now supported.

Returns:

Message caption with caption entities formatted as HTML.

Return type:

str

property caption_markdown: str

Creates an Markdown-formatted string from the markup entities found in the message’s caption using telegram.constants.ParseMode.MARKDOWN.

Use this if you want to retrieve the message caption with the caption entities formatted as Markdown in the same way the original message was formatted.

Warning

|text_markdown|

Note

telegram.constants.ParseMode.MARKDOWN is a legacy mode, retained by Telegram for backward compatibility. You should use caption_markdown_v2()

Changed in version 20.5: Since custom emoji entities are not supported by MARKDOWN, this method now raises a ValueError when encountering a custom emoji.

Changed in version 20.8: Since block quotation entities are not supported by MARKDOWN, this method now raises a ValueError when encountering a block quotation.

Returns:

Message caption with caption entities formatted as Markdown.

Return type:

str

Raises:

ValueError – If the message contains underline, strikethrough, spoiler, blockquote or nested entities.

property caption_markdown_urled: str

Creates an Markdown-formatted string from the markup entities found in the message’s caption using telegram.constants.ParseMode.MARKDOWN.

Use this if you want to retrieve the message caption with the caption entities formatted as Markdown. This also formats telegram.MessageEntity.URL as a hyperlink.

Warning

|text_markdown|

Note

telegram.constants.ParseMode.MARKDOWN is a legacy mode, retained by Telegram for backward compatibility. You should use caption_markdown_v2_urled() instead.

Changed in version 20.5: Since custom emoji entities are not supported by MARKDOWN, this method now raises a ValueError when encountering a custom emoji.

Changed in version 20.8: Since block quotation entities are not supported by MARKDOWN, this method now raises a ValueError when encountering a block quotation.

Returns:

Message caption with caption entities formatted as Markdown.

Return type:

str

Raises:

ValueError – If the message contains underline, strikethrough, spoiler, blockquote or nested entities.

property caption_markdown_v2: str

Creates an Markdown-formatted string from the markup entities found in the message’s caption using telegram.constants.ParseMode.MARKDOWN_V2.

Use this if you want to retrieve the message caption with the caption entities formatted as Markdown in the same way the original message was formatted.

Warning

|text_markdown|

Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.

Changed in version 20.3: Custom emoji entities are now supported.

Changed in version 20.8: Blockquote entities are now supported.

Returns:

Message caption with caption entities formatted as Markdown.

Return type:

str

property caption_markdown_v2_urled: str

Creates an Markdown-formatted string from the markup entities found in the message’s caption using telegram.constants.ParseMode.MARKDOWN_V2.

Use this if you want to retrieve the message caption with the caption entities formatted as Markdown. This also formats telegram.MessageEntity.URL as a hyperlink.

Warning

|text_markdown|

Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.

Changed in version 20.3: Custom emoji entities are now supported.

Changed in version 20.8: Blockquote entities are now supported.

Returns:

Message caption with caption entities formatted as Markdown.

Return type:

str

channel_chat_created: bool | None
chat_background_set: ChatBackground | None
property chat_id: int

Shortcut for telegram.Chat.id for chat.

Type:

int

chat_shared: ChatShared | None
checklist: Checklist | None
checklist_tasks_added: ChecklistTasksAdded | None
checklist_tasks_done: ChecklistTasksDone | None
async close_forum_topic(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.close_forum_topic(
   chat_id=message.chat_id, message_thread_id=message.message_thread_id, *args,
   **kwargs
)

For the documentation of the arguments, please see telegram.Bot.close_forum_topic().

Added in version 20.0.

Returns:

On success, True is returned.

Returns:

bool

compute_quote_position_and_entities(quote, index=None)[source]

Use this function to compute position and entities of a quote in the message text or caption. Useful for filling the parameters ~telegram.ReplyParameters.quote_position and ~telegram.ReplyParameters.quote_entities of telegram.ReplyParameters when replying to a message.

Example

Given a message with the text "Hello, world! Hello, world!", the following code will return the position and entities of the second occurrence of "Hello, world!".

message.compute_quote_position_and_entities("Hello, world!", 1)

Added in version 20.8.

Parameters:
  • quote (str) – Part of the message which is to be quoted. This is expected to have plain text without formatting entities.

  • index (int | None, default: None) – 0-based index of the occurrence of the quote in the message. If not specified, the first occurrence is used.

Returns:

On success, a tuple containing information about quote position and entities is returned.

Returns:

tuple[int, tuple[MessageEntity, ...] | None]

Raises:
connected_website: str | None
contact: Contact | None
async copy(chat_id, caption=None, parse_mode=None, caption_entities=None, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, reply_parameters=None, show_caption_above_media=None, allow_paid_broadcast=None, video_start_timestamp=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.copy_message(
    chat_id=chat_id,
    from_chat_id=update.effective_message.chat_id,
    message_id=update.effective_message.message_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs
)

For the documentation of the arguments, please see telegram.Bot.copy_message().

Returns:

On success, returns the MessageId of the sent message.

Returns:

MessageId

classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Message

async decline_suggested_post(comment=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.decline_suggested_post(
    chat_id=message.chat_id,
    message_id=message.message_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.decline_suggested_post().

Added in version 22.4.

Returns:

boolbool On success, True is returned.

async delete(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for either:

await bot.delete_message(
    chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)

or:

await bot.delete_business_messages(
    business_connection_id=self.business_connection_id,
    message_ids=[self.message_id],
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.delete_message() and telegram.Bot.delete_business_messages().

Returns:

On success, True is returned.

Returns:

bool

delete_chat_photo: bool | None
async delete_forum_topic(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.delete_forum_topic(
   chat_id=message.chat_id, message_thread_id=message.message_thread_id, *args,
   **kwargs
)

For the documentation of the arguments, please see telegram.Bot.delete_forum_topic().

Added in version 20.0.

Returns:

On success, True is returned.

Returns:

bool

dice: Dice | None
direct_message_price_changed: DirectMessagePriceChanged | None
direct_messages_topic: DirectMessagesTopic | None
document: Document | None
async edit_caption(caption=None, reply_markup=None, parse_mode=None, caption_entities=None, show_caption_above_media=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.edit_message_caption(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.edit_message_caption().

Note

You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Changed in version 21.4: Now also passes business_connection_id.

Returns:

On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.

Returns:

Message | bool

async edit_checklist(checklist, reply_markup=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.edit_message_checklist(
    business_connection_id=message.business_connection_id,
    chat_id=message.chat_id,
    message_id=message.message_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.edit_message_checklist().

Added in version 22.3.

Note

You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Returns:

On success, the edited Message is returned.

Returns:

Message

edit_date: dtm.datetime | None
async edit_forum_topic(name=None, icon_custom_emoji_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.edit_forum_topic(
   chat_id=message.chat_id, message_thread_id=message.message_thread_id, *args,
   **kwargs
)

For the documentation of the arguments, please see telegram.Bot.edit_forum_topic().

Added in version 20.0.

Returns:

On success, True is returned.

Returns:

bool

async edit_live_location(latitude=None, longitude=None, reply_markup=None, horizontal_accuracy=None, heading=None, proximity_alert_radius=None, live_period=None, *, location=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.edit_message_live_location(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.edit_message_live_location().

Note

You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Changed in version 21.4: Now also passes business_connection_id.

Returns:

On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.

Returns:

Message | bool

async edit_media(media, reply_markup=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.edit_message_media(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.edit_message_media().

Note

You can only edit messages that the bot sent itself(i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Changed in version 21.4: Now also passes business_connection_id.

Returns:

On success, if edited message is not an inline message, the edited Message is returned, otherwise True is returned.

Returns:

Message | bool

async edit_reply_markup(reply_markup=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.edit_message_reply_markup(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.edit_message_reply_markup().

Note

You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Changed in version 21.4: Now also passes business_connection_id.

Returns:

On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.

Returns:

Message | bool

async edit_text(text, parse_mode=None, reply_markup=None, entities=None, link_preview_options=None, *, disable_web_page_preview=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.edit_message_text(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.edit_message_text().

Note

You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Changed in version 21.4: Now also passes business_connection_id.

Returns:

On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.

Returns:

Message | bool

effect_id: str | None
property effective_attachment: Animation | Audio | Contact | Dice | Document | Game | Invoice | Location | PassportData | Sequence[PhotoSize] | PaidMediaInfo | Poll | Sticker | Story | SuccessfulPayment | Venue | Video | VideoNote | Voice | None

If the message is a user generated content which is not a plain text message, this property is set to this content. It may be one of

Otherwise None is returned.

See also

Working with Files and Media <Working-with-Files-and-Media>

Changed in version 20.0: dice, passport_data and poll are now also considered to be an attachment.

Changed in version 21.4: paid_media is now also considered to be an attachment.

Deprecated since version 21.4: successful_payment will be removed in future major versions.

entities: tuple[MessageEntity, ...]
external_reply: ExternalReplyInfo | None
forum_topic_closed: ForumTopicClosed | None
forum_topic_created: ForumTopicCreated | None
forum_topic_edited: ForumTopicEdited | None
forum_topic_reopened: ForumTopicReopened | None
async forward(chat_id, disable_notification=None, protect_content=None, message_thread_id=None, video_start_timestamp=None, suggested_post_parameters=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.forward_message(
    from_chat_id=update.effective_message.chat_id,
    message_id=update.effective_message.message_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs
)

For the documentation of the arguments, please see telegram.Bot.forward_message().

Note

Since the release of Bot API 5.5 it can be impossible to forward messages from some chats. Use the attributes telegram.Message.has_protected_content and telegram.ChatFullInfo.has_protected_content to check this.

As a workaround, it is still possible to use copy(). However, this behaviour is undocumented and might be changed by Telegram.

Returns:

On success, instance representing the message forwarded.

Returns:

Message

forward_origin: MessageOrigin | None
from_user: User | None
game: Game | None
general_forum_topic_hidden: GeneralForumTopicHidden | None
general_forum_topic_unhidden: GeneralForumTopicUnhidden | None
async get_game_high_scores(user_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.get_game_high_scores(
    chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.get_game_high_scores().

Note

You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Returns:

tuple[GameHighScore, ...] – tuple[telegram.GameHighScore]

gift: GiftInfo | None
giveaway: Giveaway | None
giveaway_completed: GiveawayCompleted | None
giveaway_created: GiveawayCreated | None
giveaway_winners: GiveawayWinners | None
group_chat_created: bool | None
has_media_spoiler: bool | None
has_protected_content: bool | None
property id: int

Shortcut for message_id.

Added in version 20.0.

Type:

int

invoice: Invoice | None
is_automatic_forward: bool | None
is_from_offline: bool | None
is_paid_post: bool | None
is_topic_message: bool | None
left_chat_member: User | None

Convenience property. If the chat of the message is not a private chat or normal group, returns a t.me link of the message.

Changed in version 20.3: For messages that are replies or part of a forum topic, the link now points to the corresponding thread view.

Type:

str

link_preview_options: LinkPreviewOptions | None
location: Location | None
media_group_id: str | None
message_auto_delete_timer_changed: MessageAutoDeleteTimerChanged | None
message_thread_id: int | None
migrate_from_chat_id: int | None
migrate_to_chat_id: int | None
new_chat_members: tuple[User, ...]
new_chat_photo: tuple[PhotoSize, ...]
new_chat_title: str | None
paid_media: PaidMediaInfo | None
paid_message_price_changed: PaidMessagePriceChanged | None
paid_star_count: int | None
parse_caption_entities(types=None)[source]

Returns a dict that maps telegram.MessageEntity to str. It contains entities from this message’s caption filtered by their telegram.MessageEntity.type attribute as the key, and the text that each entity belongs to as the value of the dict.

Note

This method should always be used instead of the caption_entities attribute, since it calculates the correct substring from the message text based on UTF-16 codepoints. See parse_entity for more info.

Parameters:

types (list[str] | None, default: None) – List of telegram.MessageEntity types as strings. If the type attribute of an entity is contained in this list, it will be returned. Defaults to a list of all types. All types can be found as constants in telegram.MessageEntity.

Returns:

A dictionary of entities mapped to the text that belongs to them, calculated based on UTF-16 codepoints.

Returns:

dict[MessageEntity, str]

parse_caption_entity(entity)[source]

Returns the text from a given telegram.MessageEntity.

Note

This method is present because Telegram calculates the offset and length in UTF-16 codepoint pairs, which some versions of Python don’t handle automatically. (That is, you can’t just slice Message.caption with the offset and length.)

Parameters:

entity (MessageEntity) – The entity to extract the text from. It must be an entity that belongs to this message.

Returns:

The text of the given entity.

Returns:

str

Raises:

RuntimeError – If the message has no caption.

parse_entities(types=None)[source]

Returns a dict that maps telegram.MessageEntity to str. It contains entities from this message filtered by their telegram.MessageEntity.type attribute as the key, and the text that each entity belongs to as the value of the dict.

Note

This method should always be used instead of the entities attribute, since it calculates the correct substring from the message text based on UTF-16 codepoints. See parse_entity for more info.

Parameters:

types (list[str] | None, default: None) – List of telegram.MessageEntity types as strings. If the type attribute of an entity is contained in this list, it will be returned. Defaults to a list of all types. All types can be found as constants in telegram.MessageEntity.

Returns:

A dictionary of entities mapped to the text that belongs to them, calculated based on UTF-16 codepoints.

Returns:

dict[MessageEntity, str]

parse_entity(entity)[source]

Returns the text from a given telegram.MessageEntity.

Note

This method is present because Telegram calculates the offset and length in UTF-16 codepoint pairs, which some versions of Python don’t handle automatically. (That is, you can’t just slice Message.text with the offset and length.)

Parameters:

entity (MessageEntity) – The entity to extract the text from. It must be an entity that belongs to this message.

Returns:

The text of the given entity.

Returns:

str

Raises:

RuntimeError – If the message has no text.

passport_data: PassportData | None
photo: tuple[PhotoSize, ...]
async pin(disable_notification=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.pin_chat_message(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.pin_chat_message().

Changed in version 21.5: Now also passes business_connection_id to telegram.Bot.pin_chat_message().

Returns:

On success, True is returned.

Returns:

bool

pinned_message: MaybeInaccessibleMessage | None
poll: Poll | None
proximity_alert_triggered: ProximityAlertTriggered | None
quote: TextQuote | None
async read_business_message(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

 await bot.read_business_message(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.read_business_message().

Added in version 22.1.

Returns:

boolbool On success, True is returned.

refunded_payment: RefundedPayment | None
async reopen_forum_topic(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.reopen_forum_topic(
    chat_id=message.chat_id, message_thread_id=message.message_thread_id, *args,
    **kwargs
 )

For the documentation of the arguments, please see telegram.Bot.reopen_forum_topic().

Added in version 20.0.

Returns:

On success, True is returned.

Returns:

bool

async reply_animation(animation, duration=None, width=None, height=None, caption=None, parse_mode=None, disable_notification=None, reply_markup=None, caption_entities=None, protect_content=None, message_thread_id=None, has_spoiler=None, thumbnail=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, show_caption_above_media=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, filename=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_animation(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_animation().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_audio(audio, duration=None, performer=None, title=None, caption=None, disable_notification=None, reply_markup=None, parse_mode=None, caption_entities=None, protect_content=None, message_thread_id=None, thumbnail=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, filename=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_audio(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_audio().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_chat_action(action, message_thread_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_chat_action(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_chat_action().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Added in version 13.2.

Returns:

On success, True is returned.

Returns:

bool

async reply_checklist(checklist, disable_notification=None, protect_content=None, message_effect_id=None, reply_parameters=None, reply_markup=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_checklist(
    business_connection_id=self.business_connection_id,
    chat_id=update.effective_message.chat_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_checklist().

Added in version 22.3.

Keyword Arguments:

do_quote (bool | dict, optional) – |do_quote|

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_contact(phone_number=None, first_name=None, last_name=None, disable_notification=None, reply_markup=None, vcard=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, contact=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_contact(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_contact().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_copy(from_chat_id, message_id, caption=None, parse_mode=None, caption_entities=None, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, reply_parameters=None, show_caption_above_media=None, allow_paid_broadcast=None, video_start_timestamp=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.copy_message(
    chat_id=message.chat.id,
    message_thread_id=update.effective_message.message_thread_id,
    message_id=message_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs
)

For the documentation of the arguments, please see telegram.Bot.copy_message().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, returns the MessageId of the sent message.

Returns:

MessageId

async reply_dice(disable_notification=None, reply_markup=None, emoji=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_dice(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_dice().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_document(document, caption=None, disable_notification=None, reply_markup=None, parse_mode=None, disable_content_type_detection=None, caption_entities=None, protect_content=None, message_thread_id=None, thumbnail=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, filename=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_document(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_document().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_game(game_short_name, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_game(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_game().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Added in version 13.2.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_html(text, disable_notification=None, reply_markup=None, entities=None, protect_content=None, message_thread_id=None, link_preview_options=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, disable_web_page_preview=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_message(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    parse_mode=ParseMode.HTML,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    business_connection_id=self.business_connection_id,
    *args,
    **kwargs,
)

Sends a message with HTML formatting.

For the documentation of the arguments, please see telegram.Bot.send_message().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_invoice(title, description, payload, currency, prices, provider_token=None, start_parameter=None, photo_url=None, photo_size=None, photo_width=None, photo_height=None, need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, is_flexible=None, disable_notification=None, reply_markup=None, provider_data=None, send_phone_number_to_provider=None, send_email_to_provider=None, max_tip_amount=None, suggested_tip_amounts=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_invoice(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_invoice().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Warning

As of API 5.2 start_parameter <telegram.Bot.send_invoice.start_parameter> is an optional argument and therefore the order of the arguments had to be changed. Use keyword arguments to make sure that the arguments are passed correctly.

Added in version 13.2.

Changed in version 13.5: As of Bot API 5.2, the parameter start_parameter <telegram.Bot.send_invoice.start_parameter> is optional.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_location(latitude=None, longitude=None, disable_notification=None, reply_markup=None, live_period=None, horizontal_accuracy=None, heading=None, proximity_alert_radius=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, location=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_location(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_location().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_markdown(text, disable_notification=None, reply_markup=None, entities=None, protect_content=None, message_thread_id=None, link_preview_options=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, disable_web_page_preview=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_message(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    parse_mode=ParseMode.MARKDOWN,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

Sends a message with Markdown version 1 formatting.

For the documentation of the arguments, please see telegram.Bot.send_message().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Note

telegram.constants.ParseMode.MARKDOWN is a legacy mode, retained by Telegram for backward compatibility. You should use reply_markdown_v2() instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_markdown_v2(text, disable_notification=None, reply_markup=None, entities=None, protect_content=None, message_thread_id=None, link_preview_options=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, disable_web_page_preview=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_message(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    parse_mode=ParseMode.MARKDOWN_V2,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    business_connection_id=self.business_connection_id,
    *args,
    **kwargs,
)

Sends a message with markdown version 2 formatting.

For the documentation of the arguments, please see telegram.Bot.send_message().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

reply_markup: InlineKeyboardMarkup | None
async reply_media_group(media, disable_notification=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None, caption=None, parse_mode=None, caption_entities=None)[source]

Shortcut for:

await bot.send_media_group(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_media_group().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

An array of the sent Messages.

Returns:

tuple[Message, ...]

Raises:

telegram.error.TelegramError

async reply_paid_media(star_count, media, caption=None, parse_mode=None, caption_entities=None, show_caption_above_media=None, disable_notification=None, protect_content=None, reply_parameters=None, reply_markup=None, payload=None, allow_paid_broadcast=None, suggested_post_parameters=None, message_thread_id=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_paid_media(
    chat_id=message.chat.id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=message.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs
)

For the documentation of the arguments, please see telegram.Bot.send_paid_media().

Added in version 21.7.

Keyword Arguments:

do_quote (bool | dict, optional) – |do_quote|

Returns:

On success, the sent message is returned.

Returns:

Message

async reply_photo(photo, caption=None, disable_notification=None, reply_markup=None, parse_mode=None, caption_entities=None, protect_content=None, message_thread_id=None, has_spoiler=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, show_caption_above_media=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, filename=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_photo(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_photo().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_poll(question, options, is_anonymous=None, type=None, allows_multiple_answers=None, correct_option_id=None, is_closed=None, disable_notification=None, reply_markup=None, explanation=None, explanation_parse_mode=None, open_period=None, close_date=None, explanation_entities=None, protect_content=None, message_thread_id=None, reply_parameters=None, question_parse_mode=None, question_entities=None, message_effect_id=None, allow_paid_broadcast=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_poll(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_poll().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_sticker(sticker, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, emoji=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_sticker(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_sticker().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_text(text, parse_mode=None, disable_notification=None, reply_markup=None, entities=None, protect_content=None, message_thread_id=None, link_preview_options=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, disable_web_page_preview=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_message(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_message().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

reply_to_checklist_task_id: int | None
reply_to_message: Message | None
reply_to_story: Story | None
async reply_venue(latitude=None, longitude=None, title=None, address=None, foursquare_id=None, disable_notification=None, reply_markup=None, foursquare_type=None, google_place_id=None, google_place_type=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, venue=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_venue(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_venue().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_video(video, duration=None, caption=None, disable_notification=None, reply_markup=None, width=None, height=None, parse_mode=None, supports_streaming=None, caption_entities=None, protect_content=None, message_thread_id=None, has_spoiler=None, thumbnail=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, show_caption_above_media=None, cover=None, start_timestamp=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, filename=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_video(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_video().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_video_note(video_note, duration=None, length=None, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, thumbnail=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, filename=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_video_note(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_video_note().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

async reply_voice(voice, duration=None, caption=None, disable_notification=None, reply_markup=None, parse_mode=None, caption_entities=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, suggested_post_parameters=None, *, reply_to_message_id=None, allow_sending_without_reply=None, filename=None, do_quote=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.send_voice(
    update.effective_message.chat_id,
    message_thread_id=update.effective_message.message_thread_id,
    business_connection_id=self.business_connection_id,
    direct_messages_topic_id=self.direct_messages_topic.topic_id,
    *args,
    **kwargs,
)

For the documentation of the arguments, please see telegram.Bot.send_voice().

Changed in version 21.1: If message_thread_id is not provided, this will reply to the same thread (topic) of the original message.

Changed in version 22.0: Removed deprecated parameter quote. Use do_quote instead.

Keyword Arguments:

do_quote (bool | dict, optional) –

|do_quote|

Added in version 20.8.

Returns:

On success, instance representing the message posted.

Returns:

Message

sender_boost_count: int | None
sender_business_bot: User | None
sender_chat: Chat | None
async set_game_score(user_id, score, force=None, disable_edit_message=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.set_game_score(
    chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.set_game_score().

Note

You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Returns:

On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.

Returns:

Message | bool

async set_reaction(reaction=None, is_big=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.set_message_reaction(chat_id=message.chat_id, message_id=message.message_id,
   *args, **kwargs)

For the documentation of the arguments, please see telegram.Bot.set_message_reaction().

Added in version 20.8.

Returns:

boolbool On success, True is returned.

show_caption_above_media: bool | None
sticker: Sticker | None
async stop_live_location(reply_markup=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.stop_message_live_location(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.stop_message_live_location().

Note

You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.

Changed in version 21.4: Now also passes business_connection_id.

Returns:

On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.

Returns:

Message | bool

async stop_poll(reply_markup=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.stop_poll(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.stop_poll().

Changed in version 21.4: Now also passes business_connection_id.

Returns:

On success, the stopped Poll with the final results is returned.

Returns:

Poll

story: Story | None
successful_payment: SuccessfulPayment | None
suggested_post_approval_failed: SuggestedPostApprovalFailed | None
suggested_post_approved: SuggestedPostApproved | None
suggested_post_declined: SuggestedPostDeclined | None
suggested_post_info: SuggestedPostInfo | None
suggested_post_paid: SuggestedPostPaid | None
suggested_post_refunded: SuggestedPostRefunded | None
supergroup_chat_created: bool | None
text: str | None
property text_html: str

Creates an HTML-formatted string from the markup entities found in the message.

Use this if you want to retrieve the message text with the entities formatted as HTML in the same way the original message was formatted.

Warning

|text_html|

Changed in version 13.10: Spoiler entities are now formatted as HTML.

Changed in version 20.3: Custom emoji entities are now supported.

Changed in version 20.8: Blockquote entities are now supported.

Returns:

Message text with entities formatted as HTML.

Return type:

str

property text_html_urled: str

Creates an HTML-formatted string from the markup entities found in the message.

Use this if you want to retrieve the message text with the entities formatted as HTML. This also formats telegram.MessageEntity.URL as a hyperlink.

Warning

|text_html|

Changed in version 13.10: Spoiler entities are now formatted as HTML.

Changed in version 20.3: Custom emoji entities are now supported.

Changed in version 20.8: Blockquote entities are now supported.

Returns:

Message text with entities formatted as HTML.

Return type:

str

property text_markdown: str

Creates an Markdown-formatted string from the markup entities found in the message using telegram.constants.ParseMode.MARKDOWN.

Use this if you want to retrieve the message text with the entities formatted as Markdown in the same way the original message was formatted.

Warning

|text_markdown|

Note

telegram.constants.ParseMode.MARKDOWN is a legacy mode, retained by Telegram for backward compatibility. You should use text_markdown_v2() instead.

Changed in version 20.5: Since custom emoji entities are not supported by MARKDOWN, this method now raises a ValueError when encountering a custom emoji.

Changed in version 20.8: Since block quotation entities are not supported by MARKDOWN, this method now raises a ValueError when encountering a block quotation.

Returns:

Message text with entities formatted as Markdown.

Return type:

str

Raises:

ValueError – If the message contains underline, strikethrough, spoiler, blockquote or nested entities.

property text_markdown_urled: str

Creates an Markdown-formatted string from the markup entities found in the message using telegram.constants.ParseMode.MARKDOWN.

Use this if you want to retrieve the message text with the entities formatted as Markdown. This also formats telegram.MessageEntity.URL as a hyperlink.

Warning

|text_markdown|

Note

telegram.constants.ParseMode.MARKDOWN is a legacy mode, retained by Telegram for backward compatibility. You should use text_markdown_v2_urled() instead.

Changed in version 20.5: Since custom emoji entities are not supported by MARKDOWN, this method now raises a ValueError when encountering a custom emoji.

Changed in version 20.8: Since block quotation entities are not supported by MARKDOWN, this method now raises a ValueError when encountering a block quotation.

Returns:

Message text with entities formatted as Markdown.

Return type:

str

Raises:

ValueError – If the message contains underline, strikethrough, spoiler, blockquote or nested entities.

property text_markdown_v2: str

Creates an Markdown-formatted string from the markup entities found in the message using telegram.constants.ParseMode.MARKDOWN_V2.

Use this if you want to retrieve the message text with the entities formatted as Markdown in the same way the original message was formatted.

Warning

|text_markdown|

Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.

Changed in version 20.3: Custom emoji entities are now supported.

Changed in version 20.8: Blockquote entities are now supported.

Returns:

Message text with entities formatted as Markdown.

Return type:

str

property text_markdown_v2_urled: str

Creates an Markdown-formatted string from the markup entities found in the message using telegram.constants.ParseMode.MARKDOWN_V2.

Use this if you want to retrieve the message text with the entities formatted as Markdown. This also formats telegram.MessageEntity.URL as a hyperlink.

Warning

|text_markdown|

Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.

Changed in version 20.3: Custom emoji entities are now supported.

Changed in version 20.8: Blockquote entities are now supported.

Returns:

Message text with entities formatted as Markdown.

Return type:

str

unique_gift: UniqueGiftInfo | None
async unpin(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.unpin_chat_message(
    chat_id=message.chat_id,
    message_id=message.message_id,
    business_connection_id=message.business_connection_id,
    *args, **kwargs
)

For the documentation of the arguments, please see telegram.Bot.unpin_chat_message().

Changed in version 21.5: Now also passes business_connection_id to telegram.Bot.pin_chat_message().

Returns:

On success, True is returned.

Returns:

bool

async unpin_all_forum_topic_messages(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Shortcut for:

await bot.unpin_all_forum_topic_messages(
   chat_id=message.chat_id, message_thread_id=message.message_thread_id, *args,
   **kwargs
)

For the documentation of the arguments, please see telegram.Bot.unpin_all_forum_topic_messages().

Added in version 20.0.

Returns:

On success, True is returned.

Returns:

bool

users_shared: UsersShared | None
venue: Venue | None
via_bot: User | None
video: Video | None
video_chat_ended: VideoChatEnded | None
video_chat_participants_invited: VideoChatParticipantsInvited | None
video_chat_scheduled: VideoChatScheduled | None
video_chat_started: VideoChatStarted | None
video_note: VideoNote | None
voice: Voice | None
web_app_data: WebAppData | None
write_access_allowed: WriteAccessAllowed | None
class spotted.data.report.Report(user_id, admin_group_id, g_message_id, channel_id=None, c_message_id=None, target_username=None, date=None)[source]

Bases: object

Class that represents a report

Parameters:
  • user_id (int) – id of the user that reported

  • admin_group_id (int) – id of the admin group

  • g_message_id (int) – id of the post in the group

  • channel_id (int | None, default: None) – id of the channel

  • c_message_id (int | None, default: None) – id of the post in question in the channel

  • target_username (str | None, default: None) – username of the reported user

  • date (datetime | None, default: None) – when the report happened

admin_group_id: int
c_message_id: int | None = None
channel_id: int | None = None
classmethod create_post_report(user_id, channel_id, c_message_id, admin_message)[source]

Adds the report of the user on a specific post

Parameters:
  • user_id (int) – id of the user that reported

  • channel_id (int) – id of the channel

  • c_message_id (int) – id of the post in question in the channel

  • admin_message (Message) – message received in the admin group that references the report

Returns:

Report | None – instance of the class or None if the report was not created

classmethod create_user_report(user_id, target_username, admin_message)[source]

Adds the report of the user targeting another user

Parameters:
  • user_id (int) – id of the user that reported

  • target_username (str) – username of reported user

  • admin_message (Message) – message received in the admin group that references the report

Returns:

Report – instance of the class

date: datetime | None = None
classmethod from_group(admin_group_id, g_message_id)[source]

Gets a report of any type related to the specified message in the admin group

Parameters:
  • admin_group_id (int) – id of the admin group

  • g_message_id (int) – id of the report in the group

Returns:

Report | None – instance of the class or None if the report was not present

g_message_id: int
classmethod get_last_user_report(user_id)[source]

Gets the last user report of a specific user

Parameters:

user_id (int) – id of the user that reported

Returns:

Report | None – instance of the class or None if the report was not present

classmethod get_post_report(user_id, channel_id, c_message_id)[source]

Gets the report of a specific user on a published post

Parameters:
  • user_id (int) – id of the user that reported

  • channel_id (int) – id of the channel

  • c_message_id (int) – id of the post in question in the channel

Returns:

Report | None – instance of the class or None if the report was not present

property minutes_passed: float

Amount of minutes elapsed from when the report was submitted, if applicable

Type:

float

save_report()[source]

Saves the report in the database

Return type:

Report

target_username: str | None = None
user_id: int
spotted.data.report.dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

class spotted.data.report.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])

Bases: date

The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints.

astimezone()

tz -> convert to local time in new timezone tz

classmethod combine()

date, time -> datetime with same date and time fields

ctime()

Return ctime() style string.

date()

Return date object with same year, month and day.

dst()

Return self.tzinfo.dst(self).

fold
classmethod fromisoformat(object, /)

string -> datetime from a string in most ISO 8601 formats

classmethod fromtimestamp()

timestamp[, tz] -> tz’s local time from POSIX timestamp.

hour
isoformat()

[sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM]. sep is used to separate the year from the time, and defaults to ‘T’. The optional argument timespec specifies the number of additional terms of the time to include. Valid options are ‘auto’, ‘hours’, ‘minutes’, ‘seconds’, ‘milliseconds’ and ‘microseconds’.

max = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
microsecond
min = datetime.datetime(1, 1, 1, 0, 0)
minute
classmethod now(tz=None)

Returns new datetime object representing current time local to tz.

tz

Timezone object.

If no tz is specified, uses local timezone.

replace()

Return datetime with new specified fields.

resolution = datetime.timedelta(microseconds=1)
second
classmethod strptime()

string, format -> new datetime parsed from a string (like time.strptime()).

time()

Return time object with same time but with tzinfo=None.

timestamp()

Return POSIX timestamp as float.

timetuple()

Return time tuple, compatible with time.localtime().

timetz()

Return time object with same time and tzinfo.

tzinfo
tzname()

Return self.tzinfo.tzname(self).

classmethod utcfromtimestamp()

Construct a naive UTC datetime from a POSIX timestamp.

classmethod utcnow()

Return a new datetime representing UTC day and time.

utcoffset()

Return self.tzinfo.utcoffset(self).

utctimetuple()

Return UTC time tuple, compatible with time.localtime().

spotted.data.user module

Users management

class spotted.data.user.Bot(token, base_url='https://api.telegram.org/bot', base_file_url='https://api.telegram.org/file/bot', request=None, get_updates_request=None, private_key=None, private_key_password=None, local_mode=False)[source]

Bases: TelegramObject, AbstractAsyncContextManager[Bot]

This object represents a Telegram Bot.

Instances of this class can be used as asyncio context managers, where

async with bot:
    # code

is roughly equivalent to

try:
    await bot.initialize()
    # code
finally:
    await bot.shutdown()

See also

__aenter__() and __aexit__().

Note

  • Most bot methods have the argument api_kwargs which allows passing arbitrary keywords to the Telegram API. This can be used to access new features of the API before they are incorporated into PTB. The limitations to this argument are the same as the ones described in do_api_request().

  • Bots should not be serialized since if you for e.g. change the bots token, then your serialized instance will not reflect that change. Trying to pickle a bot instance will raise pickle.PicklingError. Trying to deepcopy a bot instance will raise TypeError.

Examples

Raw API Bot

See also

Your First Bot <Extensions---Your-first-Bot>, Builder Pattern <Builder-Pattern>

Added in version 13.2: Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their bot is equal.

Changed in version 20.0:

  • Removed the deprecated methods kick_chat_member, kickChatMember, get_chat_members_count and getChatMembersCount.

  • Removed the deprecated property commands.

  • Removed the deprecated defaults parameter. If you want to use telegram.ext.Defaults, please use the subclass telegram.ext.ExtBot instead.

  • Attempting to pickle a bot instance will now raise pickle.PicklingError.

  • Attempting to deepcopy a bot instance will now raise TypeError.

  • The following are now keyword-only arguments in Bot methods: location, filename, venue, contact, {read, write, connect, pool}_timeout, api_kwargs. Use a named argument for those, and notice that some positional arguments changed position as a result.

  • For uploading files, file paths are now always accepted. If local_mode is False, the file contents will be read in binary mode and uploaded. Otherwise, the file path will be passed in the file URI scheme.

Changed in version 20.5: Removed deprecated methods set_sticker_set_thumb and setStickerSetThumb. Use set_sticker_set_thumbnail() and setStickerSetThumbnail() instead.

Parameters:
  • token (str) – Bot’s unique authentication token.

  • base_url (str | Callable[[str], str], default: 'https://api.telegram.org/bot') –

    Telegram Bot API service URL. If the string contains {token}, it will be replaced with the bot’s token. If a callable is passed, it will be called with the bot’s token as the only argument and must return the base URL. Otherwise, the token will be appended to the string. Defaults to "https://api.telegram.org/bot".

    Tip

    Customizing the base URL can be used to run a bot against Local Bot API Server <Local-Bot-API-Server> or using Telegrams test environment.

    Example:

    "https://api.telegram.org/bot{token}/test"

    Changed in version 21.11: Supports callable input and string formatting.

  • base_file_url (str | Callable[[str], str], default: 'https://api.telegram.org/file/bot') –

    Telegram Bot API file URL. If the string contains {token}, it will be replaced with the bot’s token. If a callable is passed, it will be called with the bot’s token as the only argument and must return the base URL. Otherwise, the token will be appended to the string. Defaults to "https://api.telegram.org/bot".

    Tip

    Customizing the base URL can be used to run a bot against Local Bot API Server <Local-Bot-API-Server> or using Telegrams test environment.

    Example:

    "https://api.telegram.org/file/bot{token}/test"

    Changed in version 21.11: Supports callable input and string formatting.

  • request (BaseRequest | None, default: None) – Pre initialized telegram.request.BaseRequest instances. Will be used for all bot methods except for get_updates(). If not passed, an instance of telegram.request.HTTPXRequest will be used.

  • get_updates_request (BaseRequest | None, default: None) – Pre initialized telegram.request.BaseRequest instances. Will be used exclusively for get_updates(). If not passed, an instance of telegram.request.HTTPXRequest will be used.

  • private_key (bytes | None, default: None) – Private key for decryption of telegram passport data.

  • private_key_password (bytes | None, default: None) – Password for above private key.

  • local_mode (bool, default: False) –

    Set to True, if the base_url is the URI of a Local Bot API Server that runs with the --local flag. Currently, the only effect of this is that files are uploaded using their local path in the file URI scheme. Defaults to False.

    Added in version 20.0..

Note

For complete information on Bot methods and their usage, see the python-telegram-bot Bot API documentation.

async addStickerToSet(user_id, name, sticker, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for add_sticker_to_set()

Return type:

bool

async add_sticker_to_set(user_id, name, sticker, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to add a new sticker to a set created by the bot. The format of the added sticker must match the format of the other stickers in the set. Emoji sticker sets can have up to telegram.constants.StickerSetLimit.MAX_EMOJI_STICKERS stickers. Other sticker sets can have up to telegram.constants.StickerSetLimit.MAX_STATIC_STICKERS stickers.

Changed in version 20.2: Since Bot API 6.6, the parameter sticker replace the parameters png_sticker, tgs_sticker, webm_sticker, emojis, and mask_position.

Changed in version 20.5: Removed deprecated parameters png_sticker, tgs_sticker, webm_sticker, emojis, and mask_position.

Parameters:
  • user_id (int) – User identifier of created sticker set owner.

  • name (str) – Sticker set name.

  • sticker (InputSticker) –

    An object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set isn’t changed.

    Added in version 20.2.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async answerCallbackQuery(callback_query_id, text=None, show_alert=None, url=None, cache_time=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for answer_callback_query()

Return type:

bool

async answerInlineQuery(inline_query_id, results, cache_time=None, is_personal=None, next_offset=None, button=None, *, current_offset=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for answer_inline_query()

Return type:

bool

async answerPreCheckoutQuery(pre_checkout_query_id, ok, error_message=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for answer_pre_checkout_query()

Return type:

bool

async answerShippingQuery(shipping_query_id, ok, shipping_options=None, error_message=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for answer_shipping_query()

Return type:

bool

async answerWebAppQuery(web_app_query_id, result, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for answer_web_app_query()

Return type:

SentWebAppMessage

async answer_callback_query(callback_query_id, text=None, show_alert=None, url=None, cache_time=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @BotFather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.

Parameters:
  • callback_query_id (str) – Unique identifier for the query to be answered.

  • text (str | None, default: None) – Text of the notification. If not specified, nothing will be shown to the user, 0-telegram.CallbackQuery.MAX_ANSWER_TEXT_LENGTH characters.

  • show_alert (bool | None, default: None) – If True, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to False.

  • url (str | None, default: None) –

    URL that will be opened by the user’s client. If you have created a Game and accepted the conditions via @BotFather, specify the URL that opens your game - note that this will only work if the query comes from a callback game button. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.

  • cache_time (int | timedelta | None, default: None) –

    The maximum amount of time in seconds that the result of the callback query may be cached client-side. Defaults to 0.

    Changed in version 21.11: |time-period-input|

Returns:

boolbool On success, True is returned.

Raises:

telegram.error.TelegramError

async answer_inline_query(inline_query_id, results, cache_time=None, is_personal=None, next_offset=None, button=None, *, current_offset=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send answers to an inline query. No more than telegram.InlineQuery.MAX_RESULTS results per query are allowed.

Warning

In most use cases current_offset should not be passed manually. Instead of calling this method directly, use the shortcut telegram.InlineQuery.answer() with telegram.InlineQuery.answer.auto_pagination set to True, which will take care of passing the correct value.

See also

Working with Files and Media <Working-with-Files-and-Media>

Changed in version 20.5: Removed deprecated arguments switch_pm_text and switch_pm_parameter.

Parameters:
  • inline_query_id (str) – Unique identifier for the answered query.

  • results (Sequence[InlineQueryResult] | Callable[[int], Sequence[InlineQueryResult] | None]) – A list of results for the inline query. In case current_offset is passed, results may also be a callable that accepts the current page index starting from 0. It must return either a list of telegram.InlineQueryResult instances or None if there are no more results.

  • cache_time (int | timedelta | None, default: None) –

    The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300.

    Changed in version 21.11: |time-period-input|

  • is_personal (bool | None, default: None) – Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query.

  • next_offset (str | None, default: None) – Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don’t support pagination. Offset length can’t exceed telegram.InlineQuery.MAX_OFFSET_LENGTH bytes.

  • button (InlineQueryResultsButton | None, default: None) –

    A button to be shown above the inline query results.

    Added in version 20.3.

Keyword Arguments:

current_offset (str, optional) – The telegram.InlineQuery.offset of the inline query to answer. If passed, PTB will automatically take care of the pagination for you, i.e. pass the correct next_offset and truncate the results list/get the results from the callable you passed.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async answer_pre_checkout_query(pre_checkout_query_id, ok, error_message=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an telegram.Update with the field telegram.Update.pre_checkout_query. Use this method to respond to such pre-checkout queries.

Note

The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.

Parameters:
  • pre_checkout_query_id (str) – Unique identifier for the query to be answered.

  • ok (bool) – Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.

  • error_message (str | None, default: None) – Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. “Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!”). Telegram will display this message to the user.

Returns:

On success, True is returned

Returns:

bool

Raises:

telegram.error.TelegramError

async answer_shipping_query(shipping_query_id, ok, shipping_options=None, error_message=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

If you sent an invoice requesting a shipping address and the parameter send_invoice.is_flexible was specified, the Bot API will send an telegram.Update with a telegram.Update.shipping_query field to the bot. Use this method to reply to shipping queries.

Parameters:
  • shipping_query_id (str) – Unique identifier for the query to be answered.

  • ok (bool) – Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible).

  • shipping_options (Sequence[ShippingOption] | None, default: None) –

    Required if ok is True. A sequence of available shipping options.

    Changed in version 20.0: |sequenceargs|

  • error_message (str | None, default: None) – Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. “Sorry, delivery to your desired address is unavailable”). Telegram will display this message to the user.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async answer_web_app_query(web_app_query_id, result, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated.

Added in version 20.0.

Parameters:
  • web_app_query_id (str) – Unique identifier for the query to be answered.

  • result (InlineQueryResult) – An object describing the message to be sent.

Returns:

On success, a sent telegram.SentWebAppMessage is returned.

Returns:

SentWebAppMessage

Raises:

telegram.error.TelegramError

async approveChatJoinRequest(chat_id, user_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for approve_chat_join_request()

Return type:

bool

async approveSuggestedPost(chat_id, message_id, send_date=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for approve_suggested_post()

Return type:

bool

async approve_chat_join_request(chat_id, user_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to approve a chat join request.

The bot must be an administrator in the chat for this to work and must have the telegram.ChatPermissions.can_invite_users administrator right.

Added in version 13.8.

Parameters:
Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async approve_suggested_post(chat_id, message_id, send_date=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to approve a suggested post in a direct messages chat. The bot must have the can_post_messages administrator right in the corresponding channel chat.

Added in version 22.4.

Parameters:
  • chat_id (int) – Unique identifier of the target direct messages chat.

  • message_id (int) – Identifier of a suggested post message to approve.

  • send_date (int | datetime | None, default: None) –

    Date when the post is expected to be published; omit if the date has already been specified when the suggested post was created. If specified, then the date must be not more than telegram.constants.SuggestedPost.MAX_SEND_DATE seconds (30 days) in the future.

    |tz-naive-dtms|

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async banChatMember(chat_id, user_id, until_date=None, revoke_messages=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for ban_chat_member()

Return type:

bool

async banChatSenderChat(chat_id, sender_chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for ban_chat_sender_chat()

Return type:

bool

async ban_chat_member(chat_id, user_id, until_date=None, revoke_messages=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to ban a user from a group, supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

Added in version 13.7.

Parameters:
  • chat_id (str | int) – Unique identifier for the target group or username of the target supergroup or channel (in the format @channelusername).

  • user_id (int) – Unique identifier of the target user.

  • until_date (int | datetime | None, default: None) – Date when the user will be unbanned, unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever. Applied for supergroups and channels only. |tz-naive-dtms|

  • revoke_messages (bool | None, default: None) –

    Pass True to delete all messages from the chat for the user that is being removed. If False, the user will be able to see messages in the group that were sent before the user was removed. Always True for supergroups and channels.

    Added in version 13.4.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async ban_chat_sender_chat(chat_id, sender_chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won’t be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights.

Added in version 13.9.

Parameters:
  • chat_id (str | int) – Unique identifier for the target group or username of the target supergroup or channel (in the format @channelusername).

  • sender_chat_id (int) – Unique identifier of the target sender chat.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

property base_file_url: str

Telegram Bot API file URL, built from Bot.base_file_url and Bot.token.

Added in version 20.0.

Type:

str

property base_url: str

Telegram Bot API service URL, built from Bot.base_url and Bot.token.

Added in version 20.0.

Type:

str

property bot: User

User instance for the bot as returned by get_me().

Warning

This value is the cached return value of get_me(). If the bots profile is changed during runtime, this value won’t reflect the changes until get_me() is called again.

See also

initialize()

Type:

telegram.User

property can_join_groups: bool

Bot’s telegram.User.can_join_groups attribute. Shortcut for the corresponding attribute of bot.

Type:

bool

property can_read_all_group_messages: bool

Bot’s telegram.User.can_read_all_group_messages attribute. Shortcut for the corresponding attribute of bot.

Type:

bool

async close(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to close the bot instance before moving it from one local server to another. You need to delete the webhook before calling this method to ensure that the bot isn’t launched again after server restart. The method will return error 429 in the first 10 minutes after the bot is launched.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async closeForumTopic(chat_id, message_thread_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for close_forum_topic()

Return type:

bool

async closeGeneralForumTopic(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for close_general_forum_topic()

Return type:

bool

async close_forum_topic(chat_id, message_thread_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to close an open topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have ~telegram.ChatAdministratorRights.can_manage_topics administrator rights, unless it is the creator of the topic.

Added in version 20.0.

Parameters:
Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async close_general_forum_topic(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to close an open ‘General’ topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have can_manage_topics administrator rights.

Added in version 20.0.

Parameters:

chat_id (str | int) – |chat_id_group|

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async convertGiftToStars(business_connection_id, owned_gift_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for convert_gift_to_stars()

Return type:

bool

async convert_gift_to_stars(business_connection_id, owned_gift_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Converts a given regular gift to Telegram Stars. Requires the can_convert_gifts_to_stars business bot right.

Added in version 22.1.

Parameters:
  • business_connection_id (str) – Unique identifier of the business connection

  • owned_gift_id (str) – Unique identifier of the regular gift that should be converted to Telegram Stars.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async copyMessage(chat_id, from_chat_id, message_id, caption=None, parse_mode=None, caption_entities=None, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, reply_parameters=None, show_caption_above_media=None, allow_paid_broadcast=None, video_start_timestamp=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for copy_message()

Return type:

MessageId

async copyMessages(chat_id, from_chat_id, message_ids, disable_notification=None, protect_content=None, message_thread_id=None, remove_caption=None, direct_messages_topic_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for copy_messages()

Return type:

tuple[MessageId, ...]

async copy_message(chat_id, from_chat_id, message_id, caption=None, parse_mode=None, caption_entities=None, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, reply_parameters=None, show_caption_above_media=None, allow_paid_broadcast=None, video_start_timestamp=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to copy messages of any kind. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can’t be copied. The method is analogous to the method forward_message(), but the copied message doesn’t have a link to the original message.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • from_chat_id (str | int) – Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername).

  • message_id (int) – Message identifier in the chat specified in from_chat_id.

  • video_start_timestamp (int | None, default: None) –

    New start timestamp for the copied video in the message

    Added in version 21.11.

  • caption (str | None, default: None) – New caption for media, 0-telegram.constants.MessageLimit.CAPTION_LENGTH characters after entities parsing. If not specified, the original caption is kept.

  • parse_mode (DefaultValue[DVValueType] | str | DefaultValue[None] | None, default: None) – Mode for parsing entities in the new caption. See the constants in telegram.constants.ParseMode for the available modes.

  • caption_entities (Sequence[MessageEntity] | None, default: None) –

    |caption_entities|

    Changed in version 20.0: |sequenceargs|

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) –

    |protect_content|

    Added in version 13.10.

  • message_thread_id (int | None, default: None) –

    |message_thread_id_arg|

    Added in version 20.0.

  • reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply | None, default: None) – Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • reply_parameters (ReplyParameters | None, default: None) –

    |reply_parameters|

    Added in version 20.8.

  • show_caption_above_media (bool | None, default: None) –

    Pass |show_cap_above_med|

    Added in version 21.3.

  • allow_paid_broadcast (bool | None, default: None) –

    |allow_paid_broadcast|

    Added in version 21.7.

  • suggested_post_parameters (SuggestedPostParameters | None, default: None) –

    |suggested_post_parameters|

    Added in version 22.4.

  • direct_messages_topic_id (int | None, default: None) –

    |direct_messages_topic_id|

    Added in version 22.4.

Keyword Arguments:
Returns:

On success, the telegram.MessageId of the sent

message is returned.

Returns:

MessageId

Raises:

telegram.error.TelegramError

async copy_messages(chat_id, from_chat_id, message_ids, disable_notification=None, protect_content=None, message_thread_id=None, remove_caption=None, direct_messages_topic_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to copy messages of any kind. If some of the specified messages can’t be found or copied, they are skipped. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can’t be copied. A quiz poll can be copied only if the value of the field telegram.Poll.correct_option_id is known to the bot. The method is analogous to the method forward_messages(), but the copied messages don’t have a link to the original message. Album grouping is kept for copied messages.

Added in version 20.8.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • from_chat_id (str | int) – Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername).

  • message_ids (Sequence[int]) – A list of telegram.constants.BulkRequestLimit.MIN_LIMIT - telegram.constants.BulkRequestLimit.MAX_LIMIT identifiers of messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order.

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |protect_content|

  • message_thread_id (int | None, default: None) – |message_thread_id_arg|

  • remove_caption (bool | None, default: None) – Pass True to copy the messages without their captions.

  • direct_messages_topic_id (int | None, default: None) –

    Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat.

    Added in version 22.4.

Returns:

On success, a tuple of MessageId of the sent messages is returned.

Returns:

tuple[MessageId, ...]

Raises:

telegram.error.TelegramError

Alias for create_chat_invite_link()

Return type:

ChatInviteLink

Alias for create_chat_subscription_invite_link()

Return type:

ChatInviteLink

async createForumTopic(chat_id, name, icon_color=None, icon_custom_emoji_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for create_forum_topic()

Return type:

ForumTopic

Alias for create_invoice_link()

Return type:

str

async createNewStickerSet(user_id, name, title, stickers, sticker_type=None, needs_repainting=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for create_new_sticker_set()

Return type:

bool

Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. The link can be revoked using the method revoke_chat_invite_link().

Note

When joining public groups via an invite link, Telegram clients may display the usual “Join” button, effectively ignoring the invite link. In particular, the parameter creates_join_request has no effect in this case. However, this behavior is undocument and may be subject to change. See this GitHub thread for some discussion.

Added in version 13.4.

Parameters:
  • chat_id (str | int) – |chat_id_channel|

  • expire_date (int | datetime | None, default: None) – Date when the link will expire. Integer input will be interpreted as Unix timestamp. |tz-naive-dtms|

  • member_limit (int | None, default: None) – Maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; telegram.constants.ChatInviteLinkLimit.MIN_MEMBER_LIMIT- telegram.constants.ChatInviteLinkLimit.MAX_MEMBER_LIMIT.

  • name (str | None, default: None) –

    Invite link name; 0-telegram.constants.ChatInviteLinkLimit.NAME_LENGTH characters.

    Added in version 13.8.

  • creates_join_request (bool | None, default: None) –

    True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can’t be specified.

    Added in version 13.8.

Returns:

ChatInviteLinktelegram.ChatInviteLink

Raises:

telegram.error.TelegramError

Use this method to create a subscription invite link for a channel chat. The bot must have the can_invite_users administrator right. The link can be edited using the edit_chat_subscription_invite_link() or revoked using the revoke_chat_invite_link().

Added in version 21.5.

Parameters:
  • chat_id (str | int) – |chat_id_channel|

  • subscription_period (int | timedelta) –

    The number of seconds the subscription will be active for before the next payment. Currently, it must always be telegram.constants.ChatSubscriptionLimit.SUBSCRIPTION_PERIOD (30 days).

    Changed in version 21.11: |time-period-input|

  • subscription_price (int) – The number of Telegram Stars a user must pay initially and after each subsequent subscription period to be a member of the chat; telegram.constants.ChatSubscriptionLimit.MIN_PRICE- telegram.constants.ChatSubscriptionLimit.MAX_PRICE.

  • name (str | None, default: None) – Invite link name; 0-telegram.constants.ChatInviteLinkLimit.NAME_LENGTH characters.

Returns:

ChatInviteLinktelegram.ChatInviteLink

Raises:

telegram.error.TelegramError

async create_forum_topic(chat_id, name, icon_color=None, icon_custom_emoji_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to create a topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have ~telegram.ChatAdministratorRights.can_manage_topics administrator rights.

Added in version 20.0.

Parameters:
Returns:

ForumTopictelegram.ForumTopic

Raises:

telegram.error.TelegramError

Use this method to create a link for an invoice.

Added in version 20.0.

Parameters:
  • business_connection_id (str | None, default: None) –

    |business_id_str| For payments in |tg_stars| only.

    Added in version 21.8.

  • title (str) – Product name. telegram.Invoice.MIN_TITLE_LENGTH- telegram.Invoice.MAX_TITLE_LENGTH characters.

  • description (str) – Product description. telegram.Invoice.MIN_DESCRIPTION_LENGTH- telegram.Invoice.MAX_DESCRIPTION_LENGTH characters.

  • payload (str) – Bot-defined invoice payload. telegram.Invoice.MIN_PAYLOAD_LENGTH- telegram.Invoice.MAX_PAYLOAD_LENGTH bytes. This will not be displayed to the user, use it for your internal processes.

  • provider_token (str | None, default: None) –

    Payments provider token, obtained via @BotFather. Pass an empty string for payments in |tg_stars|.

    Changed in version 21.11: Bot API 7.4 made this parameter is optional and this is now reflected in the function signature.

  • currency (str) – Three-letter ISO 4217 currency code, see more on currencies. Pass XTR for payments in |tg_stars|.

  • prices (Sequence[LabeledPrice]) –

    Price breakdown, a sequence of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in |tg_stars|.

    Changed in version 20.0: |sequenceargs|

  • subscription_period (int | timedelta | None, default: None) –

    The time the subscription will be active for before the next payment, either as number of seconds or as datetime.timedelta object. The currency must be set to “XTR” (Telegram Stars) if the parameter is used. Currently, it must always be telegram.constants.InvoiceLimit.SUBSCRIPTION_PERIOD if specified. Any number of subscriptions can be active for a given bot at the same time, including multiple concurrent subscriptions from the same user. Subscription price must not exceed telegram.constants.InvoiceLimit.SUBSCRIPTION_MAX_PRICE Telegram Stars.

    Added in version 21.8.

  • max_tip_amount (int | None, default: None) – The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in |tg_stars|.

  • suggested_tip_amounts (Sequence[int] | None, default: None) –

    An array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most telegram.Invoice.MAX_TIP_AMOUNTS suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount.

    Changed in version 20.0: |sequenceargs|

  • provider_data (str | object | None, default: None) – Data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. When an object is passed, it will be encoded as JSON.

  • photo_url (str | None, default: None) – URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service.

  • photo_size (int | None, default: None) – Photo size in bytes.

  • photo_width (int | None, default: None) – Photo width.

  • photo_height (int | None, default: None) – Photo height.

  • need_name (bool | None, default: None) – Pass True, if you require the user’s full name to complete the order. Ignored for payments in |tg_stars|.

  • need_phone_number (bool | None, default: None) – Pass True, if you require the user’s phone number to complete the order. Ignored for payments in |tg_stars|.

  • need_email (bool | None, default: None) – Pass True, if you require the user’s email address to complete the order. Ignored for payments in |tg_stars|.

  • need_shipping_address (bool | None, default: None) – Pass True, if you require the user’s shipping address to complete the order. Ignored for payments in |tg_stars|.

  • send_phone_number_to_provider (bool | None, default: None) – Pass True, if user’s phone number should be sent to provider. Ignored for payments in |tg_stars|.

  • send_email_to_provider (bool | None, default: None) – Pass True, if user’s email address should be sent to provider. Ignored for payments in |tg_stars|.

  • is_flexible (bool | None, default: None) – Pass True, if the final price depends on the shipping method. Ignored for payments in |tg_stars|.

Returns:

On success, the created invoice link is returned.

Returns:

str

async create_new_sticker_set(user_id, name, title, stickers, sticker_type=None, needs_repainting=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set thus created.

Changed in version 20.0: The parameter contains_masks has been removed. Use sticker_type instead.

Changed in version 20.2: Since Bot API 6.6, the parameters stickers and sticker_format replace the parameters png_sticker, tgs_sticker,``webm_sticker``, emojis, and mask_position.

Changed in version 20.5: Removed the deprecated parameters mentioned above and adjusted the order of the parameters.

Removed in version 21.2: Removed the deprecated parameter sticker_format.

Parameters:
  • user_id (int) – User identifier of created sticker set owner.

  • name (str) – Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can’t contain consecutive underscores and must end in “_by_<bot username>”. <bot_username> is case insensitive. telegram.constants.StickerLimit.MIN_NAME_AND_TITLE- telegram.constants.StickerLimit.MAX_NAME_AND_TITLE characters.

  • title (str) – Sticker set title, telegram.constants.StickerLimit.MIN_NAME_AND_TITLE- telegram.constants.StickerLimit.MAX_NAME_AND_TITLE characters.

  • stickers (Sequence[InputSticker]) –

    A sequence of telegram.constants.StickerSetLimit.MIN_INITIAL_STICKERS- telegram.constants.StickerSetLimit.MAX_INITIAL_STICKERS initial stickers to be added to the sticker set.

    Added in version 20.2.

  • sticker_type (str | None, default: None) –

    Type of stickers in the set, pass telegram.Sticker.REGULAR or telegram.Sticker.MASK, or telegram.Sticker.CUSTOM_EMOJI. By default, a regular sticker set is created

    Added in version 20.0.

  • needs_repainting (bool | None, default: None) –

    Pass True if stickers in the sticker set must be repainted to the color of text when used in messages, the accent color if used as emoji status, white on chat photos, or another appropriate color based on context; for custom emoji sticker sets only.

    Added in version 20.2.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async declineChatJoinRequest(chat_id, user_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for decline_chat_join_request()

Return type:

bool

async declineSuggestedPost(chat_id, message_id, comment=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for decline_suggested_post()

Return type:

bool

async decline_chat_join_request(chat_id, user_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to decline a chat join request.

The bot must be an administrator in the chat for this to work and must have the telegram.ChatPermissions.can_invite_users administrator right.

Added in version 13.8.

Parameters:
Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async decline_suggested_post(chat_id, message_id, comment=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to decline a suggested post in a direct messages chat. The bot must have the can_manage_direct_messages administrator right in the corresponding channel chat.

Added in version 22.4.

Parameters:
  • chat_id (int) – Unique identifier of the target direct messages chat.

  • message_id (int) – Identifier of a suggested post message to decline.

  • comment (str | None, default: None) – Comment for the creator of the suggested post. 0-telegram.constants.SuggestedPost.MAX_COMMENT_LENGTH characters.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async deleteBusinessMessages(business_connection_id, message_ids, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for delete_business_messages()

Return type:

bool

async deleteChatPhoto(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for delete_chat_photo()

Return type:

bool

async deleteChatStickerSet(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for delete_chat_sticker_set()

Return type:

bool

async deleteForumTopic(chat_id, message_thread_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for delete_forum_topic()

Return type:

bool

async deleteMessage(chat_id, message_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for delete_message()

Return type:

bool

async deleteMessages(chat_id, message_ids, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for delete_messages()

Return type:

bool

async deleteMyCommands(scope=None, language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for delete_my_commands()

Return type:

bool

async deleteStickerFromSet(sticker, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for delete_sticker_from_set()

Return type:

bool

async deleteStickerSet(name, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for delete_sticker_set()

Return type:

bool

async deleteStory(business_connection_id, story_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for delete_story()

Return type:

bool

async deleteWebhook(drop_pending_updates=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for delete_webhook()

Return type:

bool

async delete_business_messages(business_connection_id, message_ids, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Delete messages on behalf of a business account. Requires the can_delete_sent_messages business bot right to delete messages sent by the bot itself, or the can_delete_all_messages business bot right to delete any message.

Added in version 22.1.

Parameters:
  • business_connection_id (str) – Unique identifier of the business connection on behalf of which to delete the messages

  • message_ids (Sequence[int]) – A list of telegram.constants.BulkRequestLimit.MIN_LIMIT- telegram.constants.BulkRequestLimit.MAX_LIMIT identifiers of messages to delete. See delete_message() for limitations on which messages can be deleted.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async delete_chat_photo(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to delete a chat photo. Photos can’t be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

Parameters:

chat_id (str | int) – |chat_id_channel|

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async delete_chat_sticker_set(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field telegram.ChatFullInfo.can_set_sticker_set optionally returned in get_chat() requests to check if the bot can use this method.

Parameters:

chat_id (str | int) – |chat_id_group|

Returns:

On success, True is returned.

Returns:

bool

async delete_forum_topic(chat_id, message_thread_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to delete a forum topic along with all its messages in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have ~telegram.ChatAdministratorRights.can_delete_messages administrator rights.

Added in version 20.0.

Parameters:
Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async delete_message(chat_id, message_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to delete a message, including service messages, with the following limitations:

  • A message can only be deleted if it was sent less than 48 hours ago.

  • Service messages about a supergroup, channel, or forum topic creation can’t be deleted.

  • A dice message in a private chat can only be deleted if it was sent more than 24 hours ago.

  • Bots can delete outgoing messages in private chats, groups, and supergroups.

  • Bots can delete incoming messages in private chats.

  • Bots granted can_post_messages permissions can delete outgoing messages in channels.

  • If the bot is an administrator of a group, it can delete any message there.

  • If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there.

Parameters:
Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async delete_messages(chat_id, message_ids, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to delete multiple messages simultaneously. If some of the specified messages can’t be found, they are skipped.

Added in version 20.8.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • message_ids (Sequence[int]) – A list of telegram.constants.BulkRequestLimit.MIN_LIMIT- telegram.constants.BulkRequestLimit.MAX_LIMIT identifiers of messages to delete. See delete_message() for limitations on which messages can be deleted.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async delete_my_commands(scope=None, language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to delete the list of the bot’s commands for the given scope and user language. After deletion, higher level commands will be shown to affected users.

Added in version 13.7.

Parameters:
  • scope (BotCommandScope | None, default: None) – An object, describing scope of users for which the commands are relevant. Defaults to telegram.BotCommandScopeDefault.

  • language_code (str | None, default: None) – A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async delete_sticker_from_set(sticker, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to delete a sticker from a set created by the bot.

Parameters:

sticker (str | Sticker) –

File identifier of the sticker or the sticker object.

Changed in version 21.10: Accepts also telegram.Sticker instances.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async delete_sticker_set(name, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to delete a sticker set that was created by the bot.

Added in version 20.2.

Parameters:

name (str) – Sticker set name.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async delete_story(business_connection_id, story_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Deletes a story previously posted by the bot on behalf of a managed business account. Requires the can_manage_stories business bot right.

Added in version 22.1.

Parameters:
  • business_connection_id (str) – Unique identifier of the business connection.

  • story_id (int) – Unique identifier of the story to delete.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async delete_webhook(drop_pending_updates=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to remove webhook integration if you decide to switch back to get_updates().

Parameters:

drop_pending_updates (bool | None, default: None) – Pass True to drop all pending updates.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async do_api_request(endpoint, api_kwargs=None, return_type=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None)[source]

Do a request to the Telegram API.

This method is here to make it easier to use new API methods that are not yet supported by this library.

Hint

Since PTB does not know which arguments are passed to this method, some caution is necessary in terms of PTBs utility functionalities. In particular

  • passing objects of any class defined in the telegram module is supported

  • when uploading files, a telegram.InputFile must be passed as the value for the corresponding argument. Passing a file path or file-like object will not work. File paths will work only in combination with ~Bot.local_mode.

  • when uploading files, PTB can still correctly determine that a special write timeout value should be used instead of the default telegram.request.HTTPXRequest.write_timeout.

  • insertion of default values specified via telegram.ext.Defaults will not work (only relevant for telegram.ext.ExtBot).

  • The only exception is telegram.ext.Defaults.tzinfo, which will be correctly applied to datetime.datetime objects.

Added in version 20.8.

Parameters:
  • endpoint (str) – The API endpoint to use, e.g. getMe or get_me.

  • api_kwargs (dict[str, Any] | None, default: None) – The keyword arguments to pass to the API call. If not specified, no arguments are passed.

  • return_type (type[TelegramObject] | None, default: None) – If specified, the result of the API call will be deserialized into an instance of this class or tuple of instances of this class. If not specified, the raw result of the API call will be returned.

Returns:

Any – The result of the API call. If return_type is not specified, this is a dict or bool, otherwise an instance of return_type or a tuple of return_type.

Raises:

telegram.error.TelegramError

Alias for edit_chat_invite_link()

Return type:

ChatInviteLink

Alias for edit_chat_subscription_invite_link()

Return type:

ChatInviteLink

async editForumTopic(chat_id, message_thread_id, name=None, icon_custom_emoji_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for edit_forum_topic()

Return type:

bool

async editGeneralForumTopic(chat_id, name, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for edit_general_forum_topic()

Return type:

bool

async editMessageCaption(chat_id=None, message_id=None, inline_message_id=None, caption=None, reply_markup=None, parse_mode=None, caption_entities=None, show_caption_above_media=None, business_connection_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for edit_message_caption()

Return type:

Message | bool

async editMessageChecklist(business_connection_id, chat_id, message_id, checklist, reply_markup=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for edit_message_checklist()

Return type:

Message

async editMessageLiveLocation(chat_id=None, message_id=None, inline_message_id=None, latitude=None, longitude=None, reply_markup=None, horizontal_accuracy=None, heading=None, proximity_alert_radius=None, live_period=None, business_connection_id=None, *, location=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for edit_message_live_location()

Return type:

Message | bool

async editMessageMedia(media, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None, business_connection_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for edit_message_media()

Return type:

Message | bool

async editMessageReplyMarkup(chat_id=None, message_id=None, inline_message_id=None, reply_markup=None, business_connection_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for edit_message_reply_markup()

Return type:

Message | bool

async editMessageText(text, chat_id=None, message_id=None, inline_message_id=None, parse_mode=None, reply_markup=None, entities=None, link_preview_options=None, business_connection_id=None, *, disable_web_page_preview=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for edit_message_text()

Return type:

Message | bool

async editStory(business_connection_id, story_id, content, caption=None, parse_mode=None, caption_entities=None, areas=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for edit_story()

Return type:

Story

async editUserStarSubscription(user_id, telegram_payment_charge_id, is_canceled, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for edit_user_star_subscription()

Return type:

bool

Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

Note

Though not stated explicitly in the official docs, Telegram changes not only the optional parameters that are explicitly passed, but also replaces all other optional parameters to the default values. However, since not documented, this behaviour may change unbeknown to PTB.

Added in version 13.4.

Parameters:
  • chat_id (str | int) – |chat_id_channel|

  • invite_link (str | ChatInviteLink) –

    The invite link to edit.

    Changed in version 20.0: Now also accepts telegram.ChatInviteLink instances.

  • expire_date (int | datetime | None, default: None) – Date when the link will expire. |tz-naive-dtms|

  • member_limit (int | None, default: None) – Maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; telegram.constants.ChatInviteLinkLimit.MIN_MEMBER_LIMIT- telegram.constants.ChatInviteLinkLimit.MAX_MEMBER_LIMIT.

  • name (str | None, default: None) –

    Invite link name; 0-telegram.constants.ChatInviteLinkLimit.NAME_LENGTH characters.

    Added in version 13.8.

  • creates_join_request (bool | None, default: None) –

    True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can’t be specified.

    Added in version 13.8.

Returns:

ChatInviteLinktelegram.ChatInviteLink

Raises:

telegram.error.TelegramError

Use this method to edit a subscription invite link created by the bot. The bot must have telegram.ChatPermissions.can_invite_users administrator right.

Added in version 21.5.

Parameters:
  • chat_id (str | int) – |chat_id_channel|

  • invite_link (str | ChatInviteLink) – The invite link to edit.

  • name (str | None, default: None) –

    Invite link name; 0-telegram.constants.ChatInviteLinkLimit.NAME_LENGTH characters.

    Tip

    Omitting this argument removes the name of the invite link.

Returns:

ChatInviteLinktelegram.ChatInviteLink

Raises:

telegram.error.TelegramError

async edit_forum_topic(chat_id, message_thread_id, name=None, icon_custom_emoji_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to edit name and icon of a topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the ~telegram.ChatAdministratorRights.can_manage_topics administrator rights, unless it is the creator of the topic.

Added in version 20.0.

Parameters:
  • chat_id (str | int) – |chat_id_group|

  • message_thread_id (int) – |message_thread_id|

  • name (str | None, default: None) – New topic name, telegram.constants.ForumTopicLimit.MIN_NAME_LENGTH- telegram.constants.ForumTopicLimit.MAX_NAME_LENGTH characters. If not specified or empty, the current name of the topic will be kept.

  • icon_custom_emoji_id (str | None, default: None) – New unique identifier of the custom emoji shown as the topic icon. Use get_forum_topic_icon_stickers() to get all allowed custom emoji identifiers.Pass an empty string to remove the icon. If not specified, the current icon will be kept.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async edit_general_forum_topic(chat_id, name, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to edit the name of the ‘General’ topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights.

Added in version 20.0.

Parameters:
  • chat_id (str | int) – |chat_id_group|

  • name (str) – New topic name, telegram.constants.ForumTopicLimit.MIN_NAME_LENGTH- telegram.constants.ForumTopicLimit.MAX_NAME_LENGTH characters.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async edit_message_caption(chat_id=None, message_id=None, inline_message_id=None, caption=None, reply_markup=None, parse_mode=None, caption_entities=None, show_caption_above_media=None, business_connection_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to edit captions of messages.

Parameters:
  • chat_id (int | str | None, default: None) – Required if inline_message_id is not specified. |chat_id_channel|

  • message_id (int | None, default: None) – Required if inline_message_id is not specified. Identifier of the message to edit.

  • inline_message_id (str | None, default: None) – Required if chat_id and message_id are not specified. Identifier of the inline message.

  • caption (str | None, default: None) – New caption of the message, 0-telegram.constants.MessageLimit.CAPTION_LENGTH characters after entities parsing.

  • parse_mode (DefaultValue[DVValueType] | str | DefaultValue[None] | None, default: None) – |parse_mode|

  • caption_entities (Sequence[MessageEntity] | None, default: None) –

    |caption_entities|

    Changed in version 20.0: |sequenceargs|

  • reply_markup (InlineKeyboardMarkup | None, default: None) – An object for an inline keyboard.

  • show_caption_above_media (bool | None, default: None) –

    Pass |show_cap_above_med|

    Added in version 21.3.

  • business_connection_id (str | None, default: None) –

    |business_id_str_edit|

    Added in version 21.4.

Returns:

On success, if edited message is not an inline message, the edited message is returned, otherwise True is returned.

Returns:

Message | bool

Raises:

telegram.error.TelegramError

async edit_message_checklist(business_connection_id, chat_id, message_id, checklist, reply_markup=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to edit a checklist on behalf of a connected business account.

Added in version 22.3.

Parameters:
  • business_connection_id (str) – |business_id_str|

  • chat_id (int) – Unique identifier for the target chat.

  • message_id (int) – Unique identifier for the target message.

  • checklist (InputChecklist) – The new checklist.

  • reply_markup (InlineKeyboardMarkup | None, default: None) – An object for the new inline keyboard for the message.

Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async edit_message_live_location(chat_id=None, message_id=None, inline_message_id=None, latitude=None, longitude=None, reply_markup=None, horizontal_accuracy=None, heading=None, proximity_alert_radius=None, live_period=None, business_connection_id=None, *, location=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to edit live location messages sent by the bot or via the bot (for inline bots). A location can be edited until its telegram.Location.live_period expires or editing is explicitly disabled by a call to stop_message_live_location().

Note

You can either supply a latitude and longitude or a location.

Parameters:
  • chat_id (int | str | None, default: None) – Required if inline_message_id is not specified. |chat_id_channel|

  • message_id (int | None, default: None) – Required if inline_message_id is not specified. Identifier of the message to edit.

  • inline_message_id (str | None, default: None) – Required if chat_id and message_id are not specified. Identifier of the inline message.

  • latitude (float | None, default: None) – Latitude of location.

  • longitude (float | None, default: None) – Longitude of location.

  • horizontal_accuracy (float | None, default: None) – The radius of uncertainty for the location, measured in meters; 0-telegram.constants.LocationLimit.HORIZONTAL_ACCURACY.

  • heading (int | None, default: None) – Direction in which the user is moving, in degrees. Must be between telegram.constants.LocationLimit.MIN_HEADING and telegram.constants.LocationLimit.MAX_HEADING if specified.

  • proximity_alert_radius (int | None, default: None) – Maximum distance for proximity alerts about approaching another chat member, in meters. Must be between telegram.constants.LocationLimit.MIN_PROXIMITY_ALERT_RADIUS and telegram.constants.LocationLimit.MAX_PROXIMITY_ALERT_RADIUS if specified.

  • reply_markup (InlineKeyboardMarkup | None, default: None) – An object for a new inline keyboard.

  • live_period (int | timedelta | None, default: None) –

    New period in seconds during which the location can be updated, starting from the message send date. If telegram.constants.LocationLimit.LIVE_PERIOD_FOREVER is specified, then the location can be updated forever. Otherwise, the new value must not exceed the current live_period by more than a day, and the live location expiration date must remain within the next 90 days. If not specified, then live_period remains unchanged

    Added in version 21.2..

    Changed in version 21.11: |time-period-input|

  • business_connection_id (str | None, default: None) –

    |business_id_str_edit|

    Added in version 21.4.

Keyword Arguments:

location (telegram.Location, optional) – The location to send.

Returns:

On success, if edited message is not an inline message, the edited message is returned, otherwise True is returned.

Returns:

Message | bool

async edit_message_media(media, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None, business_connection_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to edit animation, audio, document, photo, or video messages, or to add media to text messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can’t be uploaded; use a previously uploaded file via its file_id or specify a URL.

See also

Working with Files and Media <Working-with-Files-and-Media>

Parameters:
  • media (InputMedia) – An object for a new media content of the message.

  • chat_id (int | str | None, default: None) – Required if inline_message_id is not specified. |chat_id_channel|

  • message_id (int | None, default: None) – Required if inline_message_id is not specified. Identifier of the message to edit.

  • inline_message_id (str | None, default: None) – Required if chat_id and message_id are not specified. Identifier of the inline message.

  • reply_markup (InlineKeyboardMarkup | None, default: None) – An object for an inline keyboard.

  • business_connection_id (str | None, default: None) –

    |business_id_str_edit|

    Added in version 21.4.

Returns:

On success, if edited message is not an inline message, the edited Message is returned, otherwise True is returned.

Returns:

Message | bool

Raises:

telegram.error.TelegramError

async edit_message_reply_markup(chat_id=None, message_id=None, inline_message_id=None, reply_markup=None, business_connection_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots).

Parameters:
  • chat_id (int | str | None, default: None) – Required if inline_message_id is not specified. |chat_id_channel|

  • message_id (int | None, default: None) – Required if inline_message_id is not specified. Identifier of the message to edit.

  • inline_message_id (str | None, default: None) – Required if chat_id and message_id are not specified. Identifier of the inline message.

  • reply_markup (InlineKeyboardMarkup | None, default: None) – An object for an inline keyboard.

  • business_connection_id (str | None, default: None) –

    |business_id_str_edit|

    Added in version 21.4.

Returns:

On success, if edited message is not an inline message, the edited message is returned, otherwise True is returned.

Returns:

Message | bool

Raises:

telegram.error.TelegramError

async edit_message_text(text, chat_id=None, message_id=None, inline_message_id=None, parse_mode=None, reply_markup=None, entities=None, link_preview_options=None, business_connection_id=None, *, disable_web_page_preview=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to edit text and game messages.

Parameters:
  • chat_id (int | str | None, default: None) – Required if inline_message_id is not specified. |chat_id_channel|

  • message_id (int | None, default: None) – Required if inline_message_id is not specified. Identifier of the message to edit.

  • inline_message_id (str | None, default: None) – Required if chat_id and message_id are not specified. Identifier of the inline message.

  • text (str) – New text of the message, telegram.constants.MessageLimit.MIN_TEXT_LENGTH- telegram.constants.MessageLimit.MAX_TEXT_LENGTH characters after entities parsing.

  • parse_mode (DefaultValue[DVValueType] | str | DefaultValue[None] | None, default: None) – |parse_mode|

  • entities (Sequence[MessageEntity] | None, default: None) –

    Sequence of special entities that appear in message text, which can be specified instead of parse_mode.

    Changed in version 20.0: |sequenceargs|

  • link_preview_options (DefaultValue[DVValueType] | LinkPreviewOptions | DefaultValue[None] | None, default: None) –

    Link preview generation options for the message. Mutually exclusive with disable_web_page_preview.

    Added in version 20.8.

  • reply_markup (InlineKeyboardMarkup | None, default: None) – An object for an inline keyboard.

  • business_connection_id (str | None, default: None) –

    |business_id_str_edit|

    Added in version 21.4.

Keyword Arguments:

disable_web_page_preview (bool, optional) –

Disables link previews for links in this message. Convenience parameter for setting link_preview_options. Mutually exclusive with link_preview_options.

Changed in version 20.8: Bot API 7.0 introduced link_preview_options replacing this argument. PTB will automatically convert this argument to that one, but for advanced options, please use link_preview_options directly.

Changed in version 21.0: |keyword_only_arg|

Returns:

On success, if edited message is not an inline message, the edited message is returned, otherwise True is returned.

Returns:

Message | bool

Raises:
async edit_story(business_connection_id, story_id, content, caption=None, parse_mode=None, caption_entities=None, areas=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Edits a story previously posted by the bot on behalf of a managed business account. Requires the can_manage_stories business bot right.

Added in version 22.1.

Parameters:
  • business_connection_id (str) – Unique identifier of the business connection.

  • story_id (int) – Unique identifier of the story to edit.

  • content (InputStoryContent) – Content of the story.

  • caption (str | None, default: None) – Caption of the story, 0-~telegram.constants.StoryLimit.CAPTION_LENGTH characters after entities parsing.

  • parse_mode (DefaultValue[DVValueType] | str | DefaultValue[None] | None, default: None) – Mode for parsing entities in the story caption. See the constants in telegram.constants.ParseMode for the available modes.

  • caption_entities (Sequence[MessageEntity] | None, default: None) – |caption_entities|

  • areas (Sequence[StoryArea] | None, default: None) –

    Sequence of clickable areas to be shown on the story.

    Note

    Each type of clickable area in areas has its own maximum limit:

Returns:

StoryStory

Raises:

telegram.error.TelegramError

async edit_user_star_subscription(user_id, telegram_payment_charge_id, is_canceled, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Allows the bot to cancel or re-enable extension of a subscription paid in Telegram Stars.

Added in version 21.8.

Parameters:
  • user_id (int) – Identifier of the user whose subscription will be edited.

  • telegram_payment_charge_id (str) – Telegram payment identifier for the subscription.

  • is_canceled (bool) – Pass True to cancel extension of the user subscription; the subscription must be active up to the end of the current subscription period. Pass False to allow the user to re-enable a subscription that was previously canceled by the bot.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

Alias for export_chat_invite_link()

Return type:

str

Use this method to generate a new primary invite link for a chat; any previously generated link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

Note

Each administrator in a chat generates their own invite links. Bots can’t use invite links generated by other administrators. If you want your bot to work with invite links, it will need to generate its own link using export_chat_invite_link() or by calling the get_chat() method. If your bot needs to generate a new primary invite link replacing its previous one, use export_chat_invite_link() again.

Parameters:

chat_id (str | int) – |chat_id_channel|

Returns:

New invite link on success.

Returns:

str

Raises:

telegram.error.TelegramError

property first_name: str

Bot’s first name. Shortcut for the corresponding attribute of bot.

Type:

str

async forwardMessage(chat_id, from_chat_id, message_id, disable_notification=None, protect_content=None, message_thread_id=None, video_start_timestamp=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for forward_message()

Return type:

Message

async forwardMessages(chat_id, from_chat_id, message_ids, disable_notification=None, protect_content=None, message_thread_id=None, direct_messages_topic_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for forward_messages()

Return type:

tuple[MessageId, ...]

async forward_message(chat_id, from_chat_id, message_id, disable_notification=None, protect_content=None, message_thread_id=None, video_start_timestamp=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to forward messages of any kind. Service messages can’t be forwarded.

Note

Since the release of Bot API 5.5 it can be impossible to forward messages from some chats. Use the attributes telegram.Message.has_protected_content and telegram.ChatFullInfo.has_protected_content to check this.

As a workaround, it is still possible to use copy_message(). However, this behaviour is undocumented and might be changed by Telegram.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • from_chat_id (str | int) – Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername).

  • message_id (int) – Message identifier in the chat specified in from_chat_id.

  • video_start_timestamp (int | None, default: None) –

    New start timestamp for the forwarded video in the message

    Added in version 21.11.

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) –

    |protect_content|

    Added in version 13.10.

  • message_thread_id (int | None, default: None) –

    |message_thread_id_arg|

    Added in version 20.0.

  • suggested_post_parameters (SuggestedPostParameters | None, default: None) –

    An object containing the parameters of the suggested post to send; for direct messages chats only.

    Added in version 22.4.

  • direct_messages_topic_id (int | None, default: None) –

    Identifier of the direct messages topic to which the message will be forwarded; required if the message is forwarded to a direct messages chat.

    Added in version 22.4.

Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async forward_messages(chat_id, from_chat_id, message_ids, disable_notification=None, protect_content=None, message_thread_id=None, direct_messages_topic_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to forward messages of any kind. If some of the specified messages can’t be found or forwarded, they are skipped. Service messages and messages with protected content can’t be forwarded. Album grouping is kept for forwarded messages.

Added in version 20.8.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • from_chat_id (str | int) – Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername).

  • message_ids (Sequence[int]) – A list of telegram.constants.BulkRequestLimit.MIN_LIMIT- telegram.constants.BulkRequestLimit.MAX_LIMIT identifiers of messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order.

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |protect_content|

  • message_thread_id (int | None, default: None) – |message_thread_id_arg|

  • direct_messages_topic_id (int | None, default: None) –

    Identifier of the direct messages topic to which the messages will be forwarded; required if the messages are forwarded to a direct messages chat.

    Added in version 22.4.

Returns:

On success, a tuple of MessageId of sent messages is returned.

Returns:

tuple[MessageId, ...]

Raises:

telegram.error.TelegramError

async getAvailableGifts(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_available_gifts()

Return type:

Gifts

async getBusinessAccountGifts(business_connection_id, exclude_unsaved=None, exclude_saved=None, exclude_unlimited=None, exclude_limited=None, exclude_unique=None, sort_by_price=None, offset=None, limit=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_business_account_gifts()

Return type:

OwnedGifts

async getBusinessAccountStarBalance(business_connection_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_business_account_star_balance()

Return type:

StarAmount

async getBusinessConnection(business_connection_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_business_connection()

Return type:

BusinessConnection

async getChat(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_chat()

Return type:

ChatFullInfo

async getChatAdministrators(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_chat_administrators()

Return type:

tuple[ChatMember, ...]

async getChatMember(chat_id, user_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_chat_member()

Return type:

ChatMember

async getChatMemberCount(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_chat_member_count()

Return type:

int

async getChatMenuButton(chat_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_chat_menu_button()

Return type:

MenuButton

async getCustomEmojiStickers(custom_emoji_ids, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_custom_emoji_stickers()

Return type:

tuple[Sticker, ...]

async getFile(file_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_file()

Return type:

File

async getForumTopicIconStickers(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_forum_topic_icon_stickers()

Return type:

tuple[Sticker, ...]

async getGameHighScores(user_id, chat_id=None, message_id=None, inline_message_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_game_high_scores()

Return type:

tuple[GameHighScore, ...]

async getMe(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_me()

Return type:

User

async getMyCommands(scope=None, language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_my_commands()

Return type:

tuple[BotCommand, ...]

async getMyDefaultAdministratorRights(for_channels=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_my_default_administrator_rights()

Return type:

ChatAdministratorRights

async getMyDescription(language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_my_description()

Return type:

BotDescription

async getMyName(language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_my_name()

Return type:

BotName

async getMyShortDescription(language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_my_short_description()

Return type:

BotShortDescription

async getMyStarBalance(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_my_star_balance()

Return type:

StarAmount

async getStarTransactions(offset=None, limit=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_star_transactions()

Return type:

StarTransactions

async getStickerSet(name, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_sticker_set()

Return type:

StickerSet

async getUpdates(offset=None, limit=None, timeout=None, allowed_updates=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_updates()

Return type:

tuple[Update, ...]

async getUserChatBoosts(chat_id, user_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_user_chat_boosts()

Return type:

UserChatBoosts

async getUserProfilePhotos(user_id, offset=None, limit=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_user_profile_photos()

Return type:

UserProfilePhotos

async getWebhookInfo(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for get_webhook_info()

Return type:

WebhookInfo

async get_available_gifts(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Returns the list of gifts that can be sent by the bot to users and channel chats. Requires no parameters.

Added in version 21.8.

Returns:

Giftstelegram.Gifts

Raises:

telegram.error.TelegramError

async get_business_account_gifts(business_connection_id, exclude_unsaved=None, exclude_saved=None, exclude_unlimited=None, exclude_limited=None, exclude_unique=None, sort_by_price=None, offset=None, limit=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Returns the gifts received and owned by a managed business account. Requires the can_view_gifts_and_stars business bot right.

Added in version 22.1.

Parameters:
  • business_connection_id (str) – Unique identifier of the business connection.

  • exclude_unsaved (bool | None, default: None) – Pass True to exclude gifts that aren’t saved to the account’s profile page.

  • exclude_saved (bool | None, default: None) – Pass True to exclude gifts that are saved to the account’s profile page.

  • exclude_unlimited (bool | None, default: None) – Pass True to exclude gifts that can be purchased an unlimited number of times.

  • exclude_limited (bool | None, default: None) – Pass True to exclude gifts that can be purchased a limited number of times.

  • exclude_unique (bool | None, default: None) – Pass True to exclude unique gifts.

  • sort_by_price (bool | None, default: None) – Pass True to sort results by gift price instead of send date. Sorting is applied before pagination.

  • offset (str | None, default: None) – Offset of the first entry to return as received from the previous request; use empty string to get the first chunk of results.

  • limit (int | None, default: None) – The maximum number of gifts to be returned; telegram.constants.BusinessLimit.MIN_GIFT_RESULTS- telegram.constants.BusinessLimit.MAX_GIFT_RESULTS. Defaults to telegram.constants.BusinessLimit.MAX_GIFT_RESULTS.

Returns:

OwnedGiftstelegram.OwnedGifts

Raises:

telegram.error.TelegramError

async get_business_account_star_balance(business_connection_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Returns the amount of Telegram Stars owned by a managed business account. Requires the can_view_gifts_and_stars business bot right.

Added in version 22.1.

Parameters:

business_connection_id (str) – Unique identifier of the business connection.

Returns:

StarAmounttelegram.StarAmount

Raises:

telegram.error.TelegramError

async get_business_connection(business_connection_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get information about the connection of the bot with a business account.

Added in version 21.1.

Parameters:

business_connection_id (str) – Unique identifier of the business connection.

Returns:

On success, the object containing the business

connection information is returned.

Returns:

BusinessConnection

Raises:

telegram.error.TelegramError

async get_chat(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.).

Changed in version 21.2: In accordance to Bot API 7.3, this method now returns a telegram.ChatFullInfo.

Parameters:

chat_id (str | int) – |chat_id_channel|

Returns:

ChatFullInfotelegram.ChatFullInfo

Raises:

telegram.error.TelegramError

async get_chat_administrators(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get a list of administrators in a chat.

Changed in version 20.0: Returns a tuple instead of a list.

Parameters:

chat_id (str | int) – |chat_id_channel|

Returns:

On success, returns a tuple of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.

Returns:

tuple[ChatMember, ...]

Raises:

telegram.error.TelegramError

async get_chat_member(chat_id, user_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get information about a member of a chat. The method is only guaranteed to work for other users if the bot is an administrator in the chat.

Parameters:
Returns:

ChatMembertelegram.ChatMember

Raises:

telegram.error.TelegramError

async get_chat_member_count(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get the number of members in a chat.

Added in version 13.7.

Parameters:

chat_id (str | int) – |chat_id_channel|

Returns:

Number of members in the chat.

Returns:

int

Raises:

telegram.error.TelegramError

async get_chat_menu_button(chat_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get the current value of the bot’s menu button in a private chat, or the default menu button.

Added in version 20.0.

Parameters:

chat_id (int | None, default: None) – Unique identifier for the target private chat. If not specified, default bot’s menu button will be returned.

Returns:

On success, the current menu button is returned.

Returns:

MenuButton

async get_custom_emoji_stickers(custom_emoji_ids, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get information about emoji stickers by their identifiers.

Changed in version 20.0: Returns a tuple instead of a list.

Parameters:

custom_emoji_ids (Sequence[str]) –

Sequence of custom emoji identifiers. At most telegram.constants.CustomEmojiStickerLimit.CUSTOM_EMOJI_IDENTIFIER_LIMIT custom emoji identifiers can be specified.

Changed in version 20.0: |sequenceargs|

Returns:

tuple[Sticker, ...] – tuple[telegram.Sticker]

Raises:

telegram.error.TelegramError

async get_file(file_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to telegram.constants.FileSizeLimit.FILESIZE_DOWNLOAD in size. The file can then be e.g. downloaded with telegram.File.download_to_drive(). It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling get_file again.

Note

This function may not preserve the original file name and MIME type. You should save the file’s MIME type and name (if available) when the File object is received.

See also

Working with Files and Media <Working-with-Files-and-Media>

Parameters:

file_id (str | Animation | Audio | ChatPhoto | Document | PhotoSize | Sticker | Video | VideoNote | Voice) – Either the file identifier or an object that has a file_id attribute to get file information about.

Returns:

Filetelegram.File

Raises:

telegram.error.TelegramError

async get_forum_topic_icon_stickers(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user. Requires no parameters.

Added in version 20.0.

Returns:

tuple[Sticker, ...] – tuple[telegram.Sticker]

Raises:

telegram.error.TelegramError

async get_game_high_scores(user_id, chat_id=None, message_id=None, inline_message_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game.

Note

This method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change.

Changed in version 20.0: Returns a tuple instead of a list.

Parameters:
  • user_id (int) – Target user id.

  • chat_id (int | None, default: None) – Required if inline_message_id is not specified. Unique identifier for the target chat.

  • message_id (int | None, default: None) – Required if inline_message_id is not specified. Identifier of the sent message.

  • inline_message_id (str | None, default: None) – Required if chat_id and message_id are not specified. Identifier of the inline message.

Returns:

tuple[GameHighScore, ...] – tuple[telegram.GameHighScore]

Raises:

telegram.error.TelegramError

async get_me(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

A simple method for testing your bot’s auth token. Requires no parameters.

Returns:

A telegram.User instance representing that bot if the credentials are valid, None otherwise.

Returns:

User

Raises:

telegram.error.TelegramError

async get_my_commands(scope=None, language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get the current list of the bot’s commands for the given scope and user language.

Changed in version 20.0: Returns a tuple instead of a list.

Parameters:
Returns:

On success, the commands set for the bot. An empty tuple is returned if commands are not set.

Returns:

tuple[BotCommand, ...]

Raises:

telegram.error.TelegramError

async get_my_default_administrator_rights(for_channels=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get the current default administrator rights of the bot.

Added in version 20.0.

Parameters:

for_channels (bool | None, default: None) – Pass True to get default administrator rights of the bot in channels. Otherwise, default administrator rights of the bot for groups and supergroups will be returned.

Returns:

On success.

Returns:

ChatAdministratorRights

Raises:

telegram.error.TelegramError

async get_my_description(language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get the current bot description for the given user language.

Parameters:

language_code (str | None, default: None) – A two-letter ISO 639-1 language code or an empty string.

Returns:

On success, the bot description is returned.

Returns:

BotDescription

Raises:

telegram.error.TelegramError

async get_my_name(language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get the current bot name for the given user language.

Parameters:

language_code (str | None, default: None) – A two-letter ISO 639-1 language code or an empty string.

Returns:

On success, the bot name is returned.

Returns:

BotName

Raises:

telegram.error.TelegramError

async get_my_short_description(language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get the current bot short description for the given user language.

Parameters:

language_code (str | None, default: None) – A two-letter ISO 639-1 language code or an empty string.

Returns:

On success, the bot short description is

returned.

Returns:

BotShortDescription

Raises:

telegram.error.TelegramError

async get_my_star_balance(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

A method to get the current Telegram Stars balance of the bot. Requires no parameters.

Added in version 22.3.

Returns:

StarAmounttelegram.StarAmount

Raises:

telegram.error.TelegramError

async get_star_transactions(offset=None, limit=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Returns the bot’s Telegram Star transactions in chronological order.

Added in version 21.4.

Parameters:
  • offset (int | None, default: None) – Number of transactions to skip in the response.

  • limit (int | None, default: None) – The maximum number of transactions to be retrieved. Values between telegram.constants.StarTransactionsLimit.MIN_LIMIT- telegram.constants.StarTransactionsLimit.MAX_LIMIT are accepted. Defaults to telegram.constants.StarTransactionsLimit.MAX_LIMIT.

Returns:

On success.

Returns:

StarTransactions

Raises:

telegram.error.TelegramError

async get_sticker_set(name, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get a sticker set.

Parameters:

name (str) – Name of the sticker set.

Returns:

StickerSettelegram.StickerSet

Raises:

telegram.error.TelegramError

async get_updates(offset=None, limit=None, timeout=None, allowed_updates=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to receive incoming updates using long polling.

Note

  1. This method will not work if an outgoing webhook is set up.

  2. In order to avoid getting duplicate updates, recalculate offset after each server response.

  3. To take full advantage of this library take a look at telegram.ext.Updater

Changed in version 20.0: Returns a tuple instead of a list.

Parameters:
  • offset (int | None, default: None) – Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as this method is called with an offset higher than its telegram.Update.update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will be forgotten.

  • limit (int | None, default: None) – Limits the number of updates to be retrieved. Values between telegram.constants.PollingLimit.MIN_LIMIT- telegram.constants.PollingLimit.MAX_LIMIT are accepted. Defaults to 100.

  • timeout (int | timedelta | None, default: None) –

    Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only.

    Changed in version v22.2: |time-period-input|

  • allowed_updates (Sequence[str] | None, default: None) –

    A sequence the types of updates you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See telegram.Update for a complete list of available update types. Specify an empty sequence to receive all updates except telegram.Update.chat_member, telegram.Update.message_reaction and telegram.Update.message_reaction_count (default). If not specified, the previous setting will be used. Please note that this parameter doesn’t affect updates created before the call to the get_updates, so unwanted updates may be received for a short period of time.

    Changed in version 20.0: |sequenceargs|

Returns:

tuple[Update, ...] – tuple[telegram.Update]

Raises:

telegram.error.TelegramError

async get_user_chat_boosts(chat_id, user_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get the list of boosts added to a chat by a user. Requires administrator rights in the chat.

Added in version 20.8.

Parameters:
Returns:

On success, the object containing the list of boosts

is returned.

Returns:

UserChatBoosts

Raises:

telegram.error.TelegramError

async get_user_profile_photos(user_id, offset=None, limit=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get a list of profile pictures for a user.

Parameters:
  • user_id (int) – Unique identifier of the target user.

  • offset (int | None, default: None) – Sequential number of the first photo to be returned. By default, all photos are returned.

  • limit (int | None, default: None) – Limits the number of photos to be retrieved. Values between telegram.constants.UserProfilePhotosLimit.MIN_LIMIT- telegram.constants.UserProfilePhotosLimit.MAX_LIMIT are accepted. Defaults to 100.

Returns:

UserProfilePhotostelegram.UserProfilePhotos

Raises:

telegram.error.TelegramError

async get_webhook_info(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to get current webhook status. Requires no parameters.

If the bot is using get_updates(), will return an object with the telegram.WebhookInfo.url field empty.

Returns:

WebhookInfotelegram.WebhookInfo

async giftPremiumSubscription(user_id, month_count, star_count, text=None, text_parse_mode=None, text_entities=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for gift_premium_subscription()

Return type:

bool

async gift_premium_subscription(user_id, month_count, star_count, text=None, text_parse_mode=None, text_entities=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Gifts a Telegram Premium subscription to the given user.

Added in version 22.1.

Parameters:
  • user_id (int) – Unique identifier of the target user who will receive a Telegram Premium subscription.

  • month_count (int) – Number of months the Telegram Premium subscription will be active for the user; must be one of telegram.constants.PremiumSubscription.MONTH_COUNT_THREE, telegram.constants.PremiumSubscription.MONTH_COUNT_SIX, or telegram.constants.PremiumSubscription.MONTH_COUNT_TWELVE.

  • star_count (int) – Number of Telegram Stars to pay for the Telegram Premium subscription; must be telegram.constants.PremiumSubscription.STARS_THREE_MONTHS for telegram.constants.PremiumSubscription.MONTH_COUNT_THREE months, telegram.constants.PremiumSubscription.STARS_SIX_MONTHS for telegram.constants.PremiumSubscription.MONTH_COUNT_SIX months, and telegram.constants.PremiumSubscription.STARS_TWELVE_MONTHS for telegram.constants.PremiumSubscription.MONTH_COUNT_TWELVE months.

  • text (str | None, default: None) – Text that will be shown along with the service message about the subscription; 0-telegram.constants.PremiumSubscription.MAX_TEXT_LENGTH characters.

  • text_parse_mode (DefaultValue[DVValueType] | str | DefaultValue[None] | None, default: None) – Mode for parsing entities. See telegram.constants.ParseMode and formatting options for more details. Entities other than BOLD, ITALIC, UNDERLINE, STRIKETHROUGH, SPOILER, and CUSTOM_EMOJI are ignored.

  • text_entities (Sequence[MessageEntity] | None, default: None) – A list of special entities that appear in the gift text. It can be specified instead of text_parse_mode. Entities other than BOLD, ITALIC, UNDERLINE, STRIKETHROUGH, SPOILER, and CUSTOM_EMOJI are ignored.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async hideGeneralForumTopic(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for hide_general_forum_topic()

Return type:

bool

async hide_general_forum_topic(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to hide the ‘General’ topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have can_manage_topics administrator rights. The topic will be automatically closed if it was open.

Added in version 20.0.

Parameters:

chat_id (str | int) – |chat_id_group|

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

property id: int

Unique identifier for this bot. Shortcut for the corresponding attribute of bot.

Type:

int

async initialize()[source]

Initialize resources used by this class. Currently calls get_me() to cache bot and calls telegram.request.BaseRequest.initialize() for the request objects used by this bot.

See also

shutdown()

Added in version 20.0.

Return type:

None

property last_name: str

Optional. Bot’s last name. Shortcut for the corresponding attribute of bot.

Type:

str

async leaveChat(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for leave_chat()

Return type:

bool

async leave_chat(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method for your bot to leave a group, supergroup or channel.

Parameters:

chat_id (str | int) – |chat_id_channel|

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

Convenience property. Returns the t.me link of the bot.

Type:

str

property local_mode: bool

Whether this bot is running in local mode.

Added in version 20.0.

Type:

bool

async logOut(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for log_out()

Return type:

bool

async log_out(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to log out from the cloud Bot API server before launching the bot locally. You must log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. After a successful call, you can immediately log in on a local server, but will not be able to log in back to the cloud Bot API server for 10 minutes.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

property name: str

Bot’s @username. Shortcut for the corresponding attribute of bot.

Type:

str

async pinChatMessage(chat_id, message_id, disable_notification=None, business_connection_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for pin_chat_message()

Return type:

bool

async pin_chat_message(chat_id, message_id, disable_notification=None, business_connection_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to add a message to the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the ~telegram.ChatAdministratorRights.can_pin_messages admin right in a supergroup or can_edit_messages admin right in a channel.

Parameters:
  • chat_id (str | int) – |chat_id_channel|

  • message_id (int) – Identifier of a message to pin.

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – Pass True, if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels and private chats.

  • business_connection_id (str | None, default: None) –

    Unique identifier of the business connection on behalf of which the message will be pinned.

    Added in version 21.5.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async postStory(business_connection_id, content, active_period, caption=None, parse_mode=None, caption_entities=None, areas=None, post_to_chat_page=None, protect_content=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for post_story()

Return type:

Story

async post_story(business_connection_id, content, active_period, caption=None, parse_mode=None, caption_entities=None, areas=None, post_to_chat_page=None, protect_content=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Posts a story on behalf of a managed business account. Requires the can_manage_stories business bot right.

Added in version 22.1.

Parameters:
  • business_connection_id (str) – Unique identifier of the business connection.

  • content (InputStoryContent) – Content of the story.

  • active_period (int | timedelta) – Period after which the story is moved to the archive, in seconds; must be one of ~telegram.constants.StoryLimit.ACTIVITY_SIX_HOURS, ~telegram.constants.StoryLimit.ACTIVITY_TWELVE_HOURS, ~telegram.constants.StoryLimit.ACTIVITY_ONE_DAY, or ~telegram.constants.StoryLimit.ACTIVITY_TWO_DAYS.

  • caption (str | None, default: None) – Caption of the story, 0-~telegram.constants.StoryLimit.CAPTION_LENGTH characters after entities parsing.

  • parse_mode (DefaultValue[DVValueType] | str | DefaultValue[None] | None, default: None) – Mode for parsing entities in the story caption. See the constants in telegram.constants.ParseMode for the available modes.

  • caption_entities (Sequence[MessageEntity] | None, default: None) – |caption_entities|

  • areas (Sequence[StoryArea] | None, default: None) –

    Sequence of clickable areas to be shown on the story.

    Note

    Each type of clickable area in areas has its own maximum limit:

  • post_to_chat_page (bool | None, default: None) – Pass True to keep the story accessible after it expires.

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – Pass True if the content of the story must be protected from forwarding and screenshotting

Returns:

StoryStory

Raises:

telegram.error.TelegramError

property private_key: Any | None

Deserialized private key for decryption of telegram passport data.

Added in version 20.0.

async promoteChatMember(chat_id, user_id, can_change_info=None, can_post_messages=None, can_edit_messages=None, can_delete_messages=None, can_invite_users=None, can_restrict_members=None, can_pin_messages=None, can_promote_members=None, is_anonymous=None, can_manage_chat=None, can_manage_video_chats=None, can_manage_topics=None, can_post_stories=None, can_edit_stories=None, can_delete_stories=None, can_manage_direct_messages=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for promote_chat_member()

Return type:

bool

async promote_chat_member(chat_id, user_id, can_change_info=None, can_post_messages=None, can_edit_messages=None, can_delete_messages=None, can_invite_users=None, can_restrict_members=None, can_pin_messages=None, can_promote_members=None, is_anonymous=None, can_manage_chat=None, can_manage_video_chats=None, can_manage_topics=None, can_post_stories=None, can_edit_stories=None, can_delete_stories=None, can_manage_direct_messages=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user.

Changed in version 20.0: The argument can_manage_voice_chats was renamed to can_manage_video_chats in accordance to Bot API 6.0.

Parameters:
  • chat_id (str | int) – |chat_id_channel|

  • user_id (int) – Unique identifier of the target user.

  • is_anonymous (bool | None, default: None) – Pass True, if the administrator’s presence in the chat is hidden.

  • can_manage_chat (bool | None, default: None) –

    Pass True, if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages and ignore slow mode. Implied by any other administrator privilege.

    Added in version 13.4.

  • can_manage_video_chats (bool | None, default: None) –

    Pass True, if the administrator can manage video chats.

    Added in version 20.0.

  • can_change_info (bool | None, default: None) – Pass True, if the administrator can change chat title, photo and other settings.

  • can_post_messages (bool | None, default: None) – Pass True, if the administrator can post messages in the channel, or access channel statistics; for channels only.

  • can_edit_messages (bool | None, default: None) – Pass True, if the administrator can edit messages of other users and can pin messages, for channels only.

  • can_delete_messages (bool | None, default: None) – Pass True, if the administrator can delete messages of other users.

  • can_invite_users (bool | None, default: None) – Pass True, if the administrator can invite new users to the chat.

  • can_restrict_members (bool | None, default: None) – Pass True, if the administrator can restrict, ban or unban chat members, or access supergroup statistics.

  • can_pin_messages (bool | None, default: None) – Pass True, if the administrator can pin messages, for supergroups only.

  • can_promote_members (bool | None, default: None) – Pass True, if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by the user).

  • can_manage_topics (bool | None, default: None) –

    Pass True, if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only.

    Added in version 20.0.

  • can_post_stories (bool | None, default: None) –

    Pass True, if the administrator can post stories to the chat.

    Added in version 20.6.

  • can_edit_stories (bool | None, default: None) –

    Pass True, if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat’s story archive

    Added in version 20.6.

  • can_delete_stories (bool | None, default: None) –

    Pass True, if the administrator can delete stories posted by other users.

    Added in version 20.6.

  • can_manage_direct_messages (bool | None, default: None) –

    Pass True, if the administrator can manage direct messages within the channel and decline suggested posts; for channels only

    Added in version 22.4.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async readBusinessMessage(business_connection_id, chat_id, message_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for read_business_message()

Return type:

bool

async read_business_message(business_connection_id, chat_id, message_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Marks incoming message as read on behalf of a business account. Requires the can_read_messages business bot right.

Added in version 22.1.

Parameters:
  • business_connection_id (str) – Unique identifier of the business connection on behalf of which to read the message.

  • chat_id (int) – Unique identifier of the chat in which the message was received. The chat must have been active in the last ~telegram.constants.BusinessLimit.CHAT_ACTIVITY_TIMEOUT seconds.

  • message_id (int) – Unique identifier of the message to mark as read.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async refundStarPayment(user_id, telegram_payment_charge_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for refund_star_payment()

Return type:

bool

async refund_star_payment(user_id, telegram_payment_charge_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Refunds a successful payment in |tg_stars|.

Added in version 21.3.

Parameters:
  • user_id (int) – User identifier of the user whose payment will be refunded.

  • telegram_payment_charge_id (str) – Telegram payment identifier.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async removeBusinessAccountProfilePhoto(business_connection_id, is_public=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for remove_business_account_profile_photo()

Return type:

bool

async removeChatVerification(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for remove_chat_verification()

Return type:

bool

async removeUserVerification(user_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for remove_user_verification()

Return type:

bool

async remove_business_account_profile_photo(business_connection_id, is_public=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Removes the current profile photo of a managed business account. Requires the can_edit_profile_photo business bot right.

Added in version 22.1.

Parameters:
  • business_connection_id (str) – Unique identifier of the business connection.

  • is_public (bool | None, default: None) – Pass True to remove the public photo, which will be visible even if the main photo is hidden by the business account’s privacy settings. After the main photo is removed, the previous profile photo (if present) becomes the main photo.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async remove_chat_verification(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Removes verification from a chat that is currently verified |org-verify| represented by the bot.

Added in version 21.10.

Parameters:

chat_id (int | str) – |chat_id_channel|

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async remove_user_verification(user_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Removes verification from a user who is currently verified |org-verify| represented by the bot.

Added in version 21.10.

Parameters:

user_id (int) – Unique identifier of the target user.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async reopenForumTopic(chat_id, message_thread_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for reopen_forum_topic()

Return type:

bool

async reopenGeneralForumTopic(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for reopen_general_forum_topic()

Return type:

bool

async reopen_forum_topic(chat_id, message_thread_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to reopen a closed topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have ~telegram.ChatAdministratorRights.can_manage_topics administrator rights, unless it is the creator of the topic.

Added in version 20.0.

Parameters:
Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async reopen_general_forum_topic(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to reopen a closed ‘General’ topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have can_manage_topics administrator rights. The topic will be automatically unhidden if it was hidden.

Added in version 20.0.

Parameters:

chat_id (str | int) – |chat_id_group|

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async replaceStickerInSet(user_id, name, old_sticker, sticker, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for replace_sticker_in_set()

Return type:

bool

async replace_sticker_in_set(user_id, name, old_sticker, sticker, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to replace an existing sticker in a sticker set with a new one. The method is equivalent to calling delete_sticker_from_set(), then add_sticker_to_set(), then set_sticker_position_in_set().

Added in version 21.1.

Parameters:
  • user_id (int) – User identifier of the sticker set owner.

  • name (str) – Sticker set name.

  • old_sticker (str | Sticker) –

    File identifier of the replaced sticker or the sticker object itself.

    Changed in version 21.10: Accepts also telegram.Sticker instances.

  • sticker (InputSticker) – An object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set remains unchanged.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

property request: BaseRequest

The BaseRequest object used by this bot.

Warning

Requests to the Bot API are made by the various methods of this class. This attribute should not be used manually.

async restrictChatMember(chat_id, user_id, permissions, until_date=None, use_independent_chat_permissions=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for restrict_chat_member()

Return type:

bool

async restrict_chat_member(chat_id, user_id, permissions, until_date=None, use_independent_chat_permissions=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user.

Parameters:
Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

Alias for revoke_chat_invite_link()

Return type:

ChatInviteLink

Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

Added in version 13.4.

Parameters:
Returns:

ChatInviteLinktelegram.ChatInviteLink

Raises:

telegram.error.TelegramError

async savePreparedInlineMessage(user_id, result, allow_user_chats=None, allow_bot_chats=None, allow_group_chats=None, allow_channel_chats=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for save_prepared_inline_message()

Return type:

PreparedInlineMessage

async save_prepared_inline_message(user_id, result, allow_user_chats=None, allow_bot_chats=None, allow_group_chats=None, allow_channel_chats=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Stores a message that can be sent by a user of a Mini App.

Added in version 21.8.

Parameters:
  • user_id (int) – Unique identifier of the target user that can use the prepared message.

  • result (InlineQueryResult) – The result to store.

  • allow_user_chats (bool | None, default: None) – Pass True if the message can be sent to private chats with users

  • allow_bot_chats (bool | None, default: None) – Pass True if the message can be sent to private chats with bots

  • allow_group_chats (bool | None, default: None) – Pass True if the message can be sent to group and supergroup chats

  • allow_channel_chats (bool | None, default: None) – Pass True if the message can be sent to channels

Returns:

On success, the prepared message is returned.

Returns:

PreparedInlineMessage

Raises:

telegram.error.TelegramError

async sendAnimation(chat_id, animation, duration=None, width=None, height=None, caption=None, parse_mode=None, disable_notification=None, reply_markup=None, caption_entities=None, protect_content=None, message_thread_id=None, has_spoiler=None, thumbnail=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, show_caption_above_media=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, filename=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_animation()

Return type:

Message

async sendAudio(chat_id, audio, duration=None, performer=None, title=None, caption=None, disable_notification=None, reply_markup=None, parse_mode=None, caption_entities=None, protect_content=None, message_thread_id=None, thumbnail=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, filename=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_audio()

Return type:

Message

async sendChatAction(chat_id, action, message_thread_id=None, business_connection_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_chat_action()

Return type:

bool

async sendChecklist(business_connection_id, chat_id, checklist, disable_notification=None, protect_content=None, message_effect_id=None, reply_parameters=None, reply_markup=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_checklist()

Return type:

Message

async sendContact(chat_id, phone_number=None, first_name=None, last_name=None, disable_notification=None, reply_markup=None, vcard=None, protect_content=None, message_thread_id=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, contact=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_contact()

Return type:

Message

async sendDice(chat_id, disable_notification=None, reply_markup=None, emoji=None, protect_content=None, message_thread_id=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_dice()

Return type:

Message

async sendDocument(chat_id, document, caption=None, disable_notification=None, reply_markup=None, parse_mode=None, disable_content_type_detection=None, caption_entities=None, protect_content=None, message_thread_id=None, thumbnail=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, filename=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_document()

Return type:

Message

async sendGame(chat_id, game_short_name, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_game()

Return type:

Message

async sendGift(gift_id, text=None, text_parse_mode=None, text_entities=None, pay_for_upgrade=None, chat_id=None, user_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_gift()

Return type:

bool

async sendInvoice(chat_id, title, description, payload, currency, prices, provider_token=None, start_parameter=None, photo_url=None, photo_size=None, photo_width=None, photo_height=None, need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, is_flexible=None, disable_notification=None, reply_markup=None, provider_data=None, send_phone_number_to_provider=None, send_email_to_provider=None, max_tip_amount=None, suggested_tip_amounts=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_invoice()

Return type:

Message

async sendLocation(chat_id, latitude=None, longitude=None, disable_notification=None, reply_markup=None, live_period=None, horizontal_accuracy=None, heading=None, proximity_alert_radius=None, protect_content=None, message_thread_id=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, location=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_location()

Return type:

Message

async sendMediaGroup(chat_id, media, disable_notification=None, protect_content=None, message_thread_id=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None, caption=None, parse_mode=None, caption_entities=None)

Alias for send_media_group()

Return type:

tuple[Message, ...]

async sendMessage(chat_id, text, parse_mode=None, entities=None, disable_notification=None, protect_content=None, reply_markup=None, message_thread_id=None, link_preview_options=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, disable_web_page_preview=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_message()

Return type:

Message

async sendPaidMedia(chat_id, star_count, media, caption=None, parse_mode=None, caption_entities=None, show_caption_above_media=None, disable_notification=None, protect_content=None, reply_parameters=None, reply_markup=None, business_connection_id=None, payload=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, message_thread_id=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_paid_media()

Return type:

Message

async sendPhoto(chat_id, photo, caption=None, disable_notification=None, reply_markup=None, parse_mode=None, caption_entities=None, protect_content=None, message_thread_id=None, has_spoiler=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, show_caption_above_media=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, filename=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_photo()

Return type:

Message

async sendPoll(chat_id, question, options, is_anonymous=None, type=None, allows_multiple_answers=None, correct_option_id=None, is_closed=None, disable_notification=None, reply_markup=None, explanation=None, explanation_parse_mode=None, open_period=None, close_date=None, explanation_entities=None, protect_content=None, message_thread_id=None, reply_parameters=None, business_connection_id=None, question_parse_mode=None, question_entities=None, message_effect_id=None, allow_paid_broadcast=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_poll()

Return type:

Message

async sendSticker(chat_id, sticker, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, emoji=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_sticker()

Return type:

Message

async sendVenue(chat_id, latitude=None, longitude=None, title=None, address=None, foursquare_id=None, disable_notification=None, reply_markup=None, foursquare_type=None, google_place_id=None, google_place_type=None, protect_content=None, message_thread_id=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, venue=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_venue()

Return type:

Message

async sendVideo(chat_id, video, duration=None, caption=None, disable_notification=None, reply_markup=None, width=None, height=None, parse_mode=None, supports_streaming=None, caption_entities=None, protect_content=None, message_thread_id=None, has_spoiler=None, thumbnail=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, show_caption_above_media=None, cover=None, start_timestamp=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, filename=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_video()

Return type:

Message

async sendVideoNote(chat_id, video_note, duration=None, length=None, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, thumbnail=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, filename=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_video_note()

Return type:

Message

async sendVoice(chat_id, voice, duration=None, caption=None, disable_notification=None, reply_markup=None, parse_mode=None, caption_entities=None, protect_content=None, message_thread_id=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, filename=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for send_voice()

Return type:

Message

async send_animation(chat_id, animation, duration=None, width=None, height=None, caption=None, parse_mode=None, disable_notification=None, reply_markup=None, caption_entities=None, protect_content=None, message_thread_id=None, has_spoiler=None, thumbnail=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, show_caption_above_media=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, filename=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). Bots can currently send animation files of up to telegram.constants.FileSizeLimit.FILESIZE_UPLOAD in size, this limit may be changed in the future.

Note

thumbnail will be ignored for small files, for which Telegram can easily generate thumbnails. However, this behaviour is undocumented and might be changed by Telegram.

See also

Working with Files and Media <Working-with-Files-and-Media>

Changed in version 20.5: Removed deprecated argument thumb. Use thumbnail instead.

Parameters:
Keyword Arguments:
  • allow_sending_without_reply (bool, optional) –

    |allow_sending_without_reply| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • reply_to_message_id (int, optional) –

    |reply_to_msg_id| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • filename (str, optional) –

    Custom file name for the animation, when uploading a new file. Convenience parameter, useful e.g. when sending files generated by the tempfile module.

    Added in version 13.1.

Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async send_audio(chat_id, audio, duration=None, performer=None, title=None, caption=None, disable_notification=None, reply_markup=None, parse_mode=None, caption_entities=None, protect_content=None, message_thread_id=None, thumbnail=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, filename=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 or .m4a format.

Bots can currently send audio files of up to telegram.constants.FileSizeLimit.FILESIZE_UPLOAD in size, this limit may be changed in the future.

For sending voice messages, use the send_voice() method instead.

See also

Working with Files and Media <Working-with-Files-and-Media>

Changed in version 20.5: Removed deprecated argument thumb. Use thumbnail instead.

Parameters:
Keyword Arguments:
  • allow_sending_without_reply (bool, optional) –

    |allow_sending_without_reply| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • reply_to_message_id (int, optional) –

    |reply_to_msg_id| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • filename (str, optional) –

    Custom file name for the audio, when uploading a new file. Convenience parameter, useful e.g. when sending files generated by the tempfile module.

    Added in version 13.1.

Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async send_chat_action(chat_id, action, message_thread_id=None, business_connection_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method when you need to tell the user that something is happening on the bot’s side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Telegram only recommends using this method when a response from the bot will take a noticeable amount of time to arrive.

Parameters:
Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async send_checklist(business_connection_id, chat_id, checklist, disable_notification=None, protect_content=None, message_effect_id=None, reply_parameters=None, reply_markup=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send a checklist on behalf of a connected business account.

Added in version 22.3.

Parameters:
Keyword Arguments:
  • allow_sending_without_reply (bool, optional) – |allow_sending_without_reply| Mutually exclusive with reply_parameters, which this is a convenience parameter for

  • reply_to_message_id (int, optional) – |reply_to_msg_id| Mutually exclusive with reply_parameters, which this is a convenience parameter for

Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async send_contact(chat_id, phone_number=None, first_name=None, last_name=None, disable_notification=None, reply_markup=None, vcard=None, protect_content=None, message_thread_id=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, contact=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send phone contacts.

Note

You can either supply contact or phone_number and first_name with optionally last_name and optionally vcard.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • phone_number (str | None, default: None) – Contact’s phone number.

  • first_name (str | None, default: None) – Contact’s first name.

  • last_name (str | None, default: None) – Contact’s last name.

  • vcard (str | None, default: None) – Additional data about the contact in the form of a vCard, 0-telegram.constants.ContactLimit.VCARD bytes.

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) –

    |protect_content|

    Added in version 13.10.

  • message_thread_id (int | None, default: None) –

    |message_thread_id_arg|

    Added in version 20.0.

  • reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply | None, default: None) – Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • reply_parameters (ReplyParameters | None, default: None) –

    |reply_parameters|

    Added in version 20.8.

  • business_connection_id (str | None, default: None) –

    |business_id_str|

    Added in version 21.1.

  • message_effect_id (str | None, default: None) –

    |message_effect_id|

    Added in version 21.3.

  • allow_paid_broadcast (bool | None, default: None) –

    |allow_paid_broadcast|

    Added in version 21.7.

  • suggested_post_parameters (SuggestedPostParameters | None, default: None) –

    |suggested_post_parameters|

    Added in version 22.4.

  • direct_messages_topic_id (int | None, default: None) –

    |direct_messages_topic_id|

    Added in version 22.4.

Keyword Arguments:
Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async send_dice(chat_id, disable_notification=None, reply_markup=None, emoji=None, protect_content=None, message_thread_id=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send an animated emoji that will display a random value.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply | None, default: None) – Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user

  • emoji (str | None, default: None) –

    Emoji on which the dice throw animation is based. Currently, must be one of telegram.constants.DiceEmoji. Dice can have values telegram.Dice.MIN_VALUE-telegram.Dice.MAX_VALUE_BOWLING for telegram.Dice.DICE, telegram.Dice.DARTS and telegram.Dice.BOWLING, values telegram.Dice.MIN_VALUE-telegram.Dice.MAX_VALUE_BASKETBALL for telegram.Dice.BASKETBALL and telegram.Dice.FOOTBALL, and values telegram.Dice.MIN_VALUE- telegram.Dice.MAX_VALUE_SLOT_MACHINE for telegram.Dice.SLOT_MACHINE. Defaults to telegram.Dice.DICE.

    Changed in version 13.4: Added the telegram.Dice.BOWLING emoji.

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) –

    |protect_content|

    Added in version 13.10.

  • message_thread_id (int | None, default: None) –

    |message_thread_id_arg|

    Added in version 20.0.

  • reply_parameters (ReplyParameters | None, default: None) –

    |reply_parameters|

    Added in version 20.8.

  • business_connection_id (str | None, default: None) –

    |business_id_str|

    Added in version 21.1.

  • message_effect_id (str | None, default: None) –

    |message_effect_id|

    Added in version 21.3.

  • allow_paid_broadcast (bool | None, default: None) –

    |allow_paid_broadcast|

    Added in version 21.7.

  • suggested_post_parameters (SuggestedPostParameters | None, default: None) –

    |suggested_post_parameters|

    Added in version 22.4.

  • direct_messages_topic_id (int | None, default: None) –

    |direct_messages_topic_id|

    Added in version 22.4.

Keyword Arguments:
Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async send_document(chat_id, document, caption=None, disable_notification=None, reply_markup=None, parse_mode=None, disable_content_type_detection=None, caption_entities=None, protect_content=None, message_thread_id=None, thumbnail=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, filename=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send general files.

Bots can currently send files of any type of up to telegram.constants.FileSizeLimit.FILESIZE_UPLOAD in size, this limit may be changed in the future.

See also

Working with Files and Media <Working-with-Files-and-Media>

Changed in version 20.5: Removed deprecated argument thumb. Use thumbnail instead.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • document (str | Path | IO[bytes] | InputFile | bytes | Document) –

    File to send. |fileinput| Lastly you can pass an existing telegram.Document object to send.

    Note

    Sending by URL will currently only work GIF, PDF & ZIP files.

    Changed in version 13.2: Accept bytes as input.

    Changed in version 20.0: File paths as input is also accepted for bots not running in ~telegram.Bot.local_mode.

  • caption (str | None, default: None) – Document caption (may also be used when resending documents by file_id), 0-telegram.constants.MessageLimit.CAPTION_LENGTH characters after entities parsing.

  • disable_content_type_detection (bool | None, default: None) – Disables automatic server-side content type detection for files uploaded using multipart/form-data.

  • parse_mode (DefaultValue[DVValueType] | str | DefaultValue[None] | None, default: None) – |parse_mode|

  • caption_entities (Sequence[MessageEntity] | None, default: None) –

    |caption_entities|

    Changed in version 20.0: |sequenceargs|

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) –

    |protect_content|

    Added in version 13.10.

  • message_thread_id (int | None, default: None) –

    |message_thread_id_arg|

    Added in version 20.0.

  • reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply | None, default: None) – Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • thumbnail (str | Path | IO[bytes] | InputFile | bytes | None, default: None) –

    |thumbdocstring|

    Added in version 20.2.

  • reply_parameters (ReplyParameters | None, default: None) –

    |reply_parameters|

    Added in version 20.8.

  • business_connection_id (str | None, default: None) –

    |business_id_str|

    Added in version 21.1.

  • message_effect_id (str | None, default: None) –

    |message_effect_id|

    Added in version 21.3.

  • allow_paid_broadcast (bool | None, default: None) –

    |allow_paid_broadcast|

    Added in version 21.7.

  • suggested_post_parameters (SuggestedPostParameters | None, default: None) –

    |suggested_post_parameters|

    Added in version 22.4.

  • direct_messages_topic_id (int | None, default: None) –

    |direct_messages_topic_id|

    Added in version 22.4.

Keyword Arguments:
  • allow_sending_without_reply (bool, optional) –

    |allow_sending_without_reply| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • reply_to_message_id (int, optional) –

    |reply_to_msg_id| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • filename (str, optional) – Custom file name for the document, when uploading a new file. Convenience parameter, useful e.g. when sending files generated by the tempfile module.

Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async send_game(chat_id, game_short_name, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send a game.

Parameters:
  • chat_id (int) – Unique identifier for the target chat.

  • game_short_name (str) –

    Short name of the game, serves as the unique identifier for the game. Set up your games via @BotFather.

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) –

    |protect_content|

    Added in version 13.10.

  • message_thread_id (int | None, default: None) –

    |message_thread_id_arg|

    Added in version 20.0.

  • reply_markup (InlineKeyboardMarkup | None, default: None) – An object for a new inline keyboard. If empty, one “Play game_title” button will be shown. If not empty, the first button must launch the game.

  • reply_parameters (ReplyParameters | None, default: None) –

    |reply_parameters|

    Added in version 20.8.

  • business_connection_id (str | None, default: None) –

    |business_id_str|

    Added in version 21.1.

  • message_effect_id (str | None, default: None) –

    |message_effect_id|

    Added in version 21.3.

  • allow_paid_broadcast (bool | None, default: None) –

    |allow_paid_broadcast|

    Added in version 21.7.

Keyword Arguments:
Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async send_gift(gift_id, text=None, text_parse_mode=None, text_entities=None, pay_for_upgrade=None, chat_id=None, user_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Sends a gift to the given user or channel chat. The gift can’t be converted to Telegram Stars by the receiver.

Added in version 21.8.

Changed in version 22.1: Bot API 8.3 made user_id optional. In version 22.1, the methods signature was changed accordingly.

Parameters:
  • gift_id (str | Gift) – Identifier of the gift or a Gift object

  • user_id (int | None, default: None) –

    Required if chat_id is not specified. Unique identifier of the target user that will receive the gift.

    Changed in version 21.11: Now optional.

  • chat_id (int | str | None, default: None) –

    Required if user_id is not specified. |chat_id_channel| It will receive the gift.

    Added in version 21.11.

  • text (str | None, default: None) – Text that will be shown along with the gift; 0- telegram.constants.GiftLimit.MAX_TEXT_LENGTH characters

  • text_parse_mode (DefaultValue[DVValueType] | str | DefaultValue[None] | None, default: None) – Mode for parsing entities. See telegram.constants.ParseMode and formatting options for more details. Entities other than BOLD, ITALIC, UNDERLINE, STRIKETHROUGH, SPOILER, and CUSTOM_EMOJI are ignored.

  • text_entities (Sequence[MessageEntity] | None, default: None) – A list of special entities that appear in the gift text. It can be specified instead of text_parse_mode. Entities other than BOLD, ITALIC, UNDERLINE, STRIKETHROUGH, SPOILER, and CUSTOM_EMOJI are ignored.

  • pay_for_upgrade (bool | None, default: None) –

    Pass True to pay for the gift upgrade from the bot’s balance, thereby making the upgrade free for the receiver.

    Added in version 21.10.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async send_invoice(chat_id, title, description, payload, currency, prices, provider_token=None, start_parameter=None, photo_url=None, photo_size=None, photo_width=None, photo_height=None, need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, is_flexible=None, disable_notification=None, reply_markup=None, provider_data=None, send_phone_number_to_provider=None, send_email_to_provider=None, max_tip_amount=None, suggested_tip_amounts=None, protect_content=None, message_thread_id=None, reply_parameters=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send invoices.

Warning

As of API 5.2 start_parameter is an optional argument and therefore the order of the arguments had to be changed. Use keyword arguments to make sure that the arguments are passed correctly.

Changed in version 13.5: As of Bot API 5.2, the parameter start_parameter is optional.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • title (str) – Product name. telegram.Invoice.MIN_TITLE_LENGTH- telegram.Invoice.MAX_TITLE_LENGTH characters.

  • description (str) – Product description. telegram.Invoice.MIN_DESCRIPTION_LENGTH- telegram.Invoice.MAX_DESCRIPTION_LENGTH characters.

  • payload (str) – Bot-defined invoice payload. telegram.Invoice.MIN_PAYLOAD_LENGTH- telegram.Invoice.MAX_PAYLOAD_LENGTH bytes. This will not be displayed to the user, use it for your internal processes.

  • provider_token (str | None, default: None) –

    Payments provider token, obtained via @BotFather. Pass an empty string for payments in |tg_stars|.

    Changed in version 21.11: Bot API 7.4 made this parameter is optional and this is now reflected in the function signature.

  • currency (str) –

    Three-letter ISO 4217 currency code, see more on currencies. Pass XTR for payment in |tg_stars|.

  • prices (Sequence[LabeledPrice]) –

    Price breakdown, a sequence of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payment in |tg_stars|.

    Changed in version 20.0: |sequenceargs|

  • max_tip_amount (int | None, default: None) –

    The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payment in |tg_stars|.

    Added in version 13.5.

  • suggested_tip_amounts (Sequence[int] | None, default: None) –

    An array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most telegram.Invoice.MAX_TIP_AMOUNTS suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount.

    Added in version 13.5.

    Changed in version 20.0: |sequenceargs|

  • start_parameter (str | None, default: None) –

    Unique deep-linking parameter. If left empty, forwarded copies of the sent message will have a Pay button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a URL button with a deep link to the bot (instead of a Pay button), with the value used as the start parameter.

    Changed in version 13.5: As of Bot API 5.2, this parameter is optional.

  • provider_data (str | object | None, default: None) – data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. When an object is passed, it will be encoded as JSON.

  • photo_url (str | None, default: None) – URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for.

  • photo_size (int | None, default: None) – Photo size.

  • photo_width (int | None, default: None) – Photo width.

  • photo_height (int | None, default: None) – Photo height.

  • need_name (bool | None, default: None) – Pass True, if you require the user’s full name to complete the order. Ignored for payments in |tg_stars|.

  • need_phone_number (bool | None, default: None) – Pass True, if you require the user’s phone number to complete the order. Ignored for payments in |tg_stars|.

  • need_email (bool | None, default: None) – Pass True, if you require the user’s email to complete the order. Ignored for payments in |tg_stars|.

  • need_shipping_address (bool | None, default: None) – Pass True, if you require the user’s shipping address to complete the order. Ignored for payments in |tg_stars|.

  • send_phone_number_to_provider (bool | None, default: None) – Pass True, if user’s phone number should be sent to provider. Ignored for payments in |tg_stars|.

  • send_email_to_provider (bool | None, default: None) – Pass True, if user’s email address should be sent to provider. Ignored for payments in |tg_stars|.

  • is_flexible (bool | None, default: None) – Pass True, if the final price depends on the shipping method. Ignored for payments in |tg_stars|.

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) –

    |protect_content|

    Added in version 13.10.

  • message_thread_id (int | None, default: None) –

    |message_thread_id_arg|

    Added in version 20.0.

  • reply_markup (InlineKeyboardMarkup | None, default: None) – An object for an inline keyboard. If empty, one ‘Pay total price’ button will be shown. If not empty, the first button must be a Pay button.

  • reply_parameters (ReplyParameters | None, default: None) –

    |reply_parameters|

    Added in version 20.8.

  • message_effect_id (str | None, default: None) –

    |message_effect_id|

    Added in version 21.3.

  • allow_paid_broadcast (bool | None, default: None) –

    |allow_paid_broadcast|

    Added in version 21.7.

  • suggested_post_parameters (SuggestedPostParameters | None, default: None) –

    |suggested_post_parameters|

    Added in version 22.4.

  • direct_messages_topic_id (int | None, default: None) –

    |direct_messages_topic_id|

    Added in version 22.4.

Keyword Arguments:
Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async send_location(chat_id, latitude=None, longitude=None, disable_notification=None, reply_markup=None, live_period=None, horizontal_accuracy=None, heading=None, proximity_alert_radius=None, protect_content=None, message_thread_id=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, location=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send point on the map.

Note

You can either supply a latitude and longitude or a location.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • latitude (float | None, default: None) – Latitude of location.

  • longitude (float | None, default: None) – Longitude of location.

  • horizontal_accuracy (float | None, default: None) – The radius of uncertainty for the location, measured in meters; 0-telegram.constants.LocationLimit.HORIZONTAL_ACCURACY.

  • live_period (int | timedelta | None, default: None) –

    Period in seconds for which the location will be updated, should be between telegram.constants.LocationLimit.MIN_LIVE_PERIOD and telegram.constants.LocationLimit.MAX_LIVE_PERIOD, or telegram.constants.LocationLimit.LIVE_PERIOD_FOREVER for live locations that can be edited indefinitely.

    Changed in version 21.11: |time-period-input|

  • heading (int | None, default: None) – For live locations, a direction in which the user is moving, in degrees. Must be between telegram.constants.LocationLimit.MIN_HEADING and telegram.constants.LocationLimit.MAX_HEADING if specified.

  • proximity_alert_radius (int | None, default: None) – For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between telegram.constants.LocationLimit.MIN_PROXIMITY_ALERT_RADIUS and telegram.constants.LocationLimit.MAX_PROXIMITY_ALERT_RADIUS if specified.

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) –

    |protect_content|

    Added in version 13.10.

  • message_thread_id (int | None, default: None) –

    |message_thread_id_arg|

    Added in version 20.0.

  • reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply | None, default: None) – Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • reply_parameters (ReplyParameters | None, default: None) –

    |reply_parameters|

    Added in version 20.8.

  • business_connection_id (str | None, default: None) –

    |business_id_str|

    Added in version 21.1.

  • message_effect_id (str | None, default: None) –

    |message_effect_id|

    Added in version 21.3.

  • allow_paid_broadcast (bool | None, default: None) –

    |allow_paid_broadcast|

    Added in version 21.7.

  • suggested_post_parameters (SuggestedPostParameters | None, default: None) –

    |suggested_post_parameters|

    Added in version 22.4.

  • direct_messages_topic_id (int | None, default: None) –

    |direct_messages_topic_id|

    Added in version 22.4.

Keyword Arguments:
Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async send_media_group(chat_id, media, disable_notification=None, protect_content=None, message_thread_id=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None, caption=None, parse_mode=None, caption_entities=None)[source]

Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type.

Note

If you supply a caption (along with either parse_mode or caption_entities), then items in media must have no captions, and vice versa.

See also

Working with Files and Media <Working-with-Files-and-Media>

Changed in version 20.0: Returns a tuple instead of a list.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • media (Sequence[InputMediaAudio | InputMediaDocument | InputMediaPhoto | InputMediaVideo]) –

    An array describing messages to be sent, must include telegram.constants.MediaGroupLimit.MIN_MEDIA_LENGTH- telegram.constants.MediaGroupLimit.MAX_MEDIA_LENGTH items.

    Changed in version 20.0: |sequenceargs|

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) –

    |protect_content|

    Added in version 13.10.

  • message_thread_id (int | None, default: None) –

    |message_thread_id_arg|

    Added in version 20.0.

  • reply_parameters (ReplyParameters | None, default: None) –

    |reply_parameters|

    Added in version 20.8.

  • business_connection_id (str | None, default: None) –

    |business_id_str|

    Added in version 21.1.

  • message_effect_id (str | None, default: None) –

    |message_effect_id|

    Added in version 21.3.

  • allow_paid_broadcast (bool | None, default: None) –

    |allow_paid_broadcast|

    Added in version 21.7.

  • direct_messages_topic_id (int | None, default: None) –

    Identifier of the direct messages topic to which the messages will be sent; required if the messages are sent to a direct messages chat.

    Added in version 22.4.

Keyword Arguments:
  • allow_sending_without_reply (bool, optional) –

    |allow_sending_without_reply| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • reply_to_message_id (int, optional) –

    |reply_to_msg_id| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • caption (str, optional) –

    Caption that will be added to the first element of media, so that it will be used as caption for the whole media group. Defaults to None.

    Added in version 20.0.

  • parse_mode (str | None, optional) –

    Parse mode for caption. See the constants in telegram.constants.ParseMode for the available modes.

    Added in version 20.0.

  • caption_entities (Sequence[telegram.MessageEntity], optional) –

    List of special entities for caption, which can be specified instead of parse_mode. Defaults to None.

    Added in version 20.0.

Returns:

An array of the sent Messages.

Returns:

tuple[Message, ...]

Raises:

telegram.error.TelegramError

async send_message(chat_id, text, parse_mode=None, entities=None, disable_notification=None, protect_content=None, reply_markup=None, message_thread_id=None, link_preview_options=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, disable_web_page_preview=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send text messages.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • text (str) – Text of the message to be sent. Max telegram.constants.MessageLimit.MAX_TEXT_LENGTH characters after entities parsing.

  • parse_mode (DefaultValue[DVValueType] | str | DefaultValue[None] | None, default: None) – |parse_mode|

  • entities (Sequence[MessageEntity] | None, default: None) –

    Sequence of special entities that appear in message text, which can be specified instead of parse_mode.

    Changed in version 20.0: |sequenceargs|

  • link_preview_options (DefaultValue[DVValueType] | LinkPreviewOptions | DefaultValue[None] | None, default: None) –

    Link preview generation options for the message. Mutually exclusive with disable_web_page_preview.

    Added in version 20.8.

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) –

    |protect_content|

    Added in version 13.10.

  • reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply | None, default: None) – Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • message_thread_id (int | None, default: None) –

    |message_thread_id_arg|

    Added in version 20.0.

  • reply_parameters (ReplyParameters | None, default: None) –

    |reply_parameters|

    Added in version 20.8.

  • business_connection_id (str | None, default: None) –

    |business_id_str|

    Added in version 21.1.

  • message_effect_id (str | None, default: None) –

    |message_effect_id|

    Added in version 21.3.

  • allow_paid_broadcast (bool | None, default: None) –

    |allow_paid_broadcast|

    Added in version 21.7.

  • suggested_post_parameters (SuggestedPostParameters | None, default: None) –

    |suggested_post_parameters|

    Added in version 22.4.

  • direct_messages_topic_id (int | None, default: None) –

    |direct_messages_topic_id|

    Added in version 22.4.

Keyword Arguments:
  • allow_sending_without_reply (bool, optional) –

    |allow_sending_without_reply| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • reply_to_message_id (int, optional) –

    |reply_to_msg_id| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • disable_web_page_preview (bool, optional) –

    Disables link previews for links in this message. Convenience parameter for setting link_preview_options. Mutually exclusive with link_preview_options.

    Changed in version 20.8: Bot API 7.0 introduced link_preview_options replacing this argument. PTB will automatically convert this argument to that one, but for advanced options, please use link_preview_options directly.

    Changed in version 21.0: |keyword_only_arg|

Returns:

On success, the sent message is returned.

Returns:

Message

Raises:
async send_paid_media(chat_id, star_count, media, caption=None, parse_mode=None, caption_entities=None, show_caption_above_media=None, disable_notification=None, protect_content=None, reply_parameters=None, reply_markup=None, business_connection_id=None, payload=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, message_thread_id=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send paid media.

Added in version 21.4.

Parameters:
  • chat_id (str | int) – |chat_id_channel| If the chat is a channel, all Telegram Star proceeds from this media will be credited to the chat’s balance. Otherwise, they will be credited to the bot’s balance.

  • star_count (int) – The number of Telegram Stars that must be paid to buy access to the media; telegram.constants.InvoiceLimit.MIN_STAR_COUNT - telegram.constants.InvoiceLimit.MAX_STAR_COUNT.

  • media (Sequence[InputPaidMedia]) – A list describing the media to be sent; up to telegram.constants.MediaGroupLimit.MAX_MEDIA_LENGTH items.

  • payload (str | None, default: None) –

    Bot-defined paid media payload, 0-telegram.constants.InvoiceLimit.MAX_PAYLOAD_LENGTH bytes. This will not be displayed to the user, use it for your internal processes.

    Added in version 21.6.

  • caption (str | None, default: None) – Caption of the media to be sent, 0-telegram.constants.MessageLimit.CAPTION_LENGTH characters.

  • parse_mode (DefaultValue[DVValueType] | str | DefaultValue[None] | None, default: None) – |parse_mode|

  • caption_entities (Sequence[MessageEntity] | None, default: None) – |caption_entities|

  • show_caption_above_media (bool | None, default: None) – Pass |show_cap_above_med|

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |protect_content|

  • reply_parameters (ReplyParameters | None, default: None) – |reply_parameters|

  • reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply | None, default: None) – Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • business_connection_id (str | None, default: None) –

    |business_id_str|

    Added in version 21.5.

  • allow_paid_broadcast (bool | None, default: None) –

    |allow_paid_broadcast|

    Added in version 21.7.

  • suggested_post_parameters (SuggestedPostParameters | None, default: None) –

    |suggested_post_parameters|

    Added in version 22.4.

  • direct_messages_topic_id (int | None, default: None) –

    |direct_messages_topic_id|

    Added in version 22.4.

  • message_thread_id (int | None, default: None) –

    |message_thread_id_arg|

    Added in version 22.4.

Keyword Arguments:
  • allow_sending_without_reply (bool, optional) – |allow_sending_without_reply| Mutually exclusive with reply_parameters, which this is a convenience parameter for

  • reply_to_message_id (int, optional) – |reply_to_msg_id| Mutually exclusive with reply_parameters, which this is a convenience parameter for

Returns:

On success, the sent message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async send_photo(chat_id, photo, caption=None, disable_notification=None, reply_markup=None, parse_mode=None, caption_entities=None, protect_content=None, message_thread_id=None, has_spoiler=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, show_caption_above_media=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, filename=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send photos.

See also

Working with Files and Media <Working-with-Files-and-Media>

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • photo (str | Path | IO[bytes] | InputFile | bytes | PhotoSize) –

    Photo to send. |fileinput| Lastly you can pass an existing telegram.PhotoSize object to send.

    Caution

    • The photo must be at most 10MB in size.

    • The photo’s width and height must not exceed 10000 in total.

    • Width and height ratio must be at most 20.

    Changed in version 13.2: Accept bytes as input.

    Changed in version 20.0: File paths as input is also accepted for bots not running in ~telegram.Bot.local_mode.

  • caption (str | None, default: None) – Photo caption (may also be used when resending photos by file_id), 0-telegram.constants.MessageLimit.CAPTION_LENGTH characters after entities parsing.

  • parse_mode (DefaultValue[DVValueType] | str | DefaultValue[None] | None, default: None) – |parse_mode|

  • caption_entities (Sequence[MessageEntity] | None, default: None) –

    |caption_entities|

    Changed in version 20.0: |sequenceargs|

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) –

    |protect_content|

    Added in version 13.10.

  • message_thread_id (int | None, default: None) –

    |message_thread_id_arg|

    Added in version 20.0.

  • reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply | None, default: None) – Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • has_spoiler (bool | None, default: None) –

    Pass True if the photo needs to be covered with a spoiler animation.

    Added in version 20.0.

  • reply_parameters (ReplyParameters | None, default: None) –

    |reply_parameters|

    Added in version 20.8.

  • business_connection_id (str | None, default: None) –

    |business_id_str|

    Added in version 21.1.

  • message_effect_id (str | None, default: None) –

    |message_effect_id|

    Added in version 21.3.

  • allow_paid_broadcast (bool | None, default: None) –

    |allow_paid_broadcast|

    Added in version 21.7.

  • show_caption_above_media (bool | None, default: None) –

    Pass |show_cap_above_med|

    Added in version 21.3.

  • suggested_post_parameters (SuggestedPostParameters | None, default: None) –

    |suggested_post_parameters|

    Added in version 22.4.

  • direct_messages_topic_id (int | None, default: None) –

    |direct_messages_topic_id|

    Added in version 22.4.

Keyword Arguments:
  • allow_sending_without_reply (bool, optional) –

    |allow_sending_without_reply| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • reply_to_message_id (int, optional) –

    |reply_to_msg_id| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • filename (str, optional) –

    Custom file name for the photo, when uploading a new file. Convenience parameter, useful e.g. when sending files generated by the tempfile module.

    Added in version 13.1.

Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async send_poll(chat_id, question, options, is_anonymous=None, type=None, allows_multiple_answers=None, correct_option_id=None, is_closed=None, disable_notification=None, reply_markup=None, explanation=None, explanation_parse_mode=None, open_period=None, close_date=None, explanation_entities=None, protect_content=None, message_thread_id=None, reply_parameters=None, business_connection_id=None, question_parse_mode=None, question_entities=None, message_effect_id=None, allow_paid_broadcast=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send a native poll.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • question (str) – Poll question, telegram.Poll.MIN_QUESTION_LENGTH- telegram.Poll.MAX_QUESTION_LENGTH characters.

  • options (Sequence[str | InputPollOption]) –

    Sequence of telegram.Poll.MIN_OPTION_NUMBER- telegram.Poll.MAX_OPTION_NUMBER answer options. Each option may either be a string with telegram.Poll.MIN_OPTION_LENGTH- telegram.Poll.MAX_OPTION_LENGTH characters or an InputPollOption object. Strings are converted to InputPollOption objects automatically.

    Changed in version 20.0: |sequenceargs|

    Changed in version 21.2: Bot API 7.3 adds support for InputPollOption objects.

  • is_anonymous (bool | None, default: None) – True, if the poll needs to be anonymous, defaults to True.

  • type (str | None, default: None) – Poll type, telegram.Poll.QUIZ or telegram.Poll.REGULAR, defaults to telegram.Poll.REGULAR.

  • allows_multiple_answers (bool | None, default: None) – True, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to False.

  • correct_option_id (Literal[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | None, default: None) – 0-based identifier of the correct answer option, required for polls in quiz mode.

  • explanation (str | None, default: None) – Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-telegram.Poll.MAX_EXPLANATION_LENGTH characters with at most telegram.Poll.MAX_EXPLANATION_LINE_FEEDS line feeds after entities parsing.

  • explanation_parse_mode (DefaultValue[DVValueType] | str | DefaultValue[None] | None, default: None) – Mode for parsing entities in the explanation. See the constants in telegram.constants.ParseMode for the available modes.

  • explanation_entities (Sequence[MessageEntity] | None, default: None) –

    Sequence of special entities that appear in message text, which can be specified instead of explanation_parse_mode.

    Changed in version 20.0: |sequenceargs|

  • open_period (int | timedelta | None, default: None) –

    Amount of time in seconds the poll will be active after creation, telegram.Poll.MIN_OPEN_PERIOD- telegram.Poll.MAX_OPEN_PERIOD. Can’t be used together with close_date.

    Changed in version 21.11: |time-period-input|

  • close_date (int | datetime | None, default: None) – Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least telegram.Poll.MIN_OPEN_PERIOD and no more than telegram.Poll.MAX_OPEN_PERIOD seconds in the future. Can’t be used together with open_period. |tz-naive-dtms|

  • is_closed (bool | None, default: None) – Pass True, if the poll needs to be immediately closed. This can be useful for poll preview.

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) –

    |protect_content|

    Added in version 13.10.

  • message_thread_id (int | None, default: None) –

    |message_thread_id_arg|

    Added in version 20.0.

  • reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply | None, default: None) – Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • reply_parameters (ReplyParameters | None, default: None) –

    |reply_parameters|

    Added in version 20.8.

  • business_connection_id (str | None, default: None) –

    |business_id_str|

    Added in version 21.1.

  • question_parse_mode (DefaultValue[DVValueType] | str | DefaultValue[None] | None, default: None) –

    Mode for parsing entities in the question. See the constants in telegram.constants.ParseMode for the available modes. Currently, only custom emoji entities are allowed.

    Added in version 21.2.

  • question_entities (Sequence[MessageEntity] | None, default: None) –

    Special entities that appear in the poll question. It can be specified instead of question_parse_mode.

    Added in version 21.2.

  • message_effect_id (str | None, default: None) –

    |message_effect_id|

    Added in version 21.3.

  • allow_paid_broadcast (bool | None, default: None) –

    |allow_paid_broadcast|

    Added in version 21.7.

Keyword Arguments:
Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async send_sticker(chat_id, sticker, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, emoji=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers.

See also

Working with Files and Media <Working-with-Files-and-Media>

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • sticker (str | Path | IO[bytes] | InputFile | bytes | Sticker) –

    Sticker to send. |fileinput| Video stickers can only be sent by a file_id. Video and animated stickers can’t be sent via an HTTP URL.

    Lastly you can pass an existing telegram.Sticker object to send.

    Changed in version 13.2: Accept bytes as input.

    Changed in version 20.0: File paths as input is also accepted for bots not running in ~telegram.Bot.local_mode.

  • emoji (str | None, default: None) –

    Emoji associated with the sticker; only for just uploaded stickers

    Added in version 20.2.

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) –

    |protect_content|

    Added in version 13.10.

  • message_thread_id (int | None, default: None) –

    |message_thread_id_arg|

    Added in version 20.0.

  • reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply | None, default: None) – Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • reply_parameters (ReplyParameters | None, default: None) –

    |reply_parameters|

    Added in version 20.8.

  • business_connection_id (str | None, default: None) –

    |business_id_str|

    Added in version 21.1.

  • message_effect_id (str | None, default: None) –

    |message_effect_id|

    Added in version 21.3.

  • allow_paid_broadcast (bool | None, default: None) –

    |allow_paid_broadcast|

    Added in version 21.7.

  • suggested_post_parameters (SuggestedPostParameters | None, default: None) –

    |suggested_post_parameters|

    Added in version 22.4.

  • direct_messages_topic_id (int | None, default: None) –

    |direct_messages_topic_id|

    Added in version 22.4.

Keyword Arguments:
Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async send_venue(chat_id, latitude=None, longitude=None, title=None, address=None, foursquare_id=None, disable_notification=None, reply_markup=None, foursquare_type=None, google_place_id=None, google_place_type=None, protect_content=None, message_thread_id=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, venue=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send information about a venue.

Note

  • You can either supply venue, or latitude, longitude, title and address and optionally foursquare_id and foursquare_type or optionally google_place_id and google_place_type.

  • Foursquare details and Google Place details are mutually exclusive. However, this behaviour is undocumented and might be changed by Telegram.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • latitude (float | None, default: None) – Latitude of venue.

  • longitude (float | None, default: None) – Longitude of venue.

  • title (str | None, default: None) – Name of the venue.

  • address (str | None, default: None) – Address of the venue.

  • foursquare_id (str | None, default: None) – Foursquare identifier of the venue.

  • foursquare_type (str | None, default: None) – Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)

  • google_place_id (str | None, default: None) – Google Places identifier of the venue.

  • google_place_type (str | None, default: None) – Google Places type of the venue. (See supported types.)

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) –

    |protect_content|

    Added in version 13.10.

  • message_thread_id (int | None, default: None) –

    |message_thread_id_arg|

    Added in version 20.0.

  • reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply | None, default: None) – Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • reply_parameters (ReplyParameters | None, default: None) –

    |reply_parameters|

    Added in version 20.8.

  • business_connection_id (str | None, default: None) –

    |business_id_str|

    Added in version 21.1.

  • message_effect_id (str | None, default: None) –

    |message_effect_id|

    Added in version 21.3.

  • allow_paid_broadcast (bool | None, default: None) –

    |allow_paid_broadcast|

    Added in version 21.7.

  • suggested_post_parameters (SuggestedPostParameters | None, default: None) –

    |suggested_post_parameters|

    Added in version 22.4.

  • direct_messages_topic_id (int | None, default: None) –

    |direct_messages_topic_id|

    Added in version 22.4.

Keyword Arguments:
Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async send_video(chat_id, video, duration=None, caption=None, disable_notification=None, reply_markup=None, width=None, height=None, parse_mode=None, supports_streaming=None, caption_entities=None, protect_content=None, message_thread_id=None, has_spoiler=None, thumbnail=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, show_caption_above_media=None, cover=None, start_timestamp=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, filename=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document).

Bots can currently send video files of up to telegram.constants.FileSizeLimit.FILESIZE_UPLOAD in size, this limit may be changed in the future.

Note

thumbnail will be ignored for small video files, for which Telegram can easily generate thumbnails. However, this behaviour is undocumented and might be changed by Telegram.

See also

Working with Files and Media <Working-with-Files-and-Media>

Changed in version 20.5: Removed deprecated argument thumb. Use thumbnail instead.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • video (str | Path | IO[bytes] | InputFile | bytes | Video) –

    Video file to send. |fileinput| Lastly you can pass an existing telegram.Video object to send.

    Changed in version 13.2: Accept bytes as input.

    Changed in version 20.0: File paths as input is also accepted for bots not running in ~telegram.Bot.local_mode.

  • duration (int | timedelta | None, default: None) –

    Duration of sent video in seconds.

    Changed in version 21.11: |time-period-input|

  • width (int | None, default: None) – Video width.

  • height (int | None, default: None) – Video height.

  • cover (str | Path | IO[bytes] | InputFile | bytes | None, default: None) –

    Cover for the video in the message. |fileinputnopath|

    Added in version 21.11.

  • start_timestamp (int | None, default: None) –

    Start timestamp for the video in the message.

    Added in version 21.11.

  • caption (str | None, default: None) – Video caption (may also be used when resending videos by file_id), 0-telegram.constants.MessageLimit.CAPTION_LENGTH characters after entities parsing.

  • parse_mode (DefaultValue[DVValueType] | str | DefaultValue[None] | None, default: None) – |parse_mode|

  • caption_entities (Sequence[MessageEntity] | None, default: None) –

    |caption_entities|

    Changed in version 20.0: |sequenceargs|

  • supports_streaming (bool | None, default: None) – Pass True, if the uploaded video is suitable for streaming.

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) –

    |protect_content|

    Added in version 13.10.

  • message_thread_id (int | None, default: None) –

    |message_thread_id_arg|

    Added in version 20.0.

  • reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply | None, default: None) – Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • has_spoiler (bool | None, default: None) –

    Pass True if the video needs to be covered with a spoiler animation.

    Added in version 20.0.

  • thumbnail (str | Path | IO[bytes] | InputFile | bytes | None, default: None) –

    |thumbdocstring|

    Added in version 20.2.

  • reply_parameters (ReplyParameters | None, default: None) –

    |reply_parameters|

    Added in version 20.8.

  • business_connection_id (str | None, default: None) –

    |business_id_str|

    Added in version 21.1.

  • message_effect_id (str | None, default: None) –

    |message_effect_id|

    Added in version 21.3.

  • allow_paid_broadcast (bool | None, default: None) –

    |allow_paid_broadcast|

    Added in version 21.7.

  • show_caption_above_media (bool | None, default: None) –

    Pass |show_cap_above_med|

    Added in version 21.3.

  • suggested_post_parameters (SuggestedPostParameters | None, default: None) –

    |suggested_post_parameters|

    Added in version 22.4.

  • direct_messages_topic_id (int | None, default: None) –

    |direct_messages_topic_id|

    Added in version 22.4.

Keyword Arguments:
  • allow_sending_without_reply (bool, optional) –

    |allow_sending_without_reply| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • reply_to_message_id (int, optional) –

    |reply_to_msg_id| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • filename (str, optional) –

    Custom file name for the video, when uploading a new file. Convenience parameter, useful e.g. when sending files generated by the tempfile module.

    Added in version 13.1.

Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async send_video_note(chat_id, video_note, duration=None, length=None, disable_notification=None, reply_markup=None, protect_content=None, message_thread_id=None, thumbnail=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, filename=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send video messages.

Note

thumbnail will be ignored for small video files, for which Telegram can easily generate thumbnails. However, this behaviour is undocumented and might be changed by Telegram.

See also

Working with Files and Media <Working-with-Files-and-Media>

Changed in version 20.5: Removed deprecated argument thumb. Use thumbnail instead.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • video_note (str | Path | IO[bytes] | InputFile | bytes | VideoNote) –

    Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. |uploadinput| Lastly you can pass an existing telegram.VideoNote object to send. Sending video notes by a URL is currently unsupported.

    Changed in version 13.2: Accept bytes as input.

    Changed in version 20.0: File paths as input is also accepted for bots not running in ~telegram.Bot.local_mode.

  • duration (int | timedelta | None, default: None) –

    Duration of sent video in seconds.

    Changed in version 21.11: |time-period-input|

  • length (int | None, default: None) – Video width and height, i.e. diameter of the video message.

  • disable_notification (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) – |disable_notification|

  • protect_content (DefaultValue[DVValueType] | bool | DefaultValue[None] | None, default: None) –

    |protect_content|

    Added in version 13.10.

  • message_thread_id (int | None, default: None) –

    |message_thread_id_arg|

    Added in version 20.0.

  • reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply | None, default: None) – Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • thumbnail (str | Path | IO[bytes] | InputFile | bytes | None, default: None) –

    |thumbdocstring|

    Added in version 20.2.

  • reply_parameters (ReplyParameters | None, default: None) –

    |reply_parameters|

    Added in version 20.8.

  • business_connection_id (str | None, default: None) –

    |business_id_str|

    Added in version 21.1.

  • message_effect_id (str | None, default: None) –

    |message_effect_id|

    Added in version 21.3.

  • allow_paid_broadcast (bool | None, default: None) –

    |allow_paid_broadcast|

    Added in version 21.7.

  • suggested_post_parameters (SuggestedPostParameters | None, default: None) –

    |suggested_post_parameters|

    Added in version 22.4.

  • direct_messages_topic_id (int | None, default: None) –

    |direct_messages_topic_id|

    Added in version 22.4.

Keyword Arguments:
  • allow_sending_without_reply (bool, optional) –

    |allow_sending_without_reply| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • reply_to_message_id (int, optional) –

    |reply_to_msg_id| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • filename (str, optional) –

    Custom file name for the video note, when uploading a new file. Convenience parameter, useful e.g. when sending files generated by the tempfile module.

    Added in version 13.1.

Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async send_voice(chat_id, voice, duration=None, caption=None, disable_notification=None, reply_markup=None, parse_mode=None, caption_entities=None, protect_content=None, message_thread_id=None, reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, *, allow_sending_without_reply=None, reply_to_message_id=None, filename=None, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS , or in .MP3 format, or in .M4A format (other formats may be sent as Audio or Document). Bots can currently send voice messages of up to telegram.constants.FileSizeLimit.FILESIZE_UPLOAD in size, this limit may be changed in the future.

Note

To use this method, the file must have the type audio/ogg and be no more than telegram.constants.FileSizeLimit.VOICE_NOTE_FILE_SIZE in size. telegram.constants.FileSizeLimit.VOICE_NOTE_FILE_SIZE- telegram.constants.FileSizeLimit.FILESIZE_DOWNLOAD voice notes will be sent as files.

See also

Working with Files and Media <Working-with-Files-and-Media>

Parameters:
Keyword Arguments:
  • allow_sending_without_reply (bool, optional) –

    |allow_sending_without_reply| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • reply_to_message_id (int, optional) –

    |reply_to_msg_id| Mutually exclusive with reply_parameters, which this is a convenience parameter for

    Changed in version 20.8: Bot API 7.0 introduced reply_parameters |rtm_aswr_deprecated|

    Changed in version 21.0: |keyword_only_arg|

  • filename (str, optional) –

    Custom file name for the voice, when uploading a new file. Convenience parameter, useful e.g. when sending files generated by the tempfile module.

    Added in version 13.1.

Returns:

On success, the sent Message is returned.

Returns:

Message

Raises:

telegram.error.TelegramError

async setBusinessAccountBio(business_connection_id, bio=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_business_account_bio()

Return type:

bool

async setBusinessAccountGiftSettings(business_connection_id, show_gift_button, accepted_gift_types, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_business_account_gift_settings()

Return type:

bool

async setBusinessAccountName(business_connection_id, first_name, last_name=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_business_account_name()

Return type:

bool

async setBusinessAccountProfilePhoto(business_connection_id, photo, is_public=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_business_account_profile_photo()

Return type:

bool

async setBusinessAccountUsername(business_connection_id, username=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_business_account_username()

Return type:

bool

async setChatAdministratorCustomTitle(chat_id, user_id, custom_title, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_chat_administrator_custom_title()

Return type:

bool

async setChatDescription(chat_id, description=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_chat_description()

Return type:

bool

async setChatMenuButton(chat_id=None, menu_button=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_chat_menu_button()

Return type:

bool

async setChatPermissions(chat_id, permissions, use_independent_chat_permissions=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_chat_permissions()

Return type:

bool

async setChatPhoto(chat_id, photo, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_chat_photo()

Return type:

bool

async setChatStickerSet(chat_id, sticker_set_name, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_chat_sticker_set()

Return type:

bool

async setChatTitle(chat_id, title, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_chat_title()

Return type:

bool

async setCustomEmojiStickerSetThumbnail(name, custom_emoji_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_custom_emoji_sticker_set_thumbnail()

Return type:

bool

async setGameScore(user_id, score, chat_id=None, message_id=None, inline_message_id=None, force=None, disable_edit_message=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_game_score()

Return type:

Message | bool

async setMessageReaction(chat_id, message_id, reaction=None, is_big=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_message_reaction()

Return type:

bool

async setMyCommands(commands, scope=None, language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_my_commands()

Return type:

bool

async setMyDefaultAdministratorRights(rights=None, for_channels=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_my_default_administrator_rights()

Return type:

bool

async setMyDescription(description=None, language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_my_description()

Return type:

bool

async setMyName(name=None, language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_my_name()

Return type:

bool

async setMyShortDescription(short_description=None, language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_my_short_description()

Return type:

bool

async setPassportDataErrors(user_id, errors, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_passport_data_errors()

Return type:

bool

async setStickerEmojiList(sticker, emoji_list, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_sticker_emoji_list()

Return type:

bool

async setStickerKeywords(sticker, keywords=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_sticker_keywords()

Return type:

bool

async setStickerMaskPosition(sticker, mask_position=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_sticker_mask_position()

Return type:

bool

async setStickerPositionInSet(sticker, position, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_sticker_position_in_set()

Return type:

bool

async setStickerSetThumbnail(name, user_id, format, thumbnail=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_sticker_set_thumbnail()

Return type:

bool

async setStickerSetTitle(name, title, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_sticker_set_title()

Return type:

bool

async setUserEmojiStatus(user_id, emoji_status_custom_emoji_id=None, emoji_status_expiration_date=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_user_emoji_status()

Return type:

bool

async setWebhook(url, certificate=None, max_connections=None, allowed_updates=None, ip_address=None, drop_pending_updates=None, secret_token=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for set_webhook()

Return type:

bool

async set_business_account_bio(business_connection_id, bio=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Changes the bio of a managed business account. Requires the can_edit_bio business bot right.

Added in version 22.1.

Parameters:
  • business_connection_id (str) – Unique identifier of the business connection.

  • bio (str | None, default: None) – The new value of the bio for the business account; 0-telegram.constants.BusinessLimit.MAX_BIO_LENGTH characters.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_business_account_gift_settings(business_connection_id, show_gift_button, accepted_gift_types, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Changes the privacy settings pertaining to incoming gifts in a managed business account. Requires the can_change_gift_settings business bot right.

Added in version 22.1.

Parameters:
  • business_connection_id (str) – Unique identifier of the business connection

  • show_gift_button (bool) – Pass True, if a button for sending a gift to the user or by the business account must always be shown in the input field.

  • accepted_gift_types (AcceptedGiftTypes) – Types of gifts accepted by the business account.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_business_account_name(business_connection_id, first_name, last_name=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Changes the first and last name of a managed business account. Requires the can_edit_name business bot right.

Added in version 22.1.

Parameters:
  • business_connection_id (str) – Unique identifier of the business connection

  • first_name (str) – New first name of the business account; telegram.constants.BusinessLimit.MIN_NAME_LENGTH- telegram.constants.BusinessLimit.MAX_NAME_LENGTH characters.

  • last_name (str | None, default: None) – New last name of the business account; 0-telegram.constants.BusinessLimit.MAX_NAME_LENGTH characters.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_business_account_profile_photo(business_connection_id, photo, is_public=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Changes the profile photo of a managed business account. Requires the can_edit_profile_photo business bot right.

Added in version 22.1.

Parameters:
  • business_connection_id (str) – Unique identifier of the business connection.

  • photo (InputProfilePhoto) – The new profile photo to set.

  • is_public (bool | None, default: None) – Pass True to set the public photo, which will be visible even if the main photo is hidden by the business account’s privacy settings. An account can have only one public photo.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_business_account_username(business_connection_id, username=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Changes the username of a managed business account. Requires the can_edit_username business bot right.

Added in version 22.1.

Parameters:
  • business_connection_id (str) – Unique identifier of the business connection.

  • username (str | None, default: None) – New business account username; 0-telegram.constants.BusinessLimit.MAX_USERNAME_LENGTH characters.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_chat_administrator_custom_title(chat_id, user_id, custom_title, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to set a custom title for administrators promoted by the bot in a supergroup. The bot must be an administrator for this to work.

Parameters:
  • chat_id (int | str) – |chat_id_group|

  • user_id (int) – Unique identifier of the target administrator.

  • custom_title (str) – New custom title for the administrator; 0-telegram.constants.ChatLimit.CHAT_ADMINISTRATOR_CUSTOM_TITLE_LENGTH characters, emoji are not allowed.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_chat_description(chat_id, description=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

Parameters:
  • chat_id (str | int) – |chat_id_channel|

  • description (str | None, default: None) – New chat description, 0-telegram.constants.ChatLimit.CHAT_DESCRIPTION_LENGTH characters.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_chat_menu_button(chat_id=None, menu_button=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to change the bot’s menu button in a private chat, or the default menu button.

Added in version 20.0.

Parameters:
  • chat_id (int | None, default: None) – Unique identifier for the target private chat. If not specified, default bot’s menu button will be changed

  • menu_button (MenuButton | None, default: None) – An object for the new bot’s menu button. Defaults to telegram.MenuButtonDefault.

Returns:

On success, True is returned.

Returns:

bool

async set_chat_permissions(chat_id, permissions, use_independent_chat_permissions=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the telegram.ChatMemberAdministrator.can_restrict_members admin rights.

Parameters:
Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_chat_photo(chat_id, photo, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to set a new profile photo for the chat.

Photos can’t be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

Parameters:
Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_chat_sticker_set(chat_id, sticker_set_name, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field telegram.ChatFullInfo.can_set_sticker_set optionally returned in get_chat() requests to check if the bot can use this method.

Parameters:
  • chat_id (str | int) – |chat_id_group|

  • sticker_set_name (str) – Name of the sticker set to be set as the group sticker set.

Returns:

On success, True is returned.

Returns:

bool

async set_chat_title(chat_id, title, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to change the title of a chat. Titles can’t be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

Parameters:
  • chat_id (str | int) – |chat_id_channel|

  • title (str) – New chat title, telegram.constants.ChatLimit.MIN_CHAT_TITLE_LENGTH- telegram.constants.ChatLimit.MAX_CHAT_TITLE_LENGTH characters.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_custom_emoji_sticker_set_thumbnail(name, custom_emoji_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to set the thumbnail of a custom emoji sticker set.

Added in version 20.2.

Parameters:
  • name (str) – Sticker set name.

  • custom_emoji_id (str | None, default: None) – Custom emoji identifier of a sticker from the sticker set; pass an empty string to drop the thumbnail and use the first sticker as the thumbnail.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_game_score(user_id, score, chat_id=None, message_id=None, inline_message_id=None, force=None, disable_edit_message=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to set the score of the specified user in a game message.

Parameters:
  • user_id (int) – User identifier.

  • score (int) – New score, must be non-negative.

  • force (bool | None, default: None) – Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters.

  • disable_edit_message (bool | None, default: None) – Pass True, if the game message should not be automatically edited to include the current scoreboard.

  • chat_id (int | None, default: None) – Required if inline_message_id is not specified. Unique identifier for the target chat.

  • message_id (int | None, default: None) – Required if inline_message_id is not specified. Identifier of the sent message.

  • inline_message_id (str | None, default: None) – Required if chat_id and message_id are not specified. Identifier of the inline message.

Returns:

The edited message. If the message is not an inline message , True.

Returns:

Message | bool

Raises:

telegram.error.TelegramError – If the new score is not greater than the user’s current score in the chat and force is False.

async set_message_reaction(chat_id, message_id, reaction=None, is_big=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to change the chosen reactions on a message. Service messages of some types can’t be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. Bots can’t use paid reactions.

Added in version 20.8.

Parameters:
  • chat_id (str | int) – |chat_id_channel|

  • message_id (int) – Identifier of the target message. If the message belongs to a media group, the reaction is set to the first non-deleted message in the group instead.

  • reaction (Sequence[ReactionType | str] | ReactionType | str | None, default: None) –

    A list of reaction types to set on the message. Currently, as non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be used if it is either already present on the message or explicitly allowed by chat administrators. Paid reactions can’t be used by bots.

    Tip

    Passed str values will be converted to either telegram.ReactionTypeEmoji or telegram.ReactionTypeCustomEmoji depending on whether they are listed in ReactionEmoji.

  • is_big (bool | None, default: None) – Pass True to set the reaction with a big animation.

Returns:

boolbool On success, True is returned.

Raises:

telegram.error.TelegramError

async set_my_commands(commands, scope=None, language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to change the list of the bot’s commands. See the Telegram docs for more details about bot commands.

Parameters:
  • commands (Sequence[BotCommand | tuple[str, str]]) –

    A sequence of bot commands to be set as the list of the bot’s commands. At most telegram.constants.BotCommandLimit.MAX_COMMAND_NUMBER commands can be specified.

    Note

    If you pass in a sequence of tuple, the order of elements in each tuple must correspond to the order of positional arguments to create a BotCommand instance.

    Changed in version 20.0: |sequenceargs|

  • scope (BotCommandScope | None, default: None) –

    An object, describing scope of users for which the commands are relevant. Defaults to telegram.BotCommandScopeDefault.

    Added in version 13.7.

  • language_code (str | None, default: None) –

    A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands.

    Added in version 13.7.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_my_default_administrator_rights(rights=None, for_channels=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to change the default administrator rights requested by the bot when it’s added as an administrator to groups or channels. These rights will be suggested to users, but they are free to modify the list before adding the bot.

Added in version 20.0.

Parameters:
  • rights (ChatAdministratorRights | None, default: None) – A telegram.ChatAdministratorRights object describing new default administrator rights. If not specified, the default administrator rights will be cleared.

  • for_channels (bool | None, default: None) – Pass True to change the default administrator rights of the bot in channels. Otherwise, the default administrator rights of the bot for groups and supergroups will be changed.

Returns:

Returns True on success.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_my_description(description=None, language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to change the bot’s description, which is shown in the chat with the bot if the chat is empty.

Added in version 20.2.

Parameters:
  • description (str | None, default: None) – New bot description; 0-telegram.constants.BotDescriptionLimit.MAX_DESCRIPTION_LENGTH characters. Pass an empty string to remove the dedicated description for the given language.

  • language_code (str | None, default: None) – A two-letter ISO 639-1 language code. If empty, the description will be applied to all users for whose language there is no dedicated description.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_my_name(name=None, language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to change the bot’s name.

Added in version 20.3.

Parameters:
  • name (str | None, default: None) –

    New bot name; 0-telegram.constants.BotNameLimit.MAX_NAME_LENGTH characters. Pass an empty string to remove the dedicated name for the given language.

    Caution

    If language_code is not specified, a name must be specified.

  • language_code (str | None, default: None) – A two-letter ISO 639-1 language code. If empty, the name will be applied to all users for whose language there is no dedicated name.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_my_short_description(short_description=None, language_code=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to change the bot’s short description, which is shown on the bot’s profile page and is sent together with the link when users share the bot.

Added in version 20.2.

Parameters:
  • short_description (str | None, default: None) – New short description for the bot; 0-telegram.constants.BotDescriptionLimit.MAX_SHORT_DESCRIPTION_LENGTH characters. Pass an empty string to remove the dedicated description for the given language.

  • language_code (str | None, default: None) – A two-letter ISO 639-1 language code. If empty, the description will be applied to all users for whose language there is no dedicated description.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_passport_data_errors(user_id, errors, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change).

Use this if the data submitted by the user doesn’t satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.

Parameters:
  • user_id (int) – User identifier

  • errors (Sequence[PassportElementError]) –

    A Sequence describing the errors.

    Changed in version 20.0: |sequenceargs|

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_sticker_emoji_list(sticker, emoji_list, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to change the list of emoji assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot.

Added in version 20.2.

Parameters:
  • sticker (str | Sticker) –

    File identifier of the sticker or the sticker object.

    Changed in version 21.10: Accepts also telegram.Sticker instances.

  • emoji_list (Sequence[str]) – A sequence of telegram.constants.StickerLimit.MIN_STICKER_EMOJI- telegram.constants.StickerLimit.MAX_STICKER_EMOJI emoji associated with the sticker.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_sticker_keywords(sticker, keywords=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to change search keywords assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot.

Added in version 20.2.

Parameters:
  • sticker (str | Sticker) –

    File identifier of the sticker or the sticker object.

    Changed in version 21.10: Accepts also telegram.Sticker instances.

  • keywords (Sequence[str] | None, default: None) – A sequence of 0-telegram.constants.StickerLimit.MAX_SEARCH_KEYWORDS search keywords for the sticker with total length up to telegram.constants.StickerLimit.MAX_KEYWORD_LENGTH characters.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_sticker_mask_position(sticker, mask_position=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to change the mask position of a mask sticker. The sticker must belong to a sticker set that was created by the bot.

Added in version 20.2.

Parameters:
  • sticker (str | Sticker) –

    File identifier of the sticker or the sticker object.

    Changed in version 21.10: Accepts also telegram.Sticker instances.

  • mask_position (MaskPosition | None, default: None) – A object with the position where the mask should be placed on faces. Omit the parameter to remove the mask position.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_sticker_position_in_set(sticker, position, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to move a sticker in a set created by the bot to a specific position.

Parameters:
  • sticker (str | Sticker) –

    File identifier of the sticker or the sticker object.

    Changed in version 21.10: Accepts also telegram.Sticker instances.

  • position (int) – New sticker position in the set, zero-based.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_sticker_set_thumbnail(name, user_id, format, thumbnail=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to set the thumbnail of a regular or mask sticker set. The format of the thumbnail file must match the format of the stickers in the set.

Added in version 20.2.

Changed in version 21.1: As per Bot API 7.2, the new argument format will be required, and thus the order of the arguments had to be changed.

Parameters:
  • name (str) – Sticker set name

  • user_id (int) – User identifier of created sticker set owner.

  • format (str) –

    Format of the added sticker, must be one of telegram.constants.StickerFormat.STATIC for a .WEBP or .PNG image, telegram.constants.StickerFormat.ANIMATED for a .TGS animation, telegram.constants.StickerFormat.VIDEO for a .WEBM video.

    Added in version 21.1.

  • thumbnail (str | Path | IO[bytes] | InputFile | bytes | None, default: None) –

    A .WEBP or .PNG image with the thumbnail, must be up to telegram.constants.StickerSetLimit.MAX_STATIC_THUMBNAIL_SIZE kilobytes in size and have width and height of exactly telegram.constants.StickerSetLimit.STATIC_THUMB_DIMENSIONS px, or a .TGS animation with the thumbnail up to telegram.constants.StickerSetLimit.MAX_ANIMATED_THUMBNAIL_SIZE kilobytes in size; see the docs for animated sticker technical requirements, or a .WEBM video with the thumbnail up to telegram.constants.StickerSetLimit.MAX_ANIMATED_THUMBNAIL_SIZE kilobytes in size; see this for video sticker technical requirements.

    |fileinput|

    Animated and video sticker set thumbnails can’t be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_sticker_set_title(name, title, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to set the title of a created sticker set.

Added in version 20.2.

Parameters:
  • name (str) – Sticker set name.

  • title (str) – Sticker set title, telegram.constants.StickerLimit.MIN_NAME_AND_TITLE- telegram.constants.StickerLimit.MAX_NAME_AND_TITLE characters.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_user_emoji_status(user_id, emoji_status_custom_emoji_id=None, emoji_status_expiration_date=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Changes the emoji status for a given user that previously allowed the bot to manage their emoji status via the Mini App method requestEmojiStatusAccess .

Added in version 21.8.

Parameters:
  • user_id (int) – Unique identifier of the target user

  • emoji_status_custom_emoji_id (str | None, default: None) – Custom emoji identifier of the emoji status to set. Pass an empty string to remove the status.

  • emoji_status_expiration_date (int | datetime | None, default: None) – Expiration date of the emoji status, if any, as unix timestamp or datetime.datetime object. |tz-naive-dtms|

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async set_webhook(url, certificate=None, max_connections=None, allowed_updates=None, ip_address=None, drop_pending_updates=None, secret_token=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, Telegram will send an HTTPS POST request to the specified url, containing An Update. In case of an unsuccessful request (a request with response HTTP status code <https://en.wikipedia.org/wiki/List_of_HTTP_status_codes>`_different from ``2XY`), Telegram will repeat the request and give up after a reasonable amount of attempts.

If you’d like to make sure that the Webhook was set by you, you can specify secret data in the parameter secret_token. If specified, the request will contain a header X-Telegram-Bot-Api-Secret-Token with the secret token as content.

Note

  1. You will not be able to receive updates using get_updates() for long as an outgoing webhook is set up.

  2. To use a self-signed certificate, you need to upload your public key certificate using certificate parameter. Please upload as InputFile, sending a String will not work.

  3. Ports currently supported for Webhooks: telegram.constants.SUPPORTED_WEBHOOK_PORTS.

If you’re having any trouble setting up webhooks, please check out this guide to Webhooks.

Examples

Custom Webhook Bot

Parameters:
  • url (str) – HTTPS url to send updates to. Use an empty string to remove webhook integration.

  • certificate (str | Path | IO[bytes] | InputFile | bytes | None, default: None) – Upload your public key certificate so that the root certificate in use can be checked. See our self-signed guide                <Webhooks#creating-a-self-signed-certificate-using-openssl> for details. |uploadinputnopath|

  • ip_address (str | None, default: None) – The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS.

  • max_connections (int | None, default: None) – Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, telegram.constants.WebhookLimit.MIN_CONNECTIONS_LIMIT- telegram.constants.WebhookLimit.MAX_CONNECTIONS_LIMIT. Defaults to 40. Use lower values to limit the load on your bot’s server, and higher values to increase your bot’s throughput.

  • allowed_updates (Sequence[str] | None, default: None) –

    A sequence of the types of updates you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See telegram.Update for a complete list of available update types. Specify an empty sequence to receive all updates except telegram.Update.chat_member, telegram.Update.message_reaction and telegram.Update.message_reaction_count (default). If not specified, the previous setting will be used. Please note that this parameter doesn’t affect updates created before the call to the set_webhook, so unwanted update may be received for a short period of time.

    Changed in version 20.0: |sequenceargs|

  • drop_pending_updates (bool | None, default: None) – Pass True to drop all pending updates.

  • secret_token (str | None, default: None) –

    A secret token to be sent in a header X-Telegram-Bot-Api-Secret-Token in every webhook request, telegram.constants.WebhookLimit.MIN_SECRET_TOKEN_LENGTH- telegram.constants.WebhookLimit.MAX_SECRET_TOKEN_LENGTH characters. Only characters A-Z, a-z, 0-9, _ and - are allowed. The header is useful to ensure that the request comes from a webhook set by you.

    Added in version 20.0.

Returns:

boolbool On success, True is returned.

Raises:

telegram.error.TelegramError

async shutdown()[source]

Stop & clear resources used by this class. Currently just calls telegram.request.BaseRequest.shutdown() for the request objects used by this bot.

See also

initialize()

Added in version 20.0.

Return type:

None

async stopMessageLiveLocation(chat_id=None, message_id=None, inline_message_id=None, reply_markup=None, business_connection_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for stop_message_live_location()

Return type:

Message | bool

async stopPoll(chat_id, message_id, reply_markup=None, business_connection_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for stop_poll()

Return type:

Poll

async stop_message_live_location(chat_id=None, message_id=None, inline_message_id=None, reply_markup=None, business_connection_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before ~telegram.Location.live_period expires.

Parameters:
  • chat_id (int | str | None, default: None) – Required if inline_message_id is not specified. |chat_id_channel|

  • message_id (int | None, default: None) – Required if inline_message_id is not specified. Identifier of the sent message with live location to stop.

  • inline_message_id (str | None, default: None) – Required if chat_id and message_id are not specified. Identifier of the inline message.

  • reply_markup (InlineKeyboardMarkup | None, default: None) – An object for a new inline keyboard.

  • business_connection_id (str | None, default: None) –

    |business_id_str_edit|

    Added in version 21.4.

Returns:

On success, if edited message is not an inline message, the edited message is returned, otherwise True is returned.

Returns:

Message | bool

async stop_poll(chat_id, message_id, reply_markup=None, business_connection_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to stop a poll which was sent by the bot.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • message_id (int) – Identifier of the original message with the poll.

  • reply_markup (InlineKeyboardMarkup | None, default: None) – An object for a new message inline keyboard.

  • business_connection_id (str | None, default: None) –

    |business_id_str_edit|

    Added in version 21.4.

Returns:

On success, the stopped Poll is returned.

Returns:

Poll

Raises:

telegram.error.TelegramError

property supports_inline_queries: bool

Bot’s telegram.User.supports_inline_queries attribute. Shortcut for the corresponding attribute of bot.

Type:

bool

to_dict(recursive=True)[source]

See telegram.TelegramObject.to_dict().

Return type:

dict[str, Any]

property token: str

Bot’s unique authentication token.

Added in version 20.0.

Type:

str

async transferBusinessAccountStars(business_connection_id, star_count, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for transfer_business_account_stars()

Return type:

bool

async transferGift(business_connection_id, owned_gift_id, new_owner_chat_id, star_count=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for transfer_gift()

Return type:

bool

async transfer_business_account_stars(business_connection_id, star_count, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Transfers Telegram Stars from the business account balance to the bot’s balance. Requires the can_transfer_stars business bot right.

Added in version 22.1.

Parameters:
  • business_connection_id (str) – Unique identifier of the business connection

  • star_count (int) – Number of Telegram Stars to transfer; ~telegram.constants.BusinessLimit.MIN_STAR_COUNT-~telegram.constants.BusinessLimit.MAX_STAR_COUNT

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async transfer_gift(business_connection_id, owned_gift_id, new_owner_chat_id, star_count=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Transfers an owned unique gift to another user. Requires the can_transfer_and_upgrade_gifts business bot right. Requires can_transfer_stars business bot right if the transfer is paid.

Added in version 22.1.

Parameters:
  • business_connection_id (str) – Unique identifier of the business connection

  • owned_gift_id (str) – Unique identifier of the regular gift that should be transferred.

  • new_owner_chat_id (int) – Unique identifier of the chat which will own the gift. The chat must be active in the last ~telegram.constants.BusinessLimit.CHAT_ACTIVITY_TIMEOUT seconds.

  • star_count (int | None, default: None) – The amount of Telegram Stars that will be paid for the transfer from the business account balance. If positive, then the can_transfer_stars business bot right is required.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async unbanChatMember(chat_id, user_id, only_if_banned=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for unban_chat_member()

Return type:

bool

async unbanChatSenderChat(chat_id, sender_chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for unban_chat_sender_chat()

Return type:

bool

async unban_chat_member(chat_id, user_id, only_if_banned=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to unban a previously kicked user in a supergroup or channel.

The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don’t want this, use the parameter only_if_banned.

Parameters:
  • chat_id (str | int) – |chat_id_channel|

  • user_id (int) – Unique identifier of the target user.

  • only_if_banned (bool | None, default: None) – Do nothing if the user is not banned.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async unban_chat_sender_chat(chat_id, sender_chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to unban a previously banned channel in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights.

Added in version 13.9.

Parameters:
Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async unhideGeneralForumTopic(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for unhide_general_forum_topic()

Return type:

bool

async unhide_general_forum_topic(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to unhide the ‘General’ topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have can_manage_topics administrator rights.

Added in version 20.0.

Parameters:

chat_id (str | int) – |chat_id_group|

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async unpinAllChatMessages(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for unpin_all_chat_messages()

Return type:

bool

async unpinAllForumTopicMessages(chat_id, message_thread_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for unpin_all_forum_topic_messages()

Return type:

bool

async unpinAllGeneralForumTopicMessages(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for unpin_all_general_forum_topic_messages()

Return type:

bool

async unpinChatMessage(chat_id, message_id=None, business_connection_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for unpin_chat_message()

Return type:

bool

async unpin_all_chat_messages(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to clear the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the ~telegram.ChatAdministratorRights.can_pin_messages admin right in a supergroup or can_edit_messages admin right in a channel.

Parameters:

chat_id (str | int) – |chat_id_channel|

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async unpin_all_forum_topic_messages(chat_id, message_thread_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to clear the list of pinned messages in a forum topic. The bot must be an administrator in the chat for this to work and must have ~telegram.ChatAdministratorRights.can_pin_messages administrator rights in the supergroup.

Added in version 20.0.

Parameters:
Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async unpin_all_general_forum_topic_messages(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to clear the list of pinned messages in a General forum topic. The bot must be an administrator in the chat for this to work and must have ~telegram.ChatAdministratorRights.can_pin_messages administrator rights in the supergroup.

Added in version 20.5.

Parameters:

chat_id (str | int) – |chat_id_group|

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async unpin_chat_message(chat_id, message_id=None, business_connection_id=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to remove a message from the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the ~telegram.ChatAdministratorRights.can_pin_messages admin right in a supergroup or can_edit_messages admin right in a channel.

Parameters:
  • chat_id (str | int) – |chat_id_channel|

  • message_id (int | None, default: None) – Identifier of the message to unpin. Required if business_connection_id is specified. If not specified, the most recent pinned message (by sending date) will be unpinned.

  • business_connection_id (str | None, default: None) –

    Unique identifier of the business connection on behalf of which the message will be unpinned.

    Added in version 21.5.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async upgradeGift(business_connection_id, owned_gift_id, keep_original_details=None, star_count=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for upgrade_gift()

Return type:

bool

async upgrade_gift(business_connection_id, owned_gift_id, keep_original_details=None, star_count=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Upgrades a given regular gift to a unique gift. Requires the can_transfer_and_upgrade_gifts business bot right. Additionally requires the can_transfer_stars business bot right if the upgrade is paid.

Added in version 22.1.

Parameters:
  • business_connection_id (str) – Unique identifier of the business connection

  • owned_gift_id (str) – Unique identifier of the regular gift that should be upgraded to a unique one.

  • keep_original_details (bool | None, default: None) – Pass True to keep the original gift text, sender and receiver in the upgraded gift

  • star_count (int | None, default: None) – The amount of Telegram Stars that will be paid for the upgrade from the business account balance. If gift.prepaid_upgrade_star_count > 0, then pass 0, otherwise, the can_transfer_stars business bot right is required and telegram.Gift.upgrade_star_count must be passed.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async uploadStickerFile(user_id, sticker, sticker_format, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for upload_sticker_file()

Return type:

File

async upload_sticker_file(user_id, sticker, sticker_format, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Use this method to upload a file with a sticker for later use in the create_new_sticker_set() and add_sticker_to_set() methods (can be used multiple times).

Changed in version 20.5: Removed deprecated parameter png_sticker.

Parameters:
Returns:

On success, the uploaded File is returned.

Returns:

File

Raises:

telegram.error.TelegramError

property username: str

Bot’s username. Shortcut for the corresponding attribute of bot.

Type:

str

async verifyChat(chat_id, custom_description=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for verify_chat()

Return type:

bool

async verifyUser(user_id, custom_description=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)

Alias for verify_user()

Return type:

bool

async verify_chat(chat_id, custom_description=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Verifies a chat |org-verify| which is represented by the bot.

Added in version 21.10.

Parameters:
  • chat_id (int | str) – |chat_id_channel|

  • custom_description (str | None, default: None) – Custom description for the verification; 0- telegram.constants.VerifyLimit.MAX_TEXT_LENGTH characters. Must be empty if the organization isn’t allowed to provide a custom verification description.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

async verify_user(user_id, custom_description=None, *, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)[source]

Verifies a user |org-verify| which is represented by the bot.

Added in version 21.10.

Parameters:
  • user_id (int) – Unique identifier of the target user.

  • custom_description (str | None, default: None) – Custom description for the verification; 0- telegram.constants.VerifyLimit.MAX_TEXT_LENGTH characters. Must be empty if the organization isn’t allowed to provide a custom verification description.

Returns:

On success, True is returned.

Returns:

bool

Raises:

telegram.error.TelegramError

class spotted.data.user.ChatPermissions(can_send_messages=None, can_send_polls=None, can_send_other_messages=None, can_add_web_page_previews=None, can_change_info=None, can_invite_users=None, can_pin_messages=None, can_manage_topics=None, can_send_audios=None, can_send_documents=None, can_send_photos=None, can_send_videos=None, can_send_video_notes=None, can_send_voice_notes=None, *, api_kwargs=None)[source]

Bases: TelegramObject

Describes actions that a non-administrator user is allowed to take in a chat.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their can_send_messages, can_send_polls, can_send_other_messages, can_add_web_page_previews, can_change_info, can_invite_users, can_pin_messages, can_send_audios, can_send_documents, can_send_photos, can_send_videos, can_send_video_notes, can_send_voice_notes, and can_manage_topics are equal.

Changed in version 20.0: can_manage_topics is considered as well when comparing objects of this type in terms of equality.

Changed in version 20.5:

Note

Though not stated explicitly in the official docs, Telegram changes not only the permissions that are set, but also sets all the others to False. However, since not documented, this behavior may change unbeknown to PTB.

Parameters:
  • can_send_messages (bool | None, default: None) – True, if the user is allowed to send text messages, contacts, locations and venues.

  • can_send_polls (bool | None, default: None) – True, if the user is allowed to send polls.

  • can_send_other_messages (bool | None, default: None) – True, if the user is allowed to send animations, games, stickers and use inline bots.

  • can_add_web_page_previews (bool | None, default: None) – True, if the user is allowed to add web page previews to their messages.

  • can_change_info (bool | None, default: None) – True, if the user is allowed to change the chat title, photo and other settings. Ignored in public supergroups.

  • can_invite_users (bool | None, default: None) – True, if the user is allowed to invite new users to the chat.

  • can_pin_messages (bool | None, default: None) – True, if the user is allowed to pin messages. Ignored in public supergroups.

  • can_manage_topics (bool | None, default: None) –

    True, if the user is allowed to create forum topics. If omitted defaults to the value of can_pin_messages.

    Added in version 20.0.

  • can_send_audios (bool | None, default: None) –

    True, if the user is allowed to send audios.

    Added in version 20.1.

  • can_send_documents (bool | None, default: None) –

    True, if the user is allowed to send documents.

    Added in version 20.1.

  • can_send_photos (bool | None, default: None) –

    True, if the user is allowed to send photos.

    Added in version 20.1.

  • can_send_videos (bool | None, default: None) –

    True, if the user is allowed to send videos.

    Added in version 20.1.

  • can_send_video_notes (bool | None, default: None) –

    True, if the user is allowed to send video notes.

    Added in version 20.1.

  • can_send_voice_notes (bool | None, default: None) –

    True, if the user is allowed to send voice notes.

    Added in version 20.1.

can_send_messages

Optional. True, if the user is allowed to send text messages, contacts, locations and venues.

Type:

bool

can_send_polls

Optional. True, if the user is allowed to send polls, implies can_send_messages.

Type:

bool

can_send_other_messages

Optional. True, if the user is allowed to send animations, games, stickers and use inline bots.

Type:

bool

can_add_web_page_previews

Optional. True, if the user is allowed to add web page previews to their messages.

Type:

bool

can_change_info

Optional. True, if the user is allowed to change the chat title, photo and other settings. Ignored in public supergroups.

Type:

bool

can_invite_users

Optional. True, if the user is allowed to invite new users to the chat.

Type:

bool

can_pin_messages

Optional. True, if the user is allowed to pin messages. Ignored in public supergroups.

Type:

bool

can_manage_topics

Optional. True, if the user is allowed to create forum topics. If omitted defaults to the value of can_pin_messages.

Added in version 20.0.

Type:

bool

can_send_audios

True, if the user is allowed to send audios.

Added in version 20.1.

Type:

bool

can_send_documents

True, if the user is allowed to send documents.

Added in version 20.1.

Type:

bool

can_send_photos

True, if the user is allowed to send photos.

Added in version 20.1.

Type:

bool

can_send_videos

True, if the user is allowed to send videos.

Added in version 20.1.

Type:

bool

can_send_video_notes

True, if the user is allowed to send video notes.

Added in version 20.1.

Type:

bool

can_send_voice_notes

True, if the user is allowed to send voice notes.

Added in version 20.1.

Type:

bool

classmethod all_permissions()[source]

This method returns an ChatPermissions instance with all attributes set to True. This is e.g. useful when unrestricting a chat member with telegram.Bot.restrict_chat_member().

Added in version 20.0.

Return type:

ChatPermissions

can_add_web_page_previews: bool | None
can_change_info: bool | None
can_invite_users: bool | None
can_manage_topics: bool | None
can_pin_messages: bool | None
can_send_audios: bool | None
can_send_documents: bool | None
can_send_messages: bool | None
can_send_other_messages: bool | None
can_send_photos: bool | None
can_send_polls: bool | None
can_send_video_notes: bool | None
can_send_videos: bool | None
can_send_voice_notes: bool | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

ChatPermissions

classmethod no_permissions()[source]

This method returns an ChatPermissions instance with all attributes set to False.

Added in version 20.0.

Return type:

ChatPermissions

class spotted.data.user.Config[source]

Bases: object

Configurations

AUTOREPLIES_PATH = 'autoreplies.yaml'
DEFAULT_AUTOREPLIES_PATH = '/opt/hostedtoolcache/Python/3.14.3/x64/lib/python3.14/site-packages/spotted/config/yaml/autoreplies.yaml'
DEFAULT_SETTINGS_PATH = '/opt/hostedtoolcache/Python/3.14.3/x64/lib/python3.14/site-packages/spotted/config/yaml/settings.yaml'
SETTINGS_PATH = 'settings.yaml'
classmethod autoreplies_get(*keys, default=None)[source]

Get the value of the specified key in the autoreplies configuration dictionary. If the key is a tuple, it will return the value of the nested key. If the key is not present, it will return the default value.

Parameters:
  • key – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

dict – value of the key or default value

classmethod debug_get(key, default=None)[source]

Get the value of the specified key in the configuration under the ‘debug’ section. If the key is not present, it will return the default value.

Parameters:
  • key (Literal['local_log', 'reset_on_load', 'log_file', 'log_error_file', 'db_file', 'backup_chat_id', 'backup_keep_pending', 'crypto_key', 'zip_backup']) – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

Any – value of the key or default value

classmethod override_settings(config)[source]

Overrides the settings with the configuration provided in the config dict.

Parameters:

config (dict) – configuration dict used to override the current settings

classmethod post_get(key, default=None)[source]

Get the value of the specified key in the configuration under the ‘post’ section. If the key is not present, it will return the default value.

Parameters:
  • key (Literal['community_group_id', 'channel_id', 'channel_tag', 'comments', 'admin_group_id', 'n_votes', 'remove_after_h', 'report', 'report_wait_mins', 'replace_anonymous_comments', 'delete_anonymous_comments', 'blacklist_messages', 'max_n_warns', 'warn_expiration_days', 'mute_default_duration_days', 'autoreplies_per_page', 'reject_after_autoreply']) – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

Any – value of the key or default value

classmethod reload(force_reload=False)[source]

Reset the configuration. The next time a setting parameter is required, the whole configuration will be reloaded. If force_reload is True, the configuration will be reloaded immediately.

Parameters:

force_reload (bool, default: False) – if True, the configuration will be reloaded immediately

classmethod settings_get(*keys, default=None)[source]

Get the value of the specified key in the configuration. If the key is a tuple, it will return the value of the nested key. If the key is not present, it will return the default value.

Parameters:
  • key – key to get

  • default (Any, default: None) – default value to return if the key is not present

Returns:

Any – value of the key or default value

class spotted.data.user.DbManager[source]

Bases: object

Class that handles the management of databases

classmethod count_from(table_name, select='*', where='', where_args=None)[source]

Returns the number of rows found with the query. Executes “SELECT COUNT(select) FROM table_name [WHERE where (with where_args)]”

Parameters:
  • table_name (str) – name of the table used in the FROM

  • select (str, default: '*') – columns considered for the query

  • where (str, default: '') – where clause, with %s placeholders for the where_args

  • where_args (tuple | None, default: None) – args used in the where clause

Returns:

int – number of rows

classmethod delete_from(table_name, where='', where_args=None)[source]

Deletes the rows from the specified table, where the condition, when set, is satisfied. Executes “DELETE FROM table_name [WHERE where (with where_args)]”

Parameters:
  • table_name (str) – name of the table used in the DELETE FROM

  • where (str, default: '') – where clause, with %s placeholders for the where args

  • where_args (tuple | None, default: None) – args used in the where clause

classmethod get_db()[source]

Creates the connection to the database. It can be sqlite or postgres

Returns:

tuple[Connection, Cursor] – sqlite database connection and cursor

classmethod insert_into(table_name, values, columns='', multiple_rows=False)[source]

Inserts the specified values in the database. Executes “INSERT INTO table_name ([columns]) VALUES (placeholders)”

Parameters:
  • table_name (str) – name of the table used in the INSERT INTO

  • values (tuple) – values to be inserted. If multiple_rows is true, tuple of tuples of values to be inserted

  • columns (tuple | str, default: '') – columns that will be inserted, as a tuple of strings

  • multiple_rows (bool, default: False) – whether or not multiple rows will be inserted at the same time

classmethod query_from_file(*file_path)[source]

Commits all the queries in the specified file. The queries must be separated by a —– string Should not be used to select something

Parameters:

file_path (str) – path of the text file containing the queries

classmethod query_from_string(*queries)[source]

Commits all the queries in the string Should not be used to select something

Parameters:

queries (str) – tuple of queries

static register_adapters_and_converters()[source]

Registers the adapter and converters for the datetime type. Needed from python 3.12 onwards, as the default option has been deprecated

static row_factory(cursor, row)[source]

Converts the rows from the database into a dictionary

Parameters:
  • cursor (Cursor) – database cursor

  • row (dict) – row from the database

Returns:

dict – dictionary containing the row. The keys are the column names

classmethod select_from(table_name, select='*', where='', where_args=None, group_by='', order_by='')[source]

Returns the results of a query. Executes “SELECT select FROM table_name [WHERE where (with where_args)] [GROUP_BY group_by] [ORDER BY order_by]”

Parameters:
  • table_name (str) – name of the table used in the FROM

  • select (str, default: '*') – columns considered for the query

  • where (str, default: '') – where clause, with %s placeholders for the where_args

  • where_args (tuple | None, default: None) – args used in the where clause

  • group_by (str, default: '') – group by clause

  • order_by (str, default: '') – order by clause

Returns:

list – rows from the select

classmethod update_from(table_name, set_clause, where='', args=None)[source]

Updates the rows from the specified table, where the condition, when set, is satisfied. Executes “UPDATE table_name SET set_clause (with args) [WHERE where (with args)]”

Parameters:
  • table_name (str) – name of the table used in the DELETE FROM

  • set_clause (str) – set clause, with %s placeholders

  • where (str, default: '') – where clause, with %s placeholders for the where args

  • args (tuple | None, default: None) – args used both in the set clause and in the where clause, in this order

class spotted.data.user.PendingPost(user_id, u_message_id, g_message_id, admin_group_id, date, credit_username=None)[source]

Bases: object

Class that represents a pending post

Parameters:
  • user_id (int) – id of the user that sent the post

  • u_message_id (int) – id of the original message of the post

  • g_message_id (int) – id of the post in the group

  • admin_group_id (int) – id of the admin group

  • credit_username (str | None, default: None) – username of the user that sent the post if it’s a credit post

  • date (datetime) – when the post was sent

admin_group_id: int
classmethod create(user_message, g_message_id, admin_group_id, credit_username=None)[source]

Creates a new post and inserts it in the table of pending posts

Parameters:
  • user_message (Message) – message sent by the user that contains the post

  • g_message_id (int) – id of the post in the group

  • admin_group_id (int) – id of the admin group

  • credit_username (str | None, default: None) – username of the user that sent the post if it’s a credit post

Returns:

PendingPost – instance of the class

credit_username: str | None = None
date: datetime
delete_post()[source]

Removes all entries on a post that is no longer pending

classmethod from_group(g_message_id, admin_group_id)[source]

Retrieves a pending post from the info related to the admin group

Parameters:
  • g_message_id (int) – id of the post in the group

  • admin_group_id (int) – id of the admin group

Returns:

PendingPost | None – instance of the class

classmethod from_user(user_id)[source]

Retrieves a pending post from the user_id

Parameters:

user_id (int) – id of the author of the post

Returns:

PendingPost | None – instance of the class

g_message_id: int
static get_all(admin_group_id, before=None)[source]

Gets the list of pending posts in the specified admin group. If before is specified, returns only the one sent before that timestamp

Parameters:
  • admin_group_id (int) – id of the admin group

  • before (datetime | None, default: None) – timestamp before which messages will be considered

Returns:

list[PendingPost] – list of ids of pending posts

get_credit_username()[source]

Gets the username of the user that credited the post

Returns:

str | None – username of the user that credited the post, or None if the post is not credited

get_list_admin_votes(vote=None)[source]

Gets the list of admins that approved or rejected the post

Parameters:

vote (bool | None, default: None) – whether you look for the approve or reject votes, or None if you want all the votes

Returns:

list[int] | list[tuple[int, bool]] – list of admins that approved or rejected a pending post

get_votes(vote)[source]

Gets all the votes of a specific kind (approve or reject)

Parameters:

vote (bool) – whether you look for the approve or reject votes

Returns:

int – number of votes

save_post()[source]

Saves the pending_post in the database

Return type:

PendingPost

set_admin_vote(admin_id, approval)[source]

Adds the vote of the admin on a specific post, or update the existing vote, if needed

Parameters:
  • admin_id (int) – id of the admin that voted

  • approval (bool) – whether the vote is approval or reject

Returns:

int – number of similar votes (all the approve or the reject), or -1 if the vote wasn’t updated

u_message_id: int
user_id: int
class spotted.data.user.User(user_id, private_message_id=None, ban_date=None, mute_date=None, mute_expire_date=None, follow_date=None)[source]

Bases: object

Class that represents a user

Parameters:
  • user_id (int) – id of the user

  • private_message_id (int | None, default: None) – id of the private message sent by the user to the bot. Only used for following

  • ban_date (datetime | None, default: None) – datetime of when the user was banned. Only used for banned users

  • follow_date (datetime | None, default: None) – datetime of when the user started following a post. Only used for following users

ban()[source]

Adds the user to the banned list

ban_date: datetime | None = None
classmethod banned_users()[source]

Returns a list of all the banned users

Return type:

list[User]

become_anonym()[source]

Removes the user from the credited list, if he was present

Returns:

bool – whether the user was already anonym

become_credited()[source]

Adds the user to the credited list, if he wasn’t already credited

Returns:

bool – whether the user was already credited

classmethod credited_users()[source]

Returns a list of all the credited users

Return type:

list[User]

follow_date: datetime | None = None
classmethod following_users(message_id)[source]

Returns a list of all the users following the post with the associated private message id used by the bot to send updates about the post by replying to it

Parameters:

message_id (int) – id of the post the users are following

Returns:

list[User] – list of users with private_message_id set to the id of the private message in the user’s conversation with the bot

get_follow_private_message_id(message_id)[source]

Verifies if the user is following a post

Parameters:

message_id (int) – id of the post

Returns:

int | None – whether the user is following the post or not

get_n_warns()[source]

Returns the count of consecutive warns of the user

Return type:

int

async get_user_sign(bot)[source]

Generates a sign for the user. It will be a random name for an anonym user

Parameters:

bot (Bot) – telegram bot

Returns:

str – the sign of the user

property is_banned: bool

If the user is banned or not

property is_credited: bool

If the user is in the credited list

is_following(message_id)[source]

Verifies if the user is following a post

Parameters:

message_id (int) – id of the post

Returns:

bool – whether the user is following the post or not

property is_muted: bool

If the user is muted or not

property is_pending: bool

If the user has a post already pending or not

property is_warn_bannable: bool

If the user is bannable due to warns

async mute(bot, days)[source]

Mute a user restricting its actions inside the community group

Parameters:
  • bot (Bot | None) – the telegram bot

  • days (int) – The number of days the user should be muted for.

mute_date: datetime | None = None
mute_expire_date: datetime | None = None
classmethod muted_users()[source]

Returns a list of all the muted users

Return type:

list[User]

private_message_id: int | None = None
sban()[source]

Removes the user from the banned list

Returns:

bool – whether the user was present in the banned list before the sban or not

set_follow(message_id, private_message_id)[source]

Sets the follow status of the user. If the private_message_id is None, the user is not following the post anymore, and the record is deleted from the database. Otherwise, the user is following the post and a new record is created.

Parameters:
  • message_id (int) – id of the post

  • private_message_id (int | None) – id of the private message. If None, the record is deleted

async unmute(bot)[source]

Unmute a user taking back all restrictions

Parameters:

bot (Bot | None) – the telegram bot

Returns:

bool – whether the user was muted before the unmute or not

user_id: int
warn()[source]

Increase the number of warns of a user If the number of warns is greater than the maximum allowed, the user is banned

Parameters:

bot – the telegram bot

spotted.data.user.choice(seq)

Choose a random element from a non-empty sequence.

spotted.data.user.dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

class spotted.data.user.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])

Bases: date

The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints.

astimezone()

tz -> convert to local time in new timezone tz

classmethod combine()

date, time -> datetime with same date and time fields

ctime()

Return ctime() style string.

date()

Return date object with same year, month and day.

dst()

Return self.tzinfo.dst(self).

fold
classmethod fromisoformat(object, /)

string -> datetime from a string in most ISO 8601 formats

classmethod fromtimestamp()

timestamp[, tz] -> tz’s local time from POSIX timestamp.

hour
isoformat()

[sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM]. sep is used to separate the year from the time, and defaults to ‘T’. The optional argument timespec specifies the number of additional terms of the time to include. Valid options are ‘auto’, ‘hours’, ‘minutes’, ‘seconds’, ‘milliseconds’ and ‘microseconds’.

max = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
microsecond
min = datetime.datetime(1, 1, 1, 0, 0)
minute
classmethod now(tz=None)

Returns new datetime object representing current time local to tz.

tz

Timezone object.

If no tz is specified, uses local timezone.

replace()

Return datetime with new specified fields.

resolution = datetime.timedelta(microseconds=1)
second
classmethod strptime()

string, format -> new datetime parsed from a string (like time.strptime()).

time()

Return time object with same time but with tzinfo=None.

timestamp()

Return POSIX timestamp as float.

timetuple()

Return time tuple, compatible with time.localtime().

timetz()

Return time object with same time and tzinfo.

tzinfo
tzname()

Return self.tzinfo.tzname(self).

classmethod utcfromtimestamp()

Construct a naive UTC datetime from a POSIX timestamp.

classmethod utcnow()

Return a new datetime representing UTC day and time.

utcoffset()

Return self.tzinfo.utcoffset(self).

utctimetuple()

Return UTC time tuple, compatible with time.localtime().

spotted.data.user.read_md(file_name)[source]

Read the contents of a markdown file. The path is data/markdown. It also will replace the following parts of the text:

  • {channel_tag} -> Config.settings[‘post’][‘channel_tag’]

  • {bot_tag} -> Config.settings[‘bot_tag’]

Parameters:

file_name (str) – name of the file

Returns:

str – contents of the file

class spotted.data.user.timedelta

Bases: object

Difference between two datetime values.

timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

All arguments are optional and default to 0. Arguments may be integers or floats, and may be positive or negative.

days

Number of days.

max = datetime.timedelta(days=999999999, seconds=86399, microseconds=999999)
microseconds

Number of microseconds (>= 0 and less than 1 second).

min = datetime.timedelta(days=-999999999)
resolution = datetime.timedelta(microseconds=1)
seconds

Number of seconds (>= 0 and less than 1 day).

total_seconds()

Total seconds in the duration.