Module contents

Modules that handle the events the bot recognizes and reacts to

class spotted.handlers.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.handlers.BotCommand(command, description, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents a bot command.

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

Parameters:
  • command (str) – Text of the command; telegram.BotCommand.MIN_COMMAND- telegram.BotCommand.MAX_COMMAND characters. Can contain only lowercase English letters, digits and underscores.

  • description (str) – Description of the command; telegram.BotCommand.MIN_DESCRIPTION- telegram.BotCommand.MAX_DESCRIPTION characters.

command

Text of the command; telegram.BotCommand.MIN_COMMAND- telegram.BotCommand.MAX_COMMAND characters. Can contain only lowercase English letters, digits and underscores.

Type:

str

description

Description of the command; telegram.BotCommand.MIN_DESCRIPTION- telegram.BotCommand.MAX_DESCRIPTION characters.

Type:

str

MAX_COMMAND: Final[int] = 32

telegram.constants.BotCommandLimit.MAX_COMMAND

Added in version 20.0.

MAX_DESCRIPTION: Final[int] = 256

telegram.constants.BotCommandLimit.MAX_DESCRIPTION

Added in version 20.0.

MIN_COMMAND: Final[int] = 1

telegram.constants.BotCommandLimit.MIN_COMMAND

Added in version 20.0.

MIN_DESCRIPTION: Final[int] = 1

telegram.constants.BotCommandLimit.MIN_DESCRIPTION

Added in version 20.0.

command: str
description: str
class spotted.handlers.BotCommandScopeAllPrivateChats(*, api_kwargs=None)[source]

Bases: BotCommandScope

Represents the scope of bot commands, covering all private chats.

Added in version 13.7.

type

Scope type telegram.BotCommandScope.ALL_PRIVATE_CHATS.

Type:

str

class spotted.handlers.BotCommandScopeChat(chat_id, *, api_kwargs=None)[source]

Bases: BotCommandScope

Represents the scope of bot commands, covering a specific chat.

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

Added in version 13.7.

Parameters:

chat_id (str | int) – |chat_id_group|

type

Scope type telegram.BotCommandScope.CHAT.

Type:

str

chat_id

|chat_id_group|

Type:

str | int

chat_id: str | int
class spotted.handlers.CallbackQueryHandler(callback, pattern=None, game_pattern=None, block=True)[source]

Bases: BaseHandler[Update, CCT, RT]

Handler class to handle Telegram callback queries. Optionally based on a regex.

Read the documentation of the re module for more information.

Note

  • If your bot allows arbitrary objects as ~telegram.InlineKeyboardButton.callback_data, it may happen that the original callback_data for the incoming telegram.CallbackQuery can not be found. This is the case when either a malicious client tempered with the telegram.CallbackQuery.data or the data was simply dropped from cache or not persisted. In these cases, an instance of telegram.ext.InvalidCallbackData will be set as telegram.CallbackQuery.data.

    Added in version 13.6.

  • If neither pattern nor game_pattern is set, any CallbackQuery will be handled. If only pattern is set, queries with game_short_name will not be considered and vice versa. If both patterns are set, queries with either :attr: ~telegram.CallbackQuery.game_short_name or data matching the defined pattern will be handled

    Added in version 21.5.

Warning

When setting block to False, you cannot rely on adding custom attributes to telegram.ext.CallbackContext. See its docs for more info.

Parameters:
callback

The callback function for this handler.

Type:

coroutine function

pattern

Optional. Regex pattern, callback or type to test telegram.CallbackQuery.data against.

Changed in version 13.6: Added support for arbitrary callback data.

Type:

re.Pattern | callable | type

game_pattern

Optional. Regex pattern to test telegram.CallbackQuery.game_short_name

Type:

re.Pattern

block

Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update().

Type:

bool

check_update(update)[source]

Determines whether an update should be passed to this handler’s callback.

Parameters:

update (object) – Incoming update.

Returns:

bool | object | Nonebool

collect_additional_context(context, update, application, check_result)[source]

Add the result of re.match(pattern, update.callback_query.data) to CallbackContext.matches as list with one element.

Return type:

None

game_pattern: str | Pattern[str] | None
pattern: str | Pattern[str] | type | Callable[[object], bool | None] | None
class spotted.handlers.CommandHandler(command, callback, filters=None, block=True, has_args=None)[source]

Bases: BaseHandler[Update, CCT, RT]

Handler class to handle Telegram commands.

Commands are Telegram messages that start with a telegram.MessageEntity.BOT_COMMAND (so with /, optionally followed by an @ and the bot’s name and/or some additional text). The handler will add a list to the CallbackContext named CallbackContext.args. It will contain a list of strings, which is the text following the command split on single or consecutive whitespace characters.

By default, the handler listens to messages as well as edited messages. To change this behavior use ~filters.UpdateType.EDITED_MESSAGE in the filter argument.

Note

CommandHandler does not handle (edited) channel posts and does not handle commands that are part of a caption. Please use MessageHandler with a suitable combination of filters (e.g. telegram.ext.filters.UpdateType.CHANNEL_POSTS, telegram.ext.filters.CAPTION and telegram.ext.filters.Regex) to handle those messages.

Note

If you want to support a different entity in the beginning, e.g. if a command message is wrapped in a telegram.MessageEntity.CODE, use the telegram.ext.PrefixHandler.

Warning

When setting block to False, you cannot rely on adding custom attributes to telegram.ext.CallbackContext. See its docs for more info.

Examples

  • Timer Bot

  • Error Handler Bot

Changed in version 20.0:

  • Renamed the attribute command to commands, which now is always a frozenset

  • Updating the commands this handler listens to is no longer possible.

Parameters:
  • command (str | Collection[str]) – The command or list of commands this handler should listen for. Case-insensitive. Limitations are the same as for telegram.BotCommand.command.

  • callback (Callable[[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])], Coroutine[Any, Any, TypeVar(RT)]]) –

    The callback function for this handler. Will be called when check_update() has determined that an update should be processed by this handler. Callback signature:

    async def callback(update: Update, context: CallbackContext)
    

    The return value of the callback is usually ignored except for the special case of telegram.ext.ConversationHandler.

  • filters (BaseFilter | None, default: None) – A filter inheriting from telegram.ext.filters.BaseFilter. Standard filters can be found in telegram.ext.filters. Filters can be combined using bitwise operators (& for and, | for or, ~ for not)

  • block (bool | DefaultValue[DVValueType], default: True) –

    Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update(). Defaults to True.

    See also

    Concurrency

  • has_args (bool | int | None, default: None) –

    Determines whether the command handler should process the update or not. If True, the handler will process any non-zero number of args. If False, the handler will only process if there are no args. if int, the handler will only process if there are exactly that many args. Defaults to None, which means the handler will process any or no args.

    Added in version 20.5.

Raises:

ValueError – When the command is too long or has illegal chars.

commands

The set of commands this handler should listen for.

Type:

frozenset[str]

callback

The callback function for this handler.

Type:

coroutine function

filters

Optional. Only allow updates with these filters.

Type:

telegram.ext.filters.BaseFilter

block

Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update().

Type:

bool

has_args

Optional argument, otherwise all implementations of CommandHandler will break. Defaults to None, which means the handler will process any args or no args.

Added in version 20.5.

Type:

bool | int | None

check_update(update)[source]

Determines whether an update should be passed to this handler’s callback.

Parameters:

update (object) – Incoming update.

Returns:

The list of args for the handler.

Returns:

bool | tuple[list[str], bool | dict[str, list[Any]] | None] | None

collect_additional_context(context, update, application, check_result)[source]

Add text after the command to CallbackContext.args as list, split on single whitespaces and add output of data filters to CallbackContext as well.

Return type:

None

commands: frozenset[str]
filters: filters_module.BaseFilter
has_args: bool | int | None
class spotted.handlers.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.handlers.MessageHandler(filters, callback, block=True)[source]

Bases: BaseHandler[Update, CCT, RT]

Handler class to handle Telegram messages. They might contain text, media or status updates.

Warning

When setting block to False, you cannot rely on adding custom attributes to telegram.ext.CallbackContext. See its docs for more info.

Parameters:
  • filters (BaseFilter | None) –

    A filter inheriting from telegram.ext.filters.BaseFilter. Standard filters can be found in telegram.ext.filters. Filters can be combined using bitwise operators (& for and, | for or, ~ for not). Passing None is a shortcut to passing telegram.ext.filters.ALL.

    See also

    Advanced Filters <Extensions---Advanced-Filters>

  • callback (Callable[[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])], Coroutine[Any, Any, TypeVar(RT)]]) –

    The callback function for this handler. Will be called when check_update() has determined that an update should be processed by this handler. Callback signature:

    async def callback(update: Update, context: CallbackContext)
    

    The return value of the callback is usually ignored except for the special case of telegram.ext.ConversationHandler.

  • block (bool | DefaultValue[DVValueType], default: True) –

    Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update(). Defaults to True.

    See also

    Concurrency

filters

Only allow updates with these Filters. See telegram.ext.filters for a full list of all available filters.

Type:

telegram.ext.filters.BaseFilter

callback

The callback function for this handler.

Type:

coroutine function

block

Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update().

Type:

bool

check_update(update)[source]

Determines whether an update should be passed to this handler’s callback.

Parameters:

update (object) – Incoming update.

Returns:

bool | dict[str, list[Any]] | Nonebool

collect_additional_context(context, update, application, check_result)[source]

Adds possible output of data filters to the CallbackContext.

Return type:

None

filters: filters_module.BaseFilter
exception spotted.handlers.PTBUserWarning[source]

Bases: UserWarning

Custom user warning class used for warnings in this library.

See also

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

Added in version 20.0.

async spotted.handlers.add_commands(app)[source]

Adds the list of commands with their description to the bot

Parameters:

app (Application) – supplied application

spotted.handlers.add_handlers(app)[source]

Adds all the needed handlers to the application

Parameters:

app (Application) – supplied application

spotted.handlers.add_jobs(app)[source]

Adds all the jobs to be scheduled to the application

Parameters:

app (Application) – supplied application

async spotted.handlers.anonymous_comment_msg(update, context)[source]

Handles a new anonym comment on a post in the comment group. Deletes the original post and sends a message with the same text, to avoid any abuse.

Parameters:
async spotted.handlers.approve_no_callback(update, context)[source]

Handles the approve_no callback. Add a negative vote to the post, updating the keyboard if necessary. If the number of negative votes is greater than the number of votes required, the post is rejected, deleting it from the pending_post table and notifying the user

Parameters:
async spotted.handlers.approve_status_callback(update, context)[source]

Handles the approve_status callback. Pauses or resume voting on a specific pending post

Parameters:
Returns:

text and replyMarkup that make up the reply, new conversation state

async spotted.handlers.approve_yes_callback(update, context)[source]

Handles the approve_yes callback. Add a positive vote to the post, updating the keyboard if necessary. If the number of positive votes is greater than the number of votes required, the post is approved, deleting it from the pending_post table and copying it to the channel

Parameters:
async spotted.handlers.autoreply_callback(update, context)[source]

Handles the autoreply callback. Reply to the user with the autoreply message to inform them about the reason of the rejection

Parameters:
async spotted.handlers.autoreply_cmd(update, context)[source]

Handles the /autoreply command. Used by replying to one of his pending posts with /autoreply + one of the keys in the autoreplies dictionary in the config file. Send a message to the user with the autoreply message to inform them about a problem with their post

Parameters:
async spotted.handlers.ban_cmd(update, context)[source]

Handles the /ban command. Ban a user by replying to one of his pending posts with /ban

Parameters:
async spotted.handlers.cancel_cmd(update, context)[source]

Handles the /cancel command. Exits from the post pipeline and removes the eventual pending post of the user

Parameters:
Returns:

int – next state of the conversation

async spotted.handlers.clean_muted_users(context)[source]

Job called each day at 05:00 utc. Removed expired users mute records from the database

Parameters:

context (CallbackContext) – context passed by the jobqueue

async spotted.handlers.clean_pending_cmd(_, context)[source]

Handles the /clean_pending command. Automatically rejects all pending posts that are older than the chosen amount of hours

Parameters:
  • _ – update event

  • context (CallbackContext) – context passed by the handler

async spotted.handlers.clean_pending_job(context)[source]

Job called each day at 05:00 utc. Automatically rejects all pending posts that are older than the chosen amount of hours

Parameters:

context (CallbackContext) – context passed by the jobqueue

async spotted.handlers.db_backup_cmd(update, context)[source]

Handles the /db_backup command. Automatically upload and send current version of db for backup

Parameters:
  • _ – update event

  • context (CallbackContext) – context passed by the handler

async spotted.handlers.db_backup_job(context)[source]

Job called each day at 05:00 utc. Automatically upload and send last version of db for backup

Parameters:

context (CallbackContext) – context passed by the jobqueue

async spotted.handlers.error_handler(update, context)[source]

Logs the error and notifies the admins.

Parameters:
spotted.handlers.filterwarnings(action, message='', category=<class 'Warning'>, module='', lineno=0, append=False)[source]

Insert an entry into the list of warnings filters (at the front).

‘action’ – one of “error”, “ignore”, “always”, “all”, “default”, “module”,

or “once”

‘message’ – a regex that the warning message must match ‘category’ – a class that the warning must be a subclass of ‘module’ – a regex that the module name must match ‘lineno’ – an integer line number, 0 matches all warnings ‘append’ – if true, append to the list of filters

async spotted.handlers.follow_spot_callback(update, context)[source]

Handles the follow callback.

Parameters:
async spotted.handlers.follow_spot_comment(update, context)[source]

Handles a new comment on a post in the comment group. Checks if someone is following the post, and sends them an update in case.

Parameters:
async spotted.handlers.forwarded_post_msg(update, context)[source]

Handles the post forwarded in the channel group. Sends a reply in the channel group and stores it in the database, so that the post can be voted

Parameters:
async spotted.handlers.help_cmd(update, context)[source]

Handles the /help command. Sends an help message

Parameters:
async spotted.handlers.log_message(update, _)[source]

Log the message that caused the update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

async spotted.handlers.mute_cmd(update, context)[source]

Handles the /mute command. Mute a user by replying to one of his message in the comment group with /mute <n_days> :type update: Update :param update: update event :type context: CallbackContext :param context: context passed by the handler

async spotted.handlers.purge_cmd(update, context)[source]

Handles the /purge command. Deletes all posts and the related votes in the database whose actual telegram message could not be found

Parameters:
async spotted.handlers.reload_cmd(update, context)[source]

Handles the /reload command. Reload the configuration file, updating the bot’s settings. This incudes both the _settings.yaml_ and the _autorereply.yaml_ file. This way the bot can be updated without restarting it.

In actuality, the current singleton is destroyed and a new one is created as soon as a configuration request is deemed necessary.

Parameters:

Warning

Loading different configurations may cause inconsistencies in live conversations.

async spotted.handlers.reply_cmd(update, context)[source]

Handles the /reply command. Send a message to a user by replying to one of his pending posts with /reply + the message you want to send

Parameters:
spotted.handlers.report_spot_conv_handler()[source]

Creates the report (user) conversation handler. The states are:

  • reporting_spot: submit the reason of the report. Expects text

Returns:

ConversationHandler – conversation handler

spotted.handlers.report_user_conv_handler()[source]

Creates the /report (user) conversation handler. The states are:

  • reporting_user: submit the username to report. Expects text starting with @ and without spaces in between

  • reporting_user_reason: submit the reason of the report. Expects text

Returns:

ConversationHandler – conversation handler

async spotted.handlers.rules_cmd(update, context)[source]

Handles the /rules command. Sends a message containing the rules

Parameters:
async spotted.handlers.sban_cmd(update, context)[source]

Handles the /sban command. Sban a user by using this command and listing all the user_id to sban

Parameters:
async spotted.handlers.settings_callback(update, context)[source]

Handles the settings,[ anonimo | credit ] callback.

  • anonimo: Removes the user_id from the table of credited users, if present.

  • credit: Adds the user_id to the table of credited users, if it wasn’t already there.

Parameters:
async spotted.handlers.settings_cmd(update, context)[source]

Handles the /settings command. Let’s the user choose whether his posts will be credited or not

Parameters:
async spotted.handlers.spam_comment_msg(update, context)[source]

Handles a spam comment on a post in the comment group. Deletes the original post and bans the user.

Parameters:
Return type:

None

spotted.handlers.spot_conv_handler()[source]

Creates the spot conversation handler. The states are:

  • posting: submit the spot. Expects text, photo or many other formats

  • confirm: confirm or cancel the spot submission. Expects an inline query

Returns:

ConversationHandler – conversation handler

async spotted.handlers.start_cmd(update, context)[source]

Handles the /start command. Sends a welcoming message

Parameters:
class spotted.handlers.time

Bases: object

time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) –> a time object

All arguments are optional. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints.

dst()

Return self.tzinfo.dst(self).

fold
classmethod fromisoformat(object, /)

string -> time from a string in ISO 8601 format

hour
isoformat()

Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].

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.time(23, 59, 59, 999999)
microsecond
min = datetime.time(0, 0)
minute
replace()

Return time with new specified fields.

resolution = datetime.timedelta(microseconds=1)
second
strftime()

format -> strftime() style string.

classmethod strptime()

string, format -> new time parsed from a string (like time.strptime()).

tzinfo
tzname()

Return self.tzinfo.tzname(self).

utcoffset()

Return self.tzinfo.utcoffset(self).

async spotted.handlers.unmute_cmd(update, context)[source]

Handles the /unmute command. Unmute a user by using this command and listing all the user_id to unmute

Parameters:
async spotted.handlers.warn_cmd(update, context)[source]
Handles the /warn command.

Warn a user by replying to a user’comment on the community group or to a pending spot/report.

Parameters:

spotted.handlers package

Submodules

spotted.handlers.anonym_comment module

Anonym Comment on a post in the comment group

class spotted.handlers.anonym_comment.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.anonym_comment.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.handlers.anonym_comment.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.anonym_comment.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
async spotted.handlers.anonym_comment.anonymous_comment_msg(update, context)[source]

Handles a new anonym comment on a post in the comment group. Deletes the original post and sends a message with the same text, to avoid any abuse.

Parameters:

spotted.handlers.approve module

Approve actions the admin can take on a pending post.

exception spotted.handlers.approve.BadRequest(message)[source]

Bases: NetworkError

Raised when Telegram could not process the request correctly.

class spotted.handlers.approve.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.approve.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.handlers.approve.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

exception spotted.handlers.approve.Forbidden(message)[source]

Bases: TelegramError

Raised when the bot has not enough rights to perform the requested action.

Examples

Raw API Bot

Changed in version 20.0: This class was previously named Unauthorized.

class spotted.handlers.approve.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.handlers.approve.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
async spotted.handlers.approve.approve_no_callback(update, context)[source]

Handles the approve_no callback. Add a negative vote to the post, updating the keyboard if necessary. If the number of negative votes is greater than the number of votes required, the post is rejected, deleting it from the pending_post table and notifying the user

Parameters:
async spotted.handlers.approve.approve_status_callback(update, context)[source]

Handles the approve_status callback. Pauses or resume voting on a specific pending post

Parameters:
Returns:

text and replyMarkup that make up the reply, new conversation state

async spotted.handlers.approve.approve_yes_callback(update, context)[source]

Handles the approve_yes callback. Add a positive vote to the post, updating the keyboard if necessary. If the number of positive votes is greater than the number of votes required, the post is approved, deleting it from the pending_post table and copying it to the channel

Parameters:
spotted.handlers.approve.get_approve_kb(pending_post=None, approve=-1, reject=-1, credited_username=None)[source]

Generates the InlineKeyboard for the pending post. If the pending post is None, the keyboard will be generated with 0 votes. Otherwise, the keyboard will be generated with the correct number of votes. To avoid unnecessary queries, the number of votes can be passed as an argument and will be assumed to be correct.

Parameters:
  • pending_post (PendingPost | None, default: None) – existing pending post to which the keyboard is attached

  • approve (int, default: -1) – number of approve votes known in advance

  • reject (int, default: -1) – number of reject votes known in advance

  • credited_username (str | None, default: None) – username of the user who credited the post if it was credited

Returns:

InlineKeyboardMarkup – new inline keyboard

spotted.handlers.approve.get_paused_kb(page, items_per_page)[source]

Generates the InlineKeyboard for the paused post

Parameters:

page (int) – page of the autoreplies

Returns:

InlineKeyboardMarkup – autoreplies keyboard append with resume button

async spotted.handlers.approve.reject_post(info, pending_post, reason=None)[source]

Rejects a pending post

Parameters:
  • info (EventInfo) – information about the callback

  • pending_post (PendingPost) – pending post to reject

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

spotted.handlers.autoreply module

/autoreply command

class spotted.handlers.autoreply.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.autoreply.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.handlers.autoreply.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.autoreply.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.handlers.autoreply.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.handlers.autoreply.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
async spotted.handlers.autoreply.autoreply_callback(update, context)[source]

Handles the autoreply callback. Reply to the user with the autoreply message to inform them about the reason of the rejection

Parameters:
async spotted.handlers.autoreply.autoreply_cmd(update, context)[source]

Handles the /autoreply command. Used by replying to one of his pending posts with /autoreply + one of the keys in the autoreplies dictionary in the config file. Send a message to the user with the autoreply message to inform them about a problem with their post

Parameters:
async spotted.handlers.autoreply.reject_post(info, pending_post, reason=None)[source]

Rejects a pending post

Parameters:
  • info (EventInfo) – information about the callback

  • pending_post (PendingPost) – pending post to reject

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

spotted.handlers.ban module

/ban command

class spotted.handlers.ban.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.ban.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.handlers.ban.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.ban.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.handlers.ban.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.handlers.ban.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
class spotted.handlers.ban.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

async spotted.handlers.ban.ban_cmd(update, context)[source]

Handles the /ban command. Ban a user by replying to one of his pending posts with /ban

Parameters:
async spotted.handlers.ban.execute_ban(user_id, info)[source]

Execute the ban of a user by his user_id

Parameters:
  • user_id (int) – The user_id of the user to ban

  • info (EventInfo) – The EventInfo object

spotted.handlers.cancel module

/cancel command

class spotted.handlers.cancel.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.cancel.ConversationState(*values)[source]

Bases: Enum

Enum for the states of the conversation. The end state must have value -1, since it is the convention used by the ConversationHandler to terminate the conversation.

END = -1
POSTING = 1
POSTING_CONFIRM = 3
POSTING_PREVIEW = 2
REPORTING_SPOT = 4
REPORTING_USER = 5
REPORTING_USER_REASON = 6
SENDING_USER_REPORT = 7
class spotted.handlers.cancel.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.cancel.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.handlers.cancel.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
async spotted.handlers.cancel.cancel_cmd(update, context)[source]

Handles the /cancel command. Exits from the post pipeline and removes the eventual pending post of the user

Parameters:
Returns:

int – next state of the conversation

spotted.handlers.clean_pending module

/clean_pending command

class spotted.handlers.clean_pending.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.clean_pending.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
async spotted.handlers.clean_pending.clean_pending_cmd(_, context)[source]

Handles the /clean_pending command. Automatically rejects all pending posts that are older than the chosen amount of hours

Parameters:
  • _ – update event

  • context (CallbackContext) – context passed by the handler

async spotted.handlers.clean_pending.clean_pending_job(context)[source]

Job called each day at 05:00 utc. Automatically rejects all pending posts that are older than the chosen amount of hours

Parameters:

context (CallbackContext) – context passed by the jobqueue

spotted.handlers.constants module

Constants used by the bot handlers

class spotted.handlers.constants.ConversationState(*values)[source]

Bases: Enum

Enum for the states of the conversation. The end state must have value -1, since it is the convention used by the ConversationHandler to terminate the conversation.

END = -1
POSTING = 1
POSTING_CONFIRM = 3
POSTING_PREVIEW = 2
REPORTING_SPOT = 4
REPORTING_USER = 5
REPORTING_USER_REASON = 6
SENDING_USER_REPORT = 7
class spotted.handlers.constants.Enum(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: object

Create a collection of name/value pairs.

Example enumeration:

>>> class Color(Enum):
...     RED = 1
...     BLUE = 2
...     GREEN = 3

Access them by:

  • attribute access:

    >>> Color.RED
    <Color.RED: 1>
    
  • value lookup:

    >>> Color(1)
    <Color.RED: 1>
    
  • name lookup:

    >>> Color['RED']
    <Color.RED: 1>
    

Enumerations can be iterated over, and know how many members they have:

>>> len(Color)
3
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.

class spotted.handlers.constants.auto(value=_auto_null)[source]

Bases: object

Instances are replaced with an appropriate value in Enum class suites.

spotted.handlers.constants.unique(enumeration)[source]

Class decorator for enumerations ensuring unique member values.

spotted.handlers.db_backup module

/db_backup command

class spotted.handlers.db_backup.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.db_backup.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.handlers.db_backup.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.db_backup.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
async spotted.handlers.db_backup.db_backup_cmd(update, context)[source]

Handles the /db_backup command. Automatically upload and send current version of db for backup

Parameters:
  • _ – update event

  • context (CallbackContext) – context passed by the handler

async spotted.handlers.db_backup.db_backup_job(context)[source]

Job called each day at 05:00 utc. Automatically upload and send last version of db for backup

Parameters:

context (CallbackContext) – context passed by the jobqueue

spotted.handlers.follow_comment module

Detect Comment on a post in the comment group

exception spotted.handlers.follow_comment.BadRequest(message)[source]

Bases: NetworkError

Raised when Telegram could not process the request correctly.

class spotted.handlers.follow_comment.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.follow_comment.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

exception spotted.handlers.follow_comment.Forbidden(message)[source]

Bases: TelegramError

Raised when the bot has not enough rights to perform the requested action.

Examples

Raw API Bot

Changed in version 20.0: This class was previously named Unauthorized.

class spotted.handlers.follow_comment.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
class spotted.handlers.follow_comment.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

async spotted.handlers.follow_comment.follow_spot_comment(update, context)[source]

Handles a new comment on a post in the comment group. Checks if someone is following the post, and sends them an update in case.

Parameters:

spotted.handlers.follow_spot module

Handles callback when the ‘Follow Spot’ button is clicked.

class spotted.handlers.follow_spot.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.follow_spot.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.handlers.follow_spot.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

exception spotted.handlers.follow_spot.Forbidden(message)[source]

Bases: TelegramError

Raised when the bot has not enough rights to perform the requested action.

Examples

Raw API Bot

Changed in version 20.0: This class was previously named Unauthorized.

class spotted.handlers.follow_spot.InlineKeyboardButton(text, url=None, callback_data=None, switch_inline_query=None, switch_inline_query_current_chat=None, callback_game=None, pay=None, login_url=None, web_app=None, switch_inline_query_chosen_chat=None, copy_text=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents one button of an inline keyboard.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their text, url, login_url, callback_data, switch_inline_query, switch_inline_query_current_chat, callback_game, web_app and pay are equal.

Note

  • Exactly one of the optional fields must be used to specify type of the button.

  • Mind that callback_game is not working as expected. Putting a game short name in it might, but is not guaranteed to work.

  • If your bot allows for arbitrary callback data, in keyboards returned in a response from telegram, callback_data may be an instance of telegram.ext.InvalidCallbackData. This will be the case, if the data associated with the button was already deleted.

    Added in version 13.6.

  • Since Bot API 5.5, it’s now allowed to mention users by their ID in inline keyboards. This will only work in Telegram versions released after December 7, 2021. Older clients will display unsupported message.

Warning

  • If your bot allows your arbitrary callback data, buttons whose callback data is a non-hashable object will become unhashable. Trying to evaluate hash(button) will result in a TypeError.

    Changed in version 13.6.

  • After Bot API 6.1, only HTTPS links will be allowed in login_url.

Examples

  • Inline Keyboard 1

  • Inline Keyboard 2

Changed in version 20.0: web_app is considered as well when comparing objects of this type in terms of equality.

Parameters:
  • text (str) – Label text on the button.

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

    HTTP or tg:// url to be opened when the button is pressed. Links tg://user?id=<user_id> can be used to mention a user by their ID without using a username, if this is allowed by their privacy settings.

    Changed in version 13.9: You can now mention a user using tg://user?id=<user_id>.

  • login_url (LoginUrl | None, default: None) –

    An HTTPS URL used to automatically authorize the user. Can be used as a replacement for the Telegram Login Widget.

    Caution

    Only HTTPS links are allowed after Bot API 6.1.

  • callback_data (str | object | None, default: None) –

    Data to be sent in a callback query to the bot when the button is pressed, UTF-8 telegram.InlineKeyboardButton.MIN_CALLBACK_DATA- telegram.InlineKeyboardButton.MAX_CALLBACK_DATA bytes. If the bot instance allows arbitrary callback data, anything can be passed.

    Tip

    The value entered here will be available in telegram.CallbackQuery.data.

    See also

    Arbitrary callback_data <Arbitrary-callback_data>

  • web_app (WebAppInfo | None, default: None) –

    Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answer_web_app_query(). Available only in private chats between a user and the bot. Not supported for messages sent on behalf of a Telegram Business account.

    Added in version 20.0.

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

    If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot’s username and the specified inline query in the input field. May be empty, in which case just the bot’s username will be inserted. Not supported for messages sent on behalf of a Telegram Business account.

    Tip

    This is similar to the parameter switch_inline_query_chosen_chat, but gives no control over which chats can be selected.

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

    If set, pressing the button will insert the bot’s username and the specified inline query in the current chat’s input field. May be empty, in which case only the bot’s username will be inserted.

    This offers a quick way for the user to open your bot in inline mode in the same chat - good for selecting something from multiple options. Not supported in channels and for messages sent on behalf of a Telegram Business account.

  • copy_text (CopyTextButton | None, default: None) –

    Description of the button that copies the specified text to the clipboard.

    Added in version 21.7.

  • callback_game (CallbackGame | None, default: None) –

    Description of the game that will be launched when the user presses the button

    Note

    This type of button must always be the first button in the first row.

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

    Specify True, to send a Pay button. Substrings “⭐️” and “XTR” in the buttons’s text will be replaced with a Telegram Star icon.

    Note

    This type of button must always be the first button in the first row and can only be used in invoice messages.

  • switch_inline_query_chosen_chat (SwitchInlineQueryChosenChat | None, default: None) –

    If set, pressing the button will prompt the user to select one of their chats of the specified type, open that chat and insert the bot’s username and the specified inline query in the input field. Not supported for messages sent on behalf of a Telegram Business account.

    Added in version 20.3.

    Tip

    This is similar to switch_inline_query, but gives more control on which chats can be selected.

    Caution

    The PTB team has discovered that this field works correctly only if your Telegram client is released after April 20th 2023.

text

Label text on the button.

Type:

str

url

Optional. HTTP or tg:// url to be opened when the button is pressed. Links tg://user?id=<user_id> can be used to mention a user by their ID without using a username, if this is allowed by their privacy settings.

Changed in version 13.9: You can now mention a user using tg://user?id=<user_id>.

Type:

str

login_url

Optional. An HTTPS URL used to automatically authorize the user. Can be used as a replacement for the Telegram Login Widget.

Caution

Only HTTPS links are allowed after Bot API 6.1.

Type:

telegram.LoginUrl

callback_data

Optional. Data to be sent in a callback query to the bot when the button is pressed, UTF-8 telegram.InlineKeyboardButton.MIN_CALLBACK_DATA- telegram.InlineKeyboardButton.MAX_CALLBACK_DATA bytes.

Type:

str | object

web_app

Optional. Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answer_web_app_query(). Available only in private chats between a user and the bot. Not supported for messages sent on behalf of a Telegram Business account.

Added in version 20.0.

Type:

telegram.WebAppInfo

switch_inline_query

Optional. If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot’s username and the specified inline query in the input field. May be empty, in which case just the bot’s username will be inserted. Not supported for messages sent on behalf of a Telegram Business account.

Tip

This is similar to the parameter switch_inline_query_chosen_chat, but gives no control over which chats can be selected.

Type:

str

switch_inline_query_current_chat

Optional. If set, pressing the button will insert the bot’s username and the specified inline query in the current chat’s input field. May be empty, in which case only the bot’s username will be inserted.

This offers a quick way for the user to open your bot in inline mode in the same chat - good for selecting something from multiple options. Not supported in channels and for messages sent on behalf of a Telegram Business account.

Type:

str

copy_text

Optional. Description of the button that copies the specified text to the clipboard.

Added in version 21.7.

Type:

telegram.CopyTextButton

callback_game

Optional. Description of the game that will be launched when the user presses the button.

Note

This type of button must always be the first button in the first row.

Type:

telegram.CallbackGame

pay

Optional. Specify True, to send a Pay button. Substrings “⭐️” and “XTR” in the buttons’s text will be replaced with a Telegram Star icon.

Note

This type of button must always be the first button in the first row and can only be used in invoice messages.

Type:

bool

switch_inline_query_chosen_chat

Optional. If set, pressing the button will prompt the user to select one of their chats of the specified type, open that chat and insert the bot’s username and the specified inline query in the input field. Not supported for messages sent on behalf of a Telegram Business account.

Added in version 20.3.

Tip

This is similar to switch_inline_query, but gives more control on which chats can be selected.

Caution

The PTB team has discovered that this field works correctly only if your Telegram client is released after April 20th 2023.

Type:

telegram.SwitchInlineQueryChosenChat

MAX_CALLBACK_DATA: Final[int] = 64

telegram.constants.InlineKeyboardButtonLimit.MAX_CALLBACK_DATA

Added in version 20.0.

MIN_CALLBACK_DATA: Final[int] = 1

telegram.constants.InlineKeyboardButtonLimit.MIN_CALLBACK_DATA

Added in version 20.0.

callback_data: str | object | None
callback_game: CallbackGame | None
copy_text: CopyTextButton | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

InlineKeyboardButton

login_url: LoginUrl | None
pay: bool | None
switch_inline_query: str | None
switch_inline_query_chosen_chat: SwitchInlineQueryChosenChat | None
switch_inline_query_current_chat: str | None
text: str
update_callback_data(callback_data)[source]

Sets callback_data to the passed object. Intended to be used by telegram.ext.CallbackDataCache.

Added in version 13.6.

Parameters:

callback_data (str | object) – The new callback data.

Return type:

None

url: str | None
web_app: WebAppInfo | None
class spotted.handlers.follow_spot.InlineKeyboardMarkup(inline_keyboard, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an inline keyboard that appears right next to the message it belongs to.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their size of inline_keyboard and all the buttons are equal.

https://core.telegram.org/file/464001863/110f3/I47qTXAD9Z4.120010/e0ea04f66357b640ec

An inline keyboard on a message

See also

Another kind of keyboard would be the telegram.ReplyKeyboardMarkup.

Examples

  • Inline Keyboard 1

  • Inline Keyboard 2

Parameters:

inline_keyboard (Sequence[Sequence[InlineKeyboardButton]]) –

Sequence of button rows, each represented by a sequence of InlineKeyboardButton objects.

Changed in version 20.0: |sequenceclassargs|

inline_keyboard

Tuple of button rows, each represented by a tuple of InlineKeyboardButton objects.

Changed in version 20.0: |tupleclassattrs|

Type:

tuple[tuple[telegram.InlineKeyboardButton]]

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

See telegram.TelegramObject.de_json().

Return type:

InlineKeyboardMarkup

classmethod from_button(button, **kwargs)[source]

Shortcut for:

InlineKeyboardMarkup([[button]], **kwargs)

Return an InlineKeyboardMarkup from a single InlineKeyboardButton

Parameters:

button (InlineKeyboardButton) – The button to use in the markup

Return type:

InlineKeyboardMarkup

classmethod from_column(button_column, **kwargs)[source]

Shortcut for:

InlineKeyboardMarkup([[button] for button in button_column], **kwargs)

Return an InlineKeyboardMarkup from a single column of InlineKeyboardButtons

Parameters:

button_column (Sequence[InlineKeyboardButton]) –

The button to use in the markup

Changed in version 20.0: |sequenceargs|

Return type:

InlineKeyboardMarkup

classmethod from_row(button_row, **kwargs)[source]

Shortcut for:

InlineKeyboardMarkup([button_row], **kwargs)

Return an InlineKeyboardMarkup from a single row of InlineKeyboardButtons

Parameters:

button_row (Sequence[InlineKeyboardButton]) –

The button to use in the markup

Changed in version 20.0: |sequenceargs|

Return type:

InlineKeyboardMarkup

inline_keyboard: tuple[tuple[InlineKeyboardButton, ...], ...]
class spotted.handlers.follow_spot.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
class spotted.handlers.follow_spot.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

async spotted.handlers.follow_spot.follow_spot_callback(update, context)[source]

Handles the follow callback.

Parameters:

spotted.handlers.forwarded_post module

Message forwarded by the telegram channel

class spotted.handlers.forwarded_post.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.forwarded_post.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.forwarded_post.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
async spotted.handlers.forwarded_post.forwarded_post_msg(update, context)[source]

Handles the post forwarded in the channel group. Sends a reply in the channel group and stores it in the database, so that the post can be voted

Parameters:

spotted.handlers.help module

/help command

class spotted.handlers.help.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.help.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.handlers.help.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.help.ParseMode(*values)[source]

Bases: StringEnum

This enum contains the available parse modes. The enum members of this enumeration are instances of str and can be treated as such.

Added in version 20.0.

HTML = 'HTML'

HTML parse mode.

Type:

str

MARKDOWN = 'Markdown'

Markdown parse mode.

Note

MARKDOWN is a legacy mode, retained by Telegram for backward compatibility. You should use MARKDOWN_V2 instead.

Type:

str

MARKDOWN_V2 = 'MarkdownV2'

Markdown parse mode version 2.

Type:

str

class spotted.handlers.help.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
async spotted.handlers.help.help_cmd(update, context)[source]

Handles the /help command. Sends an help message

Parameters:
spotted.handlers.help.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.handlers.job_handlers module

Scheduled jobs of the bot

exception spotted.handlers.job_handlers.BadRequest(message)[source]

Bases: NetworkError

Raised when Telegram could not process the request correctly.

spotted.handlers.job_handlers.BinasciiError

alias of Error

class spotted.handlers.job_handlers.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.job_handlers.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.handlers.job_handlers.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.handlers.job_handlers.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.job_handlers.Fernet(key, backend=None)[source]

Bases: object

decrypt(token, ttl=None)[source]
Return type:

bytes

decrypt_at_time(token, ttl, current_time)[source]
Return type:

bytes

encrypt(data)[source]
Return type:

bytes

encrypt_at_time(data, current_time)[source]
Return type:

bytes

extract_timestamp(token)[source]
Return type:

int

classmethod generate_key()[source]
Return type:

bytes

exception spotted.handlers.job_handlers.Forbidden(message)[source]

Bases: TelegramError

Raised when the bot has not enough rights to perform the requested action.

Examples

Raw API Bot

Changed in version 20.0: This class was previously named Unauthorized.

class spotted.handlers.job_handlers.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
exception spotted.handlers.job_handlers.TelegramError(message)[source]

Bases: Exception

Base class for Telegram errors.

Tip

Objects of this type can be serialized via Python’s pickle module and pickled objects from one version of PTB are usually loadable in future versions. However, we can not guarantee that this compatibility will always be provided. At least a manual one-time conversion of the data may be needed on major updates of the library.

See also

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

message: str
class spotted.handlers.job_handlers.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

async spotted.handlers.job_handlers.clean_muted_users(context)[source]

Job called each day at 05:00 utc. Removed expired users mute records from the database

Parameters:

context (CallbackContext) – context passed by the jobqueue

async spotted.handlers.job_handlers.clean_pending_job(context)[source]

Job called each day at 05:00 utc. Automatically rejects all pending posts that are older than the chosen amount of hours

Parameters:

context (CallbackContext) – context passed by the jobqueue

class spotted.handlers.job_handlers.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().

async spotted.handlers.job_handlers.db_backup_job(context)[source]

Job called each day at 05:00 utc. Automatically upload and send last version of db for backup

Parameters:

context (CallbackContext) – context passed by the jobqueue

spotted.handlers.job_handlers.get_backup()[source]

Get the database backup, either encrypted or not. When the crypto_key setting is set, the backup is encrypted with Fernet, otherwise it’s returned as is, in plaintext.

Returns:

bytes – bytes of the backup file, either encrypted or not

spotted.handlers.job_handlers.get_updated_backup_path()[source]

Get the path of the database backup file, applying some transformations if needed. If backup_keep_pending is set to False, it creates a copy of the database file and drops the pending_post table from the copy, so the backup won’t contain any pending post.

Returns:

str – path of the database backup file

spotted.handlers.job_handlers.get_zip_backup()[source]

Zip the database file and return the bytes of the zip file, optionally encrypting it with a password if crypto_key is set in the settings. It is called if zip_backup is set to True in the settings.

Returns:

bytes – bytes of the (possibly encrypted) zip file

class spotted.handlers.job_handlers.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.

class spotted.handlers.job_handlers.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.handlers.mute module

/mute command

class spotted.handlers.mute.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.mute.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.handlers.mute.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.mute.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
class spotted.handlers.mute.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

async spotted.handlers.mute.mute_cmd(update, context)[source]

Handles the /mute command. Mute a user by replying to one of his message in the comment group with /mute <n_days> :type update: Update :param update: update event :type context: CallbackContext :param context: context passed by the handler

spotted.handlers.purge module

/purge command

class spotted.handlers.purge.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.purge.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.handlers.purge.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.purge.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
async spotted.handlers.purge.purge_cmd(update, context)[source]

Handles the /purge command. Deletes all posts and the related votes in the database whose actual telegram message could not be found

Parameters:
spotted.handlers.purge.sleep(seconds)

Delay execution for a given number of seconds. The argument may be a floating-point number for subsecond precision.

spotted.handlers.reload module

/reload command

class spotted.handlers.reload.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.reload.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.handlers.reload.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.reload.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
async spotted.handlers.reload.reload_cmd(update, context)[source]

Handles the /reload command. Reload the configuration file, updating the bot’s settings. This incudes both the _settings.yaml_ and the _autorereply.yaml_ file. This way the bot can be updated without restarting it.

In actuality, the current singleton is destroyed and a new one is created as soon as a configuration request is deemed necessary.

Parameters:

Warning

Loading different configurations may cause inconsistencies in live conversations.

spotted.handlers.reply module

/reply command

class spotted.handlers.reply.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.reply.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.reply.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.handlers.reply.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.handlers.reply.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
async spotted.handlers.reply.reply_cmd(update, context)[source]

Handles the /reply command. Send a message to a user by replying to one of his pending posts with /reply + the message you want to send

Parameters:

spotted.handlers.report_spot module

report callback

class spotted.handlers.report_spot.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.report_spot.CallbackQueryHandler(callback, pattern=None, game_pattern=None, block=True)[source]

Bases: BaseHandler[Update, CCT, RT]

Handler class to handle Telegram callback queries. Optionally based on a regex.

Read the documentation of the re module for more information.

Note

  • If your bot allows arbitrary objects as ~telegram.InlineKeyboardButton.callback_data, it may happen that the original callback_data for the incoming telegram.CallbackQuery can not be found. This is the case when either a malicious client tempered with the telegram.CallbackQuery.data or the data was simply dropped from cache or not persisted. In these cases, an instance of telegram.ext.InvalidCallbackData will be set as telegram.CallbackQuery.data.

    Added in version 13.6.

  • If neither pattern nor game_pattern is set, any CallbackQuery will be handled. If only pattern is set, queries with game_short_name will not be considered and vice versa. If both patterns are set, queries with either :attr: ~telegram.CallbackQuery.game_short_name or data matching the defined pattern will be handled

    Added in version 21.5.

Warning

When setting block to False, you cannot rely on adding custom attributes to telegram.ext.CallbackContext. See its docs for more info.

Parameters:
callback

The callback function for this handler.

Type:

coroutine function

pattern

Optional. Regex pattern, callback or type to test telegram.CallbackQuery.data against.

Changed in version 13.6: Added support for arbitrary callback data.

Type:

re.Pattern | callable | type

game_pattern

Optional. Regex pattern to test telegram.CallbackQuery.game_short_name

Type:

re.Pattern

block

Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update().

Type:

bool

check_update(update)[source]

Determines whether an update should be passed to this handler’s callback.

Parameters:

update (object) – Incoming update.

Returns:

bool | object | Nonebool

collect_additional_context(context, update, application, check_result)[source]

Add the result of re.match(pattern, update.callback_query.data) to CallbackContext.matches as list with one element.

Return type:

None

game_pattern: str | Pattern[str] | None
pattern: str | Pattern[str] | type | Callable[[object], bool | None] | None
class spotted.handlers.report_spot.CommandHandler(command, callback, filters=None, block=True, has_args=None)[source]

Bases: BaseHandler[Update, CCT, RT]

Handler class to handle Telegram commands.

Commands are Telegram messages that start with a telegram.MessageEntity.BOT_COMMAND (so with /, optionally followed by an @ and the bot’s name and/or some additional text). The handler will add a list to the CallbackContext named CallbackContext.args. It will contain a list of strings, which is the text following the command split on single or consecutive whitespace characters.

By default, the handler listens to messages as well as edited messages. To change this behavior use ~filters.UpdateType.EDITED_MESSAGE in the filter argument.

Note

CommandHandler does not handle (edited) channel posts and does not handle commands that are part of a caption. Please use MessageHandler with a suitable combination of filters (e.g. telegram.ext.filters.UpdateType.CHANNEL_POSTS, telegram.ext.filters.CAPTION and telegram.ext.filters.Regex) to handle those messages.

Note

If you want to support a different entity in the beginning, e.g. if a command message is wrapped in a telegram.MessageEntity.CODE, use the telegram.ext.PrefixHandler.

Warning

When setting block to False, you cannot rely on adding custom attributes to telegram.ext.CallbackContext. See its docs for more info.

Examples

  • Timer Bot

  • Error Handler Bot

Changed in version 20.0:

  • Renamed the attribute command to commands, which now is always a frozenset

  • Updating the commands this handler listens to is no longer possible.

Parameters:
  • command (str | Collection[str]) – The command or list of commands this handler should listen for. Case-insensitive. Limitations are the same as for telegram.BotCommand.command.

  • callback (Callable[[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])], Coroutine[Any, Any, TypeVar(RT)]]) –

    The callback function for this handler. Will be called when check_update() has determined that an update should be processed by this handler. Callback signature:

    async def callback(update: Update, context: CallbackContext)
    

    The return value of the callback is usually ignored except for the special case of telegram.ext.ConversationHandler.

  • filters (BaseFilter | None, default: None) – A filter inheriting from telegram.ext.filters.BaseFilter. Standard filters can be found in telegram.ext.filters. Filters can be combined using bitwise operators (& for and, | for or, ~ for not)

  • block (bool | DefaultValue[DVValueType], default: True) –

    Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update(). Defaults to True.

    See also

    Concurrency

  • has_args (bool | int | None, default: None) –

    Determines whether the command handler should process the update or not. If True, the handler will process any non-zero number of args. If False, the handler will only process if there are no args. if int, the handler will only process if there are exactly that many args. Defaults to None, which means the handler will process any or no args.

    Added in version 20.5.

Raises:

ValueError – When the command is too long or has illegal chars.

commands

The set of commands this handler should listen for.

Type:

frozenset[str]

callback

The callback function for this handler.

Type:

coroutine function

filters

Optional. Only allow updates with these filters.

Type:

telegram.ext.filters.BaseFilter

block

Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update().

Type:

bool

has_args

Optional argument, otherwise all implementations of CommandHandler will break. Defaults to None, which means the handler will process any args or no args.

Added in version 20.5.

Type:

bool | int | None

check_update(update)[source]

Determines whether an update should be passed to this handler’s callback.

Parameters:

update (object) – Incoming update.

Returns:

The list of args for the handler.

Returns:

bool | tuple[list[str], bool | dict[str, list[Any]] | None] | None

collect_additional_context(context, update, application, check_result)[source]

Add text after the command to CallbackContext.args as list, split on single whitespaces and add output of data filters to CallbackContext as well.

Return type:

None

commands: frozenset[str]
filters: filters_module.BaseFilter
has_args: bool | int | None
class spotted.handlers.report_spot.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.handlers.report_spot.ConversationHandler(entry_points, states, fallbacks, allow_reentry=False, per_chat=True, per_user=True, per_message=False, conversation_timeout=None, name=None, persistent=False, map_to_parent=None, block=True)[source]

Bases: BaseHandler[Update, CCT, object]

A handler to hold a conversation with a single or multiple users through Telegram updates by managing three collections of other handlers.

Warning

ConversationHandler heavily relies on incoming updates being processed one by one. When using this handler, telegram.ext.ApplicationBuilder.concurrent_updates should be set to False.

Note

ConversationHandler will only accept updates that are (subclass-)instances of telegram.Update. This is, because depending on the per_user and per_chat, ConversationHandler relies on telegram.Update.effective_user and/or telegram.Update.effective_chat in order to determine which conversation an update should belong to. For per_message=True, ConversationHandler uses update.callback_query.message.message_id when per_chat=True and update.callback_query.inline_message_id when per_chat=False. For a more detailed explanation, please see our FAQ.

Finally, ConversationHandler, does not handle (edited) channel posts.

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

The second collection, a dict named states, contains the different conversation steps and one or more associated handlers that should be used if the user sends a message when the conversation with them is currently in that state. Here you can also define a state for TIMEOUT to define the behavior when conversation_timeout is exceeded, and a state for WAITING to define behavior when a new update is received while the previous block=False handler is not finished.

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

To change the state of conversation, the callback function of a handler must return the new state after responding to the user. If it does not return anything (returning None by default), the state will not change. If an entry point callback function returns None, the conversation ends immediately after the execution of this callback function. To end the conversation, the callback function must return END or -1. To handle the conversation timeout, use handler TIMEOUT or -2. Finally, telegram.ext.ApplicationHandlerStop can be used in conversations as described in its documentation.

Note

In each of the described collections of handlers, a handler may in turn be a ConversationHandler. In that case, the child ConversationHandler should have the attribute map_to_parent which allows returning to the parent conversation at specified states within the child conversation.

Note that the keys in map_to_parent must not appear as keys in states attribute or else the latter will be ignored. You may map END to one of the parents states to continue the parent conversation after the child conversation has ended or even map a state to END to end the parent conversation from within the child conversation. For an example on nested ConversationHandler s, see examples.nestedconversationbot.

Examples

  • Conversation Bot

  • Conversation Bot 2

  • Nested Conversation Bot

  • Persistent Conversation Bot

Parameters:
  • entry_points (list[BaseHandler[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), object]]) – A list of BaseHandler objects that can trigger the start of the conversation. The first handler whose check_update() method returns True will be used. If all return False, the update is not handled.

  • states (dict[object, list[BaseHandler[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), object]]]) – A dict that defines the different states of conversation a user can be in and one or more associated BaseHandler objects that should be used in that state. The first handler whose check_update() method returns True will be used.

  • fallbacks (list[BaseHandler[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), object]]) – A list of handlers that might be used if the user is in a conversation, but every handler for their current state returned False on check_update(). The first handler which check_update() method returns True will be used. If all return False, the update is not handled.

  • allow_reentry (bool, default: False) – If set to True, a user that is currently in a conversation can restart the conversation by triggering one of the entry points. Default is False.

  • per_chat (bool, default: True) – If the conversation key should contain the Chat’s ID. Default is True.

  • per_user (bool, default: True) – If the conversation key should contain the User’s ID. Default is True.

  • per_message (bool, default: False) – If the conversation key should contain the Message’s ID. Default is False.

  • conversation_timeout (float | timedelta | None, default: None) –

    When this handler is inactive more than this timeout (in seconds), it will be automatically ended. If this value is 0 or None (default), there will be no timeout. The last received update and the corresponding context will be handled by ALL the handler’s whose check_update() method returns True that are in the state ConversationHandler.TIMEOUT.

    Caution

    • This feature relies on the telegram.ext.Application.job_queue being set and hence requires that the dependencies that telegram.ext.JobQueue relies on are installed.

    • Using conversation_timeout with nested conversations is currently not supported. You can still try to use it, but it will likely behave differently from what you expect.

  • name (str | None, default: None) – The name for this conversation handler. Required for persistence.

  • persistent (bool, default: False) –

    If the conversation’s dict for this handler should be saved. name is required and persistence has to be set in Application.

    Changed in version 20.0: Was previously named as persistence.

  • map_to_parent (dict[object, object] | None, default: None) – A dict that can be used to instruct a child conversation handler to transition into a mapped state on its parent conversation handler in place of a specified nested state.

  • block (bool | DefaultValue[DVValueType], default: True) –

    Pass False or True to set a default value for the BaseHandler.block setting of all handlers (in entry_points, states and fallbacks). The resolution order for checking if a handler should be run non-blocking is:

    1. telegram.ext.BaseHandler.block (if set)

    2. the value passed to this parameter (if any)

    3. telegram.ext.Defaults.block (if defaults are used)

    See also

    Concurrency

    Changed in version 20.0: No longer overrides the handlers settings. Resolution order was changed.

Raises:

ValueError – If persistent is used but name was not set, or when per_message, per_chat, per_user are all False.

block

Determines whether the callback will run in a blocking way. Always True since conversation handlers handle any non-blocking callbacks internally.

Type:

bool

END: Final[int] = -1

Used as a constant to return when a conversation is ended.

Type:

int

TIMEOUT: Final[int] = -2

Used as a constant to handle state when a conversation is timed out (exceeded conversation_timeout).

Type:

int

WAITING: Final[int] = -3

Used as a constant to handle state when a conversation is still waiting on the previous block=False handler to finish.

Type:

int

property allow_reentry: bool

Determines if a user can restart a conversation with an entry point.

Type:

bool

check_update(update)[source]

Determines whether an update should be handled by this conversation handler, and if so in which state the conversation currently is.

Parameters:

update (object) – Incoming update.

Returns:

tuple[object, tuple[int | str, ...], BaseHandler[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), object], object] | Nonebool

property conversation_timeout: float | timedelta | None

Optional. When this handler is inactive more than this timeout (in seconds), it will be automatically ended.

Type:

float | datetime.timedelta

property entry_points: list[BaseHandler[Update, CCT, object]]

A list of BaseHandler objects that can trigger the start of the conversation.

Type:

list[telegram.ext.BaseHandler]

property fallbacks: list[BaseHandler[Update, CCT, object]]

A list of handlers that might be used if the user is in a conversation, but every handler for their current state returned False on check_update().

Type:

list[telegram.ext.BaseHandler]

async handle_update(update, application, check_result, context)[source]

Send the update to the callback for the current state and BaseHandler

Parameters:
  • check_result (tuple[object, tuple[int | str, ...], BaseHandler[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), object], object]) – The result from check_update(). For this handler it’s a tuple of the conversation state, key, handler, and the handler’s check result.

  • update (Update) – Incoming telegram update.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – Application that originated the update.

  • context (TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])) – The context as provided by the application.

Return type:

object | None

property map_to_parent: dict[object, object] | None

Optional. A dict that can be used to instruct a nested ConversationHandler to transition into a mapped state on its parent ConversationHandler in place of a specified nested state.

Type:

dict[object, object]

property name: str | None

Optional. The name for this ConversationHandler.

Type:

str

property per_chat: bool

If the conversation key should contain the Chat’s ID.

Type:

bool

property per_message: bool

If the conversation key should contain the message’s ID.

Type:

bool

property per_user: bool

If the conversation key should contain the User’s ID.

Type:

bool

property persistent: bool

Optional. If the conversations dict for this handler should be saved. name is required and persistence has to be set in Application.

Type:

bool

property states: dict[object, list[BaseHandler[Update, CCT, object]]]

A dict that defines the different states of conversation a user can be in and one or more associated BaseHandler objects that should be used in that state.

Type:

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

timeout_jobs: dict[ConversationKey, Job[Any]]
class spotted.handlers.report_spot.ConversationState(*values)[source]

Bases: Enum

Enum for the states of the conversation. The end state must have value -1, since it is the convention used by the ConversationHandler to terminate the conversation.

END = -1
POSTING = 1
POSTING_CONFIRM = 3
POSTING_PREVIEW = 2
REPORTING_SPOT = 4
REPORTING_USER = 5
REPORTING_USER_REASON = 6
SENDING_USER_REPORT = 7
class spotted.handlers.report_spot.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

exception spotted.handlers.report_spot.Forbidden(message)[source]

Bases: TelegramError

Raised when the bot has not enough rights to perform the requested action.

Examples

Raw API Bot

Changed in version 20.0: This class was previously named Unauthorized.

class spotted.handlers.report_spot.MessageHandler(filters, callback, block=True)[source]

Bases: BaseHandler[Update, CCT, RT]

Handler class to handle Telegram messages. They might contain text, media or status updates.

Warning

When setting block to False, you cannot rely on adding custom attributes to telegram.ext.CallbackContext. See its docs for more info.

Parameters:
  • filters (BaseFilter | None) –

    A filter inheriting from telegram.ext.filters.BaseFilter. Standard filters can be found in telegram.ext.filters. Filters can be combined using bitwise operators (& for and, | for or, ~ for not). Passing None is a shortcut to passing telegram.ext.filters.ALL.

    See also

    Advanced Filters <Extensions---Advanced-Filters>

  • callback (Callable[[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])], Coroutine[Any, Any, TypeVar(RT)]]) –

    The callback function for this handler. Will be called when check_update() has determined that an update should be processed by this handler. Callback signature:

    async def callback(update: Update, context: CallbackContext)
    

    The return value of the callback is usually ignored except for the special case of telegram.ext.ConversationHandler.

  • block (bool | DefaultValue[DVValueType], default: True) –

    Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update(). Defaults to True.

    See also

    Concurrency

filters

Only allow updates with these Filters. See telegram.ext.filters for a full list of all available filters.

Type:

telegram.ext.filters.BaseFilter

callback

The callback function for this handler.

Type:

coroutine function

block

Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update().

Type:

bool

check_update(update)[source]

Determines whether an update should be passed to this handler’s callback.

Parameters:

update (object) – Incoming update.

Returns:

bool | dict[str, list[Any]] | Nonebool

collect_additional_context(context, update, application, check_result)[source]

Adds possible output of data filters to the CallbackContext.

Return type:

None

filters: filters_module.BaseFilter
class spotted.handlers.report_spot.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.handlers.report_spot.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
class spotted.handlers.report_spot.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.handlers.report_spot.conv_cancel(family)[source]

Creates a function used to handle the /cancel command in the conversation. Invoking /cancel will exit the conversation immediately

Parameters:

family (str) – family of the command

Returns:

Callable[[Any, Any], Coroutine[Any, Any, int]] – function used to handle the /cancel command

async spotted.handlers.report_spot.report_spot_callback(update, context)[source]

Handles the report callback.

Parameters:
Returns:

int – next state of the conversation

spotted.handlers.report_spot.report_spot_conv_handler()[source]

Creates the report (user) conversation handler. The states are:

  • reporting_spot: submit the reason of the report. Expects text

Returns:

ConversationHandler – conversation handler

async spotted.handlers.report_spot.report_spot_msg(update, context)[source]

Handles the reply to the key “Report”. Checks the message the user wants to report, and goes to the final step

Parameters:
Returns:

int – next state of the conversation

spotted.handlers.report_user module

/report command

class spotted.handlers.report_user.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.report_user.CommandHandler(command, callback, filters=None, block=True, has_args=None)[source]

Bases: BaseHandler[Update, CCT, RT]

Handler class to handle Telegram commands.

Commands are Telegram messages that start with a telegram.MessageEntity.BOT_COMMAND (so with /, optionally followed by an @ and the bot’s name and/or some additional text). The handler will add a list to the CallbackContext named CallbackContext.args. It will contain a list of strings, which is the text following the command split on single or consecutive whitespace characters.

By default, the handler listens to messages as well as edited messages. To change this behavior use ~filters.UpdateType.EDITED_MESSAGE in the filter argument.

Note

CommandHandler does not handle (edited) channel posts and does not handle commands that are part of a caption. Please use MessageHandler with a suitable combination of filters (e.g. telegram.ext.filters.UpdateType.CHANNEL_POSTS, telegram.ext.filters.CAPTION and telegram.ext.filters.Regex) to handle those messages.

Note

If you want to support a different entity in the beginning, e.g. if a command message is wrapped in a telegram.MessageEntity.CODE, use the telegram.ext.PrefixHandler.

Warning

When setting block to False, you cannot rely on adding custom attributes to telegram.ext.CallbackContext. See its docs for more info.

Examples

  • Timer Bot

  • Error Handler Bot

Changed in version 20.0:

  • Renamed the attribute command to commands, which now is always a frozenset

  • Updating the commands this handler listens to is no longer possible.

Parameters:
  • command (str | Collection[str]) – The command or list of commands this handler should listen for. Case-insensitive. Limitations are the same as for telegram.BotCommand.command.

  • callback (Callable[[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])], Coroutine[Any, Any, TypeVar(RT)]]) –

    The callback function for this handler. Will be called when check_update() has determined that an update should be processed by this handler. Callback signature:

    async def callback(update: Update, context: CallbackContext)
    

    The return value of the callback is usually ignored except for the special case of telegram.ext.ConversationHandler.

  • filters (BaseFilter | None, default: None) – A filter inheriting from telegram.ext.filters.BaseFilter. Standard filters can be found in telegram.ext.filters. Filters can be combined using bitwise operators (& for and, | for or, ~ for not)

  • block (bool | DefaultValue[DVValueType], default: True) –

    Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update(). Defaults to True.

    See also

    Concurrency

  • has_args (bool | int | None, default: None) –

    Determines whether the command handler should process the update or not. If True, the handler will process any non-zero number of args. If False, the handler will only process if there are no args. if int, the handler will only process if there are exactly that many args. Defaults to None, which means the handler will process any or no args.

    Added in version 20.5.

Raises:

ValueError – When the command is too long or has illegal chars.

commands

The set of commands this handler should listen for.

Type:

frozenset[str]

callback

The callback function for this handler.

Type:

coroutine function

filters

Optional. Only allow updates with these filters.

Type:

telegram.ext.filters.BaseFilter

block

Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update().

Type:

bool

has_args

Optional argument, otherwise all implementations of CommandHandler will break. Defaults to None, which means the handler will process any args or no args.

Added in version 20.5.

Type:

bool | int | None

check_update(update)[source]

Determines whether an update should be passed to this handler’s callback.

Parameters:

update (object) – Incoming update.

Returns:

The list of args for the handler.

Returns:

bool | tuple[list[str], bool | dict[str, list[Any]] | None] | None

collect_additional_context(context, update, application, check_result)[source]

Add text after the command to CallbackContext.args as list, split on single whitespaces and add output of data filters to CallbackContext as well.

Return type:

None

commands: frozenset[str]
filters: filters_module.BaseFilter
has_args: bool | int | None
class spotted.handlers.report_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.handlers.report_user.ConversationHandler(entry_points, states, fallbacks, allow_reentry=False, per_chat=True, per_user=True, per_message=False, conversation_timeout=None, name=None, persistent=False, map_to_parent=None, block=True)[source]

Bases: BaseHandler[Update, CCT, object]

A handler to hold a conversation with a single or multiple users through Telegram updates by managing three collections of other handlers.

Warning

ConversationHandler heavily relies on incoming updates being processed one by one. When using this handler, telegram.ext.ApplicationBuilder.concurrent_updates should be set to False.

Note

ConversationHandler will only accept updates that are (subclass-)instances of telegram.Update. This is, because depending on the per_user and per_chat, ConversationHandler relies on telegram.Update.effective_user and/or telegram.Update.effective_chat in order to determine which conversation an update should belong to. For per_message=True, ConversationHandler uses update.callback_query.message.message_id when per_chat=True and update.callback_query.inline_message_id when per_chat=False. For a more detailed explanation, please see our FAQ.

Finally, ConversationHandler, does not handle (edited) channel posts.

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

The second collection, a dict named states, contains the different conversation steps and one or more associated handlers that should be used if the user sends a message when the conversation with them is currently in that state. Here you can also define a state for TIMEOUT to define the behavior when conversation_timeout is exceeded, and a state for WAITING to define behavior when a new update is received while the previous block=False handler is not finished.

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

To change the state of conversation, the callback function of a handler must return the new state after responding to the user. If it does not return anything (returning None by default), the state will not change. If an entry point callback function returns None, the conversation ends immediately after the execution of this callback function. To end the conversation, the callback function must return END or -1. To handle the conversation timeout, use handler TIMEOUT or -2. Finally, telegram.ext.ApplicationHandlerStop can be used in conversations as described in its documentation.

Note

In each of the described collections of handlers, a handler may in turn be a ConversationHandler. In that case, the child ConversationHandler should have the attribute map_to_parent which allows returning to the parent conversation at specified states within the child conversation.

Note that the keys in map_to_parent must not appear as keys in states attribute or else the latter will be ignored. You may map END to one of the parents states to continue the parent conversation after the child conversation has ended or even map a state to END to end the parent conversation from within the child conversation. For an example on nested ConversationHandler s, see examples.nestedconversationbot.

Examples

  • Conversation Bot

  • Conversation Bot 2

  • Nested Conversation Bot

  • Persistent Conversation Bot

Parameters:
  • entry_points (list[BaseHandler[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), object]]) – A list of BaseHandler objects that can trigger the start of the conversation. The first handler whose check_update() method returns True will be used. If all return False, the update is not handled.

  • states (dict[object, list[BaseHandler[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), object]]]) – A dict that defines the different states of conversation a user can be in and one or more associated BaseHandler objects that should be used in that state. The first handler whose check_update() method returns True will be used.

  • fallbacks (list[BaseHandler[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), object]]) – A list of handlers that might be used if the user is in a conversation, but every handler for their current state returned False on check_update(). The first handler which check_update() method returns True will be used. If all return False, the update is not handled.

  • allow_reentry (bool, default: False) – If set to True, a user that is currently in a conversation can restart the conversation by triggering one of the entry points. Default is False.

  • per_chat (bool, default: True) – If the conversation key should contain the Chat’s ID. Default is True.

  • per_user (bool, default: True) – If the conversation key should contain the User’s ID. Default is True.

  • per_message (bool, default: False) – If the conversation key should contain the Message’s ID. Default is False.

  • conversation_timeout (float | timedelta | None, default: None) –

    When this handler is inactive more than this timeout (in seconds), it will be automatically ended. If this value is 0 or None (default), there will be no timeout. The last received update and the corresponding context will be handled by ALL the handler’s whose check_update() method returns True that are in the state ConversationHandler.TIMEOUT.

    Caution

    • This feature relies on the telegram.ext.Application.job_queue being set and hence requires that the dependencies that telegram.ext.JobQueue relies on are installed.

    • Using conversation_timeout with nested conversations is currently not supported. You can still try to use it, but it will likely behave differently from what you expect.

  • name (str | None, default: None) – The name for this conversation handler. Required for persistence.

  • persistent (bool, default: False) –

    If the conversation’s dict for this handler should be saved. name is required and persistence has to be set in Application.

    Changed in version 20.0: Was previously named as persistence.

  • map_to_parent (dict[object, object] | None, default: None) – A dict that can be used to instruct a child conversation handler to transition into a mapped state on its parent conversation handler in place of a specified nested state.

  • block (bool | DefaultValue[DVValueType], default: True) –

    Pass False or True to set a default value for the BaseHandler.block setting of all handlers (in entry_points, states and fallbacks). The resolution order for checking if a handler should be run non-blocking is:

    1. telegram.ext.BaseHandler.block (if set)

    2. the value passed to this parameter (if any)

    3. telegram.ext.Defaults.block (if defaults are used)

    See also

    Concurrency

    Changed in version 20.0: No longer overrides the handlers settings. Resolution order was changed.

Raises:

ValueError – If persistent is used but name was not set, or when per_message, per_chat, per_user are all False.

block

Determines whether the callback will run in a blocking way. Always True since conversation handlers handle any non-blocking callbacks internally.

Type:

bool

END: Final[int] = -1

Used as a constant to return when a conversation is ended.

Type:

int

TIMEOUT: Final[int] = -2

Used as a constant to handle state when a conversation is timed out (exceeded conversation_timeout).

Type:

int

WAITING: Final[int] = -3

Used as a constant to handle state when a conversation is still waiting on the previous block=False handler to finish.

Type:

int

property allow_reentry: bool

Determines if a user can restart a conversation with an entry point.

Type:

bool

check_update(update)[source]

Determines whether an update should be handled by this conversation handler, and if so in which state the conversation currently is.

Parameters:

update (object) – Incoming update.

Returns:

tuple[object, tuple[int | str, ...], BaseHandler[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), object], object] | Nonebool

property conversation_timeout: float | timedelta | None

Optional. When this handler is inactive more than this timeout (in seconds), it will be automatically ended.

Type:

float | datetime.timedelta

property entry_points: list[BaseHandler[Update, CCT, object]]

A list of BaseHandler objects that can trigger the start of the conversation.

Type:

list[telegram.ext.BaseHandler]

property fallbacks: list[BaseHandler[Update, CCT, object]]

A list of handlers that might be used if the user is in a conversation, but every handler for their current state returned False on check_update().

Type:

list[telegram.ext.BaseHandler]

async handle_update(update, application, check_result, context)[source]

Send the update to the callback for the current state and BaseHandler

Parameters:
  • check_result (tuple[object, tuple[int | str, ...], BaseHandler[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), object], object]) – The result from check_update(). For this handler it’s a tuple of the conversation state, key, handler, and the handler’s check result.

  • update (Update) – Incoming telegram update.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – Application that originated the update.

  • context (TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])) – The context as provided by the application.

Return type:

object | None

property map_to_parent: dict[object, object] | None

Optional. A dict that can be used to instruct a nested ConversationHandler to transition into a mapped state on its parent ConversationHandler in place of a specified nested state.

Type:

dict[object, object]

property name: str | None

Optional. The name for this ConversationHandler.

Type:

str

property per_chat: bool

If the conversation key should contain the Chat’s ID.

Type:

bool

property per_message: bool

If the conversation key should contain the message’s ID.

Type:

bool

property per_user: bool

If the conversation key should contain the User’s ID.

Type:

bool

property persistent: bool

Optional. If the conversations dict for this handler should be saved. name is required and persistence has to be set in Application.

Type:

bool

property states: dict[object, list[BaseHandler[Update, CCT, object]]]

A dict that defines the different states of conversation a user can be in and one or more associated BaseHandler objects that should be used in that state.

Type:

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

timeout_jobs: dict[ConversationKey, Job[Any]]
class spotted.handlers.report_user.ConversationState(*values)[source]

Bases: Enum

Enum for the states of the conversation. The end state must have value -1, since it is the convention used by the ConversationHandler to terminate the conversation.

END = -1
POSTING = 1
POSTING_CONFIRM = 3
POSTING_PREVIEW = 2
REPORTING_SPOT = 4
REPORTING_USER = 5
REPORTING_USER_REASON = 6
SENDING_USER_REPORT = 7
class spotted.handlers.report_user.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.report_user.MessageHandler(filters, callback, block=True)[source]

Bases: BaseHandler[Update, CCT, RT]

Handler class to handle Telegram messages. They might contain text, media or status updates.

Warning

When setting block to False, you cannot rely on adding custom attributes to telegram.ext.CallbackContext. See its docs for more info.

Parameters:
  • filters (BaseFilter | None) –

    A filter inheriting from telegram.ext.filters.BaseFilter. Standard filters can be found in telegram.ext.filters. Filters can be combined using bitwise operators (& for and, | for or, ~ for not). Passing None is a shortcut to passing telegram.ext.filters.ALL.

    See also

    Advanced Filters <Extensions---Advanced-Filters>

  • callback (Callable[[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])], Coroutine[Any, Any, TypeVar(RT)]]) –

    The callback function for this handler. Will be called when check_update() has determined that an update should be processed by this handler. Callback signature:

    async def callback(update: Update, context: CallbackContext)
    

    The return value of the callback is usually ignored except for the special case of telegram.ext.ConversationHandler.

  • block (bool | DefaultValue[DVValueType], default: True) –

    Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update(). Defaults to True.

    See also

    Concurrency

filters

Only allow updates with these Filters. See telegram.ext.filters for a full list of all available filters.

Type:

telegram.ext.filters.BaseFilter

callback

The callback function for this handler.

Type:

coroutine function

block

Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update().

Type:

bool

check_update(update)[source]

Determines whether an update should be passed to this handler’s callback.

Parameters:

update (object) – Incoming update.

Returns:

bool | dict[str, list[Any]] | Nonebool

collect_additional_context(context, update, application, check_result)[source]

Adds possible output of data filters to the CallbackContext.

Return type:

None

filters: filters_module.BaseFilter
class spotted.handlers.report_user.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.handlers.report_user.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
spotted.handlers.report_user.conv_cancel(family)[source]

Creates a function used to handle the /cancel command in the conversation. Invoking /cancel will exit the conversation immediately

Parameters:

family (str) – family of the command

Returns:

Callable[[Any, Any], Coroutine[Any, Any, int]] – function used to handle the /cancel command

async spotted.handlers.report_user.report_cmd(update, context)[source]

Handles the reply to the key “Report”. Checks the message the user wants to report

Parameters:
Returns:

int – next state of the conversation

spotted.handlers.report_user.report_user_conv_handler()[source]

Creates the /report (user) conversation handler. The states are:

  • reporting_user: submit the username to report. Expects text starting with @ and without spaces in between

  • reporting_user_reason: submit the reason of the report. Expects text

Returns:

ConversationHandler – conversation handler

async spotted.handlers.report_user.report_user_msg(update, context)[source]

Handles the reply to the /report command after sent the @username. Checks the the user wants to report, and goes to ask the reason

Parameters:
Returns:

int – next state of the conversation

async spotted.handlers.report_user.report_user_sent_msg(update, context)[source]

Handles the reply to the /report command after sent the reason. Checks the the user wants to report, and goes to final step

Parameters:
Returns:

int – next state of the conversation

spotted.handlers.rules module

/rules command

class spotted.handlers.rules.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.rules.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.rules.ParseMode(*values)[source]

Bases: StringEnum

This enum contains the available parse modes. The enum members of this enumeration are instances of str and can be treated as such.

Added in version 20.0.

HTML = 'HTML'

HTML parse mode.

Type:

str

MARKDOWN = 'Markdown'

Markdown parse mode.

Note

MARKDOWN is a legacy mode, retained by Telegram for backward compatibility. You should use MARKDOWN_V2 instead.

Type:

str

MARKDOWN_V2 = 'MarkdownV2'

Markdown parse mode version 2.

Type:

str

class spotted.handlers.rules.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
spotted.handlers.rules.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

async spotted.handlers.rules.rules_cmd(update, context)[source]

Handles the /rules command. Sends a message containing the rules

Parameters:

spotted.handlers.sban module

/sban command

class spotted.handlers.sban.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.sban.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

exception spotted.handlers.sban.TelegramError(message)[source]

Bases: Exception

Base class for Telegram errors.

Tip

Objects of this type can be serialized via Python’s pickle module and pickled objects from one version of PTB are usually loadable in future versions. However, we can not guarantee that this compatibility will always be provided. At least a manual one-time conversion of the data may be needed on major updates of the library.

See also

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

message: str
class spotted.handlers.sban.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
class spotted.handlers.sban.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.handlers.sban.get_user_by_id_or_index(user_id_or_idx, users_list)[source]

Get a user either by their user_id or by their index in a given list of users. The index is specified by prefixing the number with a ‘#’ character. For example, ‘#0’ would refer to the first user in the list. On the other hand, if the input is a number without the ‘#’ prefix, it will be treated as a user_id.

Parameters:
  • user_id_or_idx (str) – The user_id or index to look for. If it starts with ‘#’, it will be treated as an index.

  • users_list (list[User]) – The list of users to search through when looking for an index.

Returns:

User | None – The User object corresponding to the given user_id or index, or None if no such user exists.

async spotted.handlers.sban.sban_cmd(update, context)[source]

Handles the /sban command. Sban a user by using this command and listing all the user_id to sban

Parameters:

spotted.handlers.settings module

/settings command

class spotted.handlers.settings.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.settings.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.settings.ParseMode(*values)[source]

Bases: StringEnum

This enum contains the available parse modes. The enum members of this enumeration are instances of str and can be treated as such.

Added in version 20.0.

HTML = 'HTML'

HTML parse mode.

Type:

str

MARKDOWN = 'Markdown'

Markdown parse mode.

Note

MARKDOWN is a legacy mode, retained by Telegram for backward compatibility. You should use MARKDOWN_V2 instead.

Type:

str

MARKDOWN_V2 = 'MarkdownV2'

Markdown parse mode version 2.

Type:

str

class spotted.handlers.settings.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
class spotted.handlers.settings.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.handlers.settings.get_settings_kb()[source]

Generates the InlineKeyboard to edit the settings

Returns:

InlineKeyboardMarkup – new inline keyboard

async spotted.handlers.settings.settings_callback(update, context)[source]

Handles the settings,[ anonimo | credit ] callback.

  • anonimo: Removes the user_id from the table of credited users, if present.

  • credit: Adds the user_id to the table of credited users, if it wasn’t already there.

Parameters:
async spotted.handlers.settings.settings_cmd(update, context)[source]

Handles the /settings command. Let’s the user choose whether his posts will be credited or not

Parameters:

spotted.handlers.spam_comment module

Anonym Comment on a post in the comment group

class spotted.handlers.spam_comment.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.spam_comment.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.handlers.spam_comment.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.spam_comment.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
async spotted.handlers.spam_comment.spam_comment_msg(update, context)[source]

Handles a spam comment on a post in the comment group. Deletes the original post and bans the user.

Parameters:
Return type:

None

spotted.handlers.spot module

/spot command

class spotted.handlers.spot.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.spot.CallbackQueryHandler(callback, pattern=None, game_pattern=None, block=True)[source]

Bases: BaseHandler[Update, CCT, RT]

Handler class to handle Telegram callback queries. Optionally based on a regex.

Read the documentation of the re module for more information.

Note

  • If your bot allows arbitrary objects as ~telegram.InlineKeyboardButton.callback_data, it may happen that the original callback_data for the incoming telegram.CallbackQuery can not be found. This is the case when either a malicious client tempered with the telegram.CallbackQuery.data or the data was simply dropped from cache or not persisted. In these cases, an instance of telegram.ext.InvalidCallbackData will be set as telegram.CallbackQuery.data.

    Added in version 13.6.

  • If neither pattern nor game_pattern is set, any CallbackQuery will be handled. If only pattern is set, queries with game_short_name will not be considered and vice versa. If both patterns are set, queries with either :attr: ~telegram.CallbackQuery.game_short_name or data matching the defined pattern will be handled

    Added in version 21.5.

Warning

When setting block to False, you cannot rely on adding custom attributes to telegram.ext.CallbackContext. See its docs for more info.

Parameters:
callback

The callback function for this handler.

Type:

coroutine function

pattern

Optional. Regex pattern, callback or type to test telegram.CallbackQuery.data against.

Changed in version 13.6: Added support for arbitrary callback data.

Type:

re.Pattern | callable | type

game_pattern

Optional. Regex pattern to test telegram.CallbackQuery.game_short_name

Type:

re.Pattern

block

Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update().

Type:

bool

check_update(update)[source]

Determines whether an update should be passed to this handler’s callback.

Parameters:

update (object) – Incoming update.

Returns:

bool | object | Nonebool

collect_additional_context(context, update, application, check_result)[source]

Add the result of re.match(pattern, update.callback_query.data) to CallbackContext.matches as list with one element.

Return type:

None

game_pattern: str | Pattern[str] | None
pattern: str | Pattern[str] | type | Callable[[object], bool | None] | None
class spotted.handlers.spot.CommandHandler(command, callback, filters=None, block=True, has_args=None)[source]

Bases: BaseHandler[Update, CCT, RT]

Handler class to handle Telegram commands.

Commands are Telegram messages that start with a telegram.MessageEntity.BOT_COMMAND (so with /, optionally followed by an @ and the bot’s name and/or some additional text). The handler will add a list to the CallbackContext named CallbackContext.args. It will contain a list of strings, which is the text following the command split on single or consecutive whitespace characters.

By default, the handler listens to messages as well as edited messages. To change this behavior use ~filters.UpdateType.EDITED_MESSAGE in the filter argument.

Note

CommandHandler does not handle (edited) channel posts and does not handle commands that are part of a caption. Please use MessageHandler with a suitable combination of filters (e.g. telegram.ext.filters.UpdateType.CHANNEL_POSTS, telegram.ext.filters.CAPTION and telegram.ext.filters.Regex) to handle those messages.

Note

If you want to support a different entity in the beginning, e.g. if a command message is wrapped in a telegram.MessageEntity.CODE, use the telegram.ext.PrefixHandler.

Warning

When setting block to False, you cannot rely on adding custom attributes to telegram.ext.CallbackContext. See its docs for more info.

Examples

  • Timer Bot

  • Error Handler Bot

Changed in version 20.0:

  • Renamed the attribute command to commands, which now is always a frozenset

  • Updating the commands this handler listens to is no longer possible.

Parameters:
  • command (str | Collection[str]) – The command or list of commands this handler should listen for. Case-insensitive. Limitations are the same as for telegram.BotCommand.command.

  • callback (Callable[[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])], Coroutine[Any, Any, TypeVar(RT)]]) –

    The callback function for this handler. Will be called when check_update() has determined that an update should be processed by this handler. Callback signature:

    async def callback(update: Update, context: CallbackContext)
    

    The return value of the callback is usually ignored except for the special case of telegram.ext.ConversationHandler.

  • filters (BaseFilter | None, default: None) – A filter inheriting from telegram.ext.filters.BaseFilter. Standard filters can be found in telegram.ext.filters. Filters can be combined using bitwise operators (& for and, | for or, ~ for not)

  • block (bool | DefaultValue[DVValueType], default: True) –

    Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update(). Defaults to True.

    See also

    Concurrency

  • has_args (bool | int | None, default: None) –

    Determines whether the command handler should process the update or not. If True, the handler will process any non-zero number of args. If False, the handler will only process if there are no args. if int, the handler will only process if there are exactly that many args. Defaults to None, which means the handler will process any or no args.

    Added in version 20.5.

Raises:

ValueError – When the command is too long or has illegal chars.

commands

The set of commands this handler should listen for.

Type:

frozenset[str]

callback

The callback function for this handler.

Type:

coroutine function

filters

Optional. Only allow updates with these filters.

Type:

telegram.ext.filters.BaseFilter

block

Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update().

Type:

bool

has_args

Optional argument, otherwise all implementations of CommandHandler will break. Defaults to None, which means the handler will process any args or no args.

Added in version 20.5.

Type:

bool | int | None

check_update(update)[source]

Determines whether an update should be passed to this handler’s callback.

Parameters:

update (object) – Incoming update.

Returns:

The list of args for the handler.

Returns:

bool | tuple[list[str], bool | dict[str, list[Any]] | None] | None

collect_additional_context(context, update, application, check_result)[source]

Add text after the command to CallbackContext.args as list, split on single whitespaces and add output of data filters to CallbackContext as well.

Return type:

None

commands: frozenset[str]
filters: filters_module.BaseFilter
has_args: bool | int | None
class spotted.handlers.spot.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.handlers.spot.ConversationHandler(entry_points, states, fallbacks, allow_reentry=False, per_chat=True, per_user=True, per_message=False, conversation_timeout=None, name=None, persistent=False, map_to_parent=None, block=True)[source]

Bases: BaseHandler[Update, CCT, object]

A handler to hold a conversation with a single or multiple users through Telegram updates by managing three collections of other handlers.

Warning

ConversationHandler heavily relies on incoming updates being processed one by one. When using this handler, telegram.ext.ApplicationBuilder.concurrent_updates should be set to False.

Note

ConversationHandler will only accept updates that are (subclass-)instances of telegram.Update. This is, because depending on the per_user and per_chat, ConversationHandler relies on telegram.Update.effective_user and/or telegram.Update.effective_chat in order to determine which conversation an update should belong to. For per_message=True, ConversationHandler uses update.callback_query.message.message_id when per_chat=True and update.callback_query.inline_message_id when per_chat=False. For a more detailed explanation, please see our FAQ.

Finally, ConversationHandler, does not handle (edited) channel posts.

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

The second collection, a dict named states, contains the different conversation steps and one or more associated handlers that should be used if the user sends a message when the conversation with them is currently in that state. Here you can also define a state for TIMEOUT to define the behavior when conversation_timeout is exceeded, and a state for WAITING to define behavior when a new update is received while the previous block=False handler is not finished.

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

To change the state of conversation, the callback function of a handler must return the new state after responding to the user. If it does not return anything (returning None by default), the state will not change. If an entry point callback function returns None, the conversation ends immediately after the execution of this callback function. To end the conversation, the callback function must return END or -1. To handle the conversation timeout, use handler TIMEOUT or -2. Finally, telegram.ext.ApplicationHandlerStop can be used in conversations as described in its documentation.

Note

In each of the described collections of handlers, a handler may in turn be a ConversationHandler. In that case, the child ConversationHandler should have the attribute map_to_parent which allows returning to the parent conversation at specified states within the child conversation.

Note that the keys in map_to_parent must not appear as keys in states attribute or else the latter will be ignored. You may map END to one of the parents states to continue the parent conversation after the child conversation has ended or even map a state to END to end the parent conversation from within the child conversation. For an example on nested ConversationHandler s, see examples.nestedconversationbot.

Examples

  • Conversation Bot

  • Conversation Bot 2

  • Nested Conversation Bot

  • Persistent Conversation Bot

Parameters:
  • entry_points (list[BaseHandler[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), object]]) – A list of BaseHandler objects that can trigger the start of the conversation. The first handler whose check_update() method returns True will be used. If all return False, the update is not handled.

  • states (dict[object, list[BaseHandler[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), object]]]) – A dict that defines the different states of conversation a user can be in and one or more associated BaseHandler objects that should be used in that state. The first handler whose check_update() method returns True will be used.

  • fallbacks (list[BaseHandler[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), object]]) – A list of handlers that might be used if the user is in a conversation, but every handler for their current state returned False on check_update(). The first handler which check_update() method returns True will be used. If all return False, the update is not handled.

  • allow_reentry (bool, default: False) – If set to True, a user that is currently in a conversation can restart the conversation by triggering one of the entry points. Default is False.

  • per_chat (bool, default: True) – If the conversation key should contain the Chat’s ID. Default is True.

  • per_user (bool, default: True) – If the conversation key should contain the User’s ID. Default is True.

  • per_message (bool, default: False) – If the conversation key should contain the Message’s ID. Default is False.

  • conversation_timeout (float | timedelta | None, default: None) –

    When this handler is inactive more than this timeout (in seconds), it will be automatically ended. If this value is 0 or None (default), there will be no timeout. The last received update and the corresponding context will be handled by ALL the handler’s whose check_update() method returns True that are in the state ConversationHandler.TIMEOUT.

    Caution

    • This feature relies on the telegram.ext.Application.job_queue being set and hence requires that the dependencies that telegram.ext.JobQueue relies on are installed.

    • Using conversation_timeout with nested conversations is currently not supported. You can still try to use it, but it will likely behave differently from what you expect.

  • name (str | None, default: None) – The name for this conversation handler. Required for persistence.

  • persistent (bool, default: False) –

    If the conversation’s dict for this handler should be saved. name is required and persistence has to be set in Application.

    Changed in version 20.0: Was previously named as persistence.

  • map_to_parent (dict[object, object] | None, default: None) – A dict that can be used to instruct a child conversation handler to transition into a mapped state on its parent conversation handler in place of a specified nested state.

  • block (bool | DefaultValue[DVValueType], default: True) –

    Pass False or True to set a default value for the BaseHandler.block setting of all handlers (in entry_points, states and fallbacks). The resolution order for checking if a handler should be run non-blocking is:

    1. telegram.ext.BaseHandler.block (if set)

    2. the value passed to this parameter (if any)

    3. telegram.ext.Defaults.block (if defaults are used)

    See also

    Concurrency

    Changed in version 20.0: No longer overrides the handlers settings. Resolution order was changed.

Raises:

ValueError – If persistent is used but name was not set, or when per_message, per_chat, per_user are all False.

block

Determines whether the callback will run in a blocking way. Always True since conversation handlers handle any non-blocking callbacks internally.

Type:

bool

END: Final[int] = -1

Used as a constant to return when a conversation is ended.

Type:

int

TIMEOUT: Final[int] = -2

Used as a constant to handle state when a conversation is timed out (exceeded conversation_timeout).

Type:

int

WAITING: Final[int] = -3

Used as a constant to handle state when a conversation is still waiting on the previous block=False handler to finish.

Type:

int

property allow_reentry: bool

Determines if a user can restart a conversation with an entry point.

Type:

bool

check_update(update)[source]

Determines whether an update should be handled by this conversation handler, and if so in which state the conversation currently is.

Parameters:

update (object) – Incoming update.

Returns:

tuple[object, tuple[int | str, ...], BaseHandler[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), object], object] | Nonebool

property conversation_timeout: float | timedelta | None

Optional. When this handler is inactive more than this timeout (in seconds), it will be automatically ended.

Type:

float | datetime.timedelta

property entry_points: list[BaseHandler[Update, CCT, object]]

A list of BaseHandler objects that can trigger the start of the conversation.

Type:

list[telegram.ext.BaseHandler]

property fallbacks: list[BaseHandler[Update, CCT, object]]

A list of handlers that might be used if the user is in a conversation, but every handler for their current state returned False on check_update().

Type:

list[telegram.ext.BaseHandler]

async handle_update(update, application, check_result, context)[source]

Send the update to the callback for the current state and BaseHandler

Parameters:
  • check_result (tuple[object, tuple[int | str, ...], BaseHandler[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), object], object]) – The result from check_update(). For this handler it’s a tuple of the conversation state, key, handler, and the handler’s check result.

  • update (Update) – Incoming telegram update.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – Application that originated the update.

  • context (TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])) – The context as provided by the application.

Return type:

object | None

property map_to_parent: dict[object, object] | None

Optional. A dict that can be used to instruct a nested ConversationHandler to transition into a mapped state on its parent ConversationHandler in place of a specified nested state.

Type:

dict[object, object]

property name: str | None

Optional. The name for this ConversationHandler.

Type:

str

property per_chat: bool

If the conversation key should contain the Chat’s ID.

Type:

bool

property per_message: bool

If the conversation key should contain the message’s ID.

Type:

bool

property per_user: bool

If the conversation key should contain the User’s ID.

Type:

bool

property persistent: bool

Optional. If the conversations dict for this handler should be saved. name is required and persistence has to be set in Application.

Type:

bool

property states: dict[object, list[BaseHandler[Update, CCT, object]]]

A dict that defines the different states of conversation a user can be in and one or more associated BaseHandler objects that should be used in that state.

Type:

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

timeout_jobs: dict[ConversationKey, Job[Any]]
class spotted.handlers.spot.ConversationState(*values)[source]

Bases: Enum

Enum for the states of the conversation. The end state must have value -1, since it is the convention used by the ConversationHandler to terminate the conversation.

END = -1
POSTING = 1
POSTING_CONFIRM = 3
POSTING_PREVIEW = 2
REPORTING_SPOT = 4
REPORTING_USER = 5
REPORTING_USER_REASON = 6
SENDING_USER_REPORT = 7
class spotted.handlers.spot.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.spot.MessageHandler(filters, callback, block=True)[source]

Bases: BaseHandler[Update, CCT, RT]

Handler class to handle Telegram messages. They might contain text, media or status updates.

Warning

When setting block to False, you cannot rely on adding custom attributes to telegram.ext.CallbackContext. See its docs for more info.

Parameters:
  • filters (BaseFilter | None) –

    A filter inheriting from telegram.ext.filters.BaseFilter. Standard filters can be found in telegram.ext.filters. Filters can be combined using bitwise operators (& for and, | for or, ~ for not). Passing None is a shortcut to passing telegram.ext.filters.ALL.

    See also

    Advanced Filters <Extensions---Advanced-Filters>

  • callback (Callable[[Update, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])], Coroutine[Any, Any, TypeVar(RT)]]) –

    The callback function for this handler. Will be called when check_update() has determined that an update should be processed by this handler. Callback signature:

    async def callback(update: Update, context: CallbackContext)
    

    The return value of the callback is usually ignored except for the special case of telegram.ext.ConversationHandler.

  • block (bool | DefaultValue[DVValueType], default: True) –

    Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update(). Defaults to True.

    See also

    Concurrency

filters

Only allow updates with these Filters. See telegram.ext.filters for a full list of all available filters.

Type:

telegram.ext.filters.BaseFilter

callback

The callback function for this handler.

Type:

coroutine function

block

Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update().

Type:

bool

check_update(update)[source]

Determines whether an update should be passed to this handler’s callback.

Parameters:

update (object) – Incoming update.

Returns:

bool | dict[str, list[Any]] | Nonebool

collect_additional_context(context, update, application, check_result)[source]

Adds possible output of data filters to the CallbackContext.

Return type:

None

filters: filters_module.BaseFilter
class spotted.handlers.spot.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
class spotted.handlers.spot.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.handlers.spot.choice(seq)

Choose a random element from a non-empty sequence.

spotted.handlers.spot.conv_cancel(family)[source]

Creates a function used to handle the /cancel command in the conversation. Invoking /cancel will exit the conversation immediately

Parameters:

family (str) – family of the command

Returns:

Callable[[Any, Any], Coroutine[Any, Any, int]] – function used to handle the /cancel command

spotted.handlers.spot.get_confirm_kb()[source]

Generates the InlineKeyboard to confirm the creation of the post

Returns:

InlineKeyboardMarkup – new inline keyboard

spotted.handlers.spot.get_preview_kb()[source]

Generates the InlineKeyboard to choose if the post should be previewed or not

Returns:

InlineKeyboardMarkup – new inline keyboard

spotted.handlers.spot.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

async spotted.handlers.spot.spot_cmd(update, context)[source]

Handles the /spot command. Checks that the user is in a private chat and it’s not banned and start the post conversation

Parameters:
Returns:

int – next state of the conversation

async spotted.handlers.spot.spot_confirm_query(update, context)[source]

Handles the [ submit | cancel ] callback. Creates the bid or cancels its creation.

  • submit: saves the post as pending and sends it to the admins for them to check.

  • cancel: cancels the current spot conversation

Parameters:
Returns:

int – next state of the conversation

spotted.handlers.spot.spot_conv_handler()[source]

Creates the spot conversation handler. The states are:

  • posting: submit the spot. Expects text, photo or many other formats

  • confirm: confirm or cancel the spot submission. Expects an inline query

Returns:

ConversationHandler – conversation handler

async spotted.handlers.spot.spot_msg(update, context)[source]

Handles the reply to the /spot command. Checks the message the user wants to post, and goes to the final step

Parameters:
Returns:

int – next state of the conversation

async spotted.handlers.spot.spot_preview_query(update, context)[source]

Handles the [ accept | reject ] callback. Let the user decide if wants to post the message with or without preview.

  • accept: the post will be published with preview

  • reject: the post will be published without preview

Parameters:
Returns:

int – next state of the conversation

spotted.handlers.start module

/start command

class spotted.handlers.start.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.start.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.start.ParseMode(*values)[source]

Bases: StringEnum

This enum contains the available parse modes. The enum members of this enumeration are instances of str and can be treated as such.

Added in version 20.0.

HTML = 'HTML'

HTML parse mode.

Type:

str

MARKDOWN = 'Markdown'

Markdown parse mode.

Note

MARKDOWN is a legacy mode, retained by Telegram for backward compatibility. You should use MARKDOWN_V2 instead.

Type:

str

MARKDOWN_V2 = 'MarkdownV2'

Markdown parse mode version 2.

Type:

str

class spotted.handlers.start.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
spotted.handlers.start.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

async spotted.handlers.start.start_cmd(update, context)[source]

Handles the /start command. Sends a welcoming message

Parameters:

spotted.handlers.unmute module

/unmute command

class spotted.handlers.unmute.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.unmute.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

exception spotted.handlers.unmute.TelegramError(message)[source]

Bases: Exception

Base class for Telegram errors.

Tip

Objects of this type can be serialized via Python’s pickle module and pickled objects from one version of PTB are usually loadable in future versions. However, we can not guarantee that this compatibility will always be provided. At least a manual one-time conversion of the data may be needed on major updates of the library.

See also

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

message: str
class spotted.handlers.unmute.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
class spotted.handlers.unmute.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.handlers.unmute.get_user_by_id_or_index(user_id_or_idx, users_list)[source]

Get a user either by their user_id or by their index in a given list of users. The index is specified by prefixing the number with a ‘#’ character. For example, ‘#0’ would refer to the first user in the list. On the other hand, if the input is a number without the ‘#’ prefix, it will be treated as a user_id.

Parameters:
  • user_id_or_idx (str) – The user_id or index to look for. If it starts with ‘#’, it will be treated as an index.

  • users_list (list[User]) – The list of users to search through when looking for an index.

Returns:

User | None – The User object corresponding to the given user_id or index, or None if no such user exists.

async spotted.handlers.unmute.unmute_cmd(update, context)[source]

Handles the /unmute command. Unmute a user by using this command and listing all the user_id to unmute

Parameters:

spotted.handlers.warn module

/warn command

class spotted.handlers.warn.CallbackContext(application, chat_id=None, user_id=None)[source]

Bases: Generic[BT, UD, CD, BD]

This is a context object passed to the callback called by telegram.ext.BaseHandler or by the telegram.ext.Application in an error handler added by telegram.ext.Application.add_error_handler or to the callback of a telegram.ext.Job.

Note

telegram.ext.Application will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same CallbackContext object (of course with proper attributes like matches differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on CallbackContext might change in the future, so make sure to use a fairly unique name for the attributes.

Warning

Do not combine custom attributes with telegram.ext.BaseHandler.block set to False or telegram.ext.Application.concurrent_updates set to True. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

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

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

  2. The type of user_data (if user_data is not None).

  3. The type of chat_data (if chat_data is not None).

  4. The type of bot_data (if bot_data is not None).

Examples

  • Context Types Bot

  • Custom Webhook Bot

See also

telegram.ext.ContextTypes.DEFAULT_TYPE, Job Queue <Extensions---JobQueue>

Parameters:
  • application (Application[TypeVar(BT, bound= Bot), TypeVar(ST, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

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

    The ID of the chat associated with this object. Used to provide chat_data.

    Added in version 20.0.

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

    The ID of the user associated with this object. Used to provide user_data.

    Added in version 20.0.

coroutine

Optional. Only present in error handlers if the error was caused by an awaitable run with Application.create_task() or a handler callback with block=False.

Type:

awaitable

matches

Optional. If the associated update originated from a filters.Regex, this will contain a list of match objects for every pattern where re.search(pattern, string) returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

Type:

list[re.Match]

args

Optional. Arguments passed to a command if the associated update is handled by telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

Type:

list[str]

error

Optional. The error that was raised. Only present when passed to an error handler registered with telegram.ext.Application.add_error_handler.

Type:

Exception

job

Optional. The job which originated this callback. Only present when passed to the callback of telegram.ext.Job or in error handlers if the error is caused by a job.

Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.

Type:

telegram.ext.Job

property application: Application[BT, ST, UD, CD, BD, Any]

The application associated with this context.

Type:

telegram.ext.Application

args: list[str] | None
property bot: BT

The bot associated with this context.

Type:

telegram.Bot

property bot_data: BD

Optional. An object that can be used to keep any data in. For each update it will be the same ContextTypes.bot_data. Defaults to dict.

See also

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

Type:

ContextTypes.bot_data

property chat_data: CD | None

Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same ContextTypes.chat_data. Defaults to dict.

Warning

When a group chat migrates to a supergroup, its chat id will change and the chat_data needs to be transferred. For details see our wiki page <Storing-bot,-user-and-chat-related-data#chat-migration>.

See also

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

Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.chat_data

coroutine: Generator[Future[object] | None, None, Any] | Awaitable[Any] | None
drop_callback_data(callback_query)[source]

Deletes the cached data for the specified callback query.

Added in version 13.6.

Note

Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case the callback query can not be found in the cache.

See also

Arbitrary callback_data <Arbitrary-callback_data>

Parameters:

callback_query (CallbackQuery) – The callback query.

Raises:

KeyError | RuntimeErrorKeyError, if the callback query can not be found in the cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.

Return type:

None

error: Exception | None
classmethod from_error(update, error, application, job=None, coroutine=None)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the error handlers.

Changed in version 20.0: Removed arguments async_args and async_kwargs.

Parameters:
  • update (object) – The update associated with the error. May be None, e.g. for errors in job callbacks.

  • error (Exception) – The error.

  • application (Application[TypeVar(BT, bound= Bot), TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), TypeVar(UD), TypeVar(CD), TypeVar(BD), Any]) – The application associated with this context.

  • job (Job[Any] | None, default: None) –

    The job associated with the error.

    Added in version 20.0.

  • coroutine (Generator[Future[object] | None, None, Any] | Awaitable[Any] | None, default: None) –

    The awaitable associated with this error if the error was caused by a coroutine run with Application.create_task() or a handler callback with block=False.

    Added in version 20.0.

    Changed in version 20.2: Accepts asyncio.Future and generator-based coroutine functions.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_job(job, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to a job callback.

See also

telegram.ext.JobQueue()

Parameters:
  • job (Job[TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])]) – The job.

  • application (Application[Any, TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]), Any, Any, Any, Any]) – The application associated with this context.

Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

classmethod from_update(update, application)[source]

Constructs an instance of telegram.ext.CallbackContext to be passed to the handlers.

Parameters:
Returns:

TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any])telegram.ext.CallbackContext

job: Job[Any] | None
property job_queue: JobQueue[ST] | None

The JobQueue used by the telegram.ext.Application.

See also

Job Queue <Extensions---JobQueue>

Type:

telegram.ext.JobQueue

property match: Match[str] | None

The first match from matches. Useful if you are only filtering using a single regex filter. Returns None if matches is empty.

Type:

re.Match

matches: list[Match[str]] | None
async refresh_data()[source]

If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data() on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.

Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.run().

Added in version 13.6.

Return type:

None

update(data)[source]

Updates self.__slots__ with the passed data.

Parameters:

data (dict[str, object]) – The data.

Return type:

None

property update_queue: Queue[object]

The asyncio.Queue instance used by the telegram.ext.Application and (usually) the telegram.ext.Updater associated with this context.

Type:

asyncio.Queue

property user_data: UD | None

Optional. An object that can be used to keep any data in. For each update from the same user it will be the same ContextTypes.user_data. Defaults to dict.

See also

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

Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

Type:

ContextTypes.user_data

class spotted.handlers.warn.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.handlers.warn.EventInfo(bot, ctx, update=None, message=None, query=None)[source]

Bases: object

Class that contains all the relevant information related to an event

async answer_callback_query(text=None)[source]

Calls the answer_callback_query method of the bot class, while also handling the exception

Parameters:

text (str | None, default: None) – Text to show to the user

property args: list[str]

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property bot: Bot

Instance of the telegram bot

property bot_data: dict

Data related to the bot. Is not persistent between restarts

property callback_key: str

Return the args of the message that caused the update. If the update was caused by a callback, the callback data is splitted by ‘,’ and returned

property chat_id: int | None

Id of the chat where the event happened

property chat_type: str | None

Type of the chat where the event happened

property context: CallbackContext

Context generated by some event

async edit_inline_keyboard(chat_id=None, message_id=None, new_keyboard=None)[source]

Generic wrapper used to edit the inline keyboard of a message with the telegram bot, while also handling the exception

Parameters:
  • chat_id (int | None, default: None) – id of the chat the message to edit belongs to or the current chat if None

  • message_id (int | None, default: None) – id of the message to edit. It is the current message if left None

  • new_keyboard (InlineKeyboardMarkup | None, default: None) – new inline keyboard to assign to the message

property forward_from_chat_id: int | None

Id of the original chat the message has been forwarded from

property forward_from_id: int | None

Id of the original message that has been forwarded

classmethod from_callback(update, ctx)[source]

Instance of EventInfo created by a callback update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_job(ctx)[source]

Instance of EventInfo created by a job update

Parameters:

context – context passed by the handler

Returns:

EventInfo – instance of the class

classmethod from_message(update, ctx)[source]

Instance of EventInfo created by a message update

Parameters:
  • update (Update) – update event

  • context – context passed by the handler

Returns:

EventInfo – instance of the class

property inline_keyboard: InlineKeyboardMarkup | None

InlineKeyboard attached to the message

property is_forward_from_channel: bool

Whether the message has been forwarded from a channel

property is_forward_from_chat: bool

Whether the message has been forwarded from a chat

property is_forward_from_user: bool

Whether the message has been forwarded from a user

property is_forwarded_post: bool

Whether the message is in fact a forwarded post from the channel to the group

property is_private_chat: bool | None

Whether the chat is private or not

property is_valid_message_type: bool

Whether or not the type of the message is supported

property message: Message | None

Message that caused the update

property message_id: int | None

Id of the message that caused the update

property query_data: str | None

Data associated with the query that caused the update

property query_id: str | None

Id of the query that caused the update

property reply_markup: InlineKeyboardMarkup | None

Reply_markup of the message that caused the update

async send_post_to_admins()[source]

Sends the post to the admin group, so it can be approved

Returns:

bool – whether or not the operation was successful

async send_post_to_channel(user_id)[source]

Sends the post to the channel, so it can be enjoyed by the users (and voted, if comments are disabled)

async send_post_to_channel_group()[source]

If comments are enabled, sends the post to the group associated to the channel, allowing the author to be credited and other users to report the spot or follow it.

async show_admins_votes(pending_post, reason=None)[source]

After a post is been approved or rejected, shows the admins that approved or rejected it and edit the message to show the admin’s votes

Parameters:
  • pending_post (PendingPost) – post to show the admin’s votes for

  • reason (str | None, default: None) – reason for the rejection, currently used on autoreply

property text: str | None

Text of the message that caused the update

property update: Update | None

Update generated by some event

property user_data: dict | None

Data related to the user. Is not persistent between restarts

property user_id: int | None

Id of the user that caused the update

property user_name: str | None

Name of the user that caused the update

property user_username: str | None

Username of the user that caused the update

class spotted.handlers.warn.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.handlers.warn.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.handlers.warn.Update(update_id, message=None, edited_message=None, channel_post=None, edited_channel_post=None, inline_query=None, chosen_inline_result=None, callback_query=None, shipping_query=None, pre_checkout_query=None, poll=None, poll_answer=None, my_chat_member=None, chat_member=None, chat_join_request=None, chat_boost=None, removed_chat_boost=None, message_reaction=None, message_reaction_count=None, business_connection=None, business_message=None, edited_business_message=None, deleted_business_messages=None, purchased_paid_media=None, *, api_kwargs=None)[source]

Bases: TelegramObject

This object represents an incoming update.

Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their update_id is equal.

Note

At most one of the optional parameters can be present in any given update.

See also

Your First Bot <Extensions---Your-first-Bot>

Parameters:
  • update_id (int) – The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

  • message (Message | None, default: None) – New incoming message of any kind - text, photo, sticker, etc.

  • edited_message (Message | None, default: None) – New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • channel_post (Message | None, default: None) – New incoming channel post of any kind - text, photo, sticker, etc.

  • edited_channel_post (Message | None, default: None) – New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

  • inline_query (InlineQuery | None, default: None) – New incoming inline query.

  • chosen_inline_result (ChosenInlineResult | None, default: None) – The result of an inline query that was chosen by a user and sent to their chat partner.

  • callback_query (CallbackQuery | None, default: None) – New incoming callback query.

  • shipping_query (ShippingQuery | None, default: None) – New incoming shipping query. Only for invoices with flexible price.

  • pre_checkout_query (PreCheckoutQuery | None, default: None) – New incoming pre-checkout query. Contains full information about checkout.

  • poll (Poll | None, default: None) – New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

  • poll_answer (PollAnswer | None, default: None) – A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

  • my_chat_member (ChatMemberUpdated | None, default: None) –

    The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

    Added in version 13.4.

  • chat_member (ChatMemberUpdated | None, default: None) –

    A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

    Added in version 13.4.

  • chat_join_request (ChatJoinRequest | None, default: None) –

    A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

    Added in version 13.8.

  • chat_boost (ChatBoostUpdated | None, default: None) –

    A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • removed_chat_boost (ChatBoostRemoved | None, default: None) –

    A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

    Added in version 20.8.

  • message_reaction (MessageReactionUpdated | None, default: None) –

    A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

    Added in version 20.8.

  • message_reaction_count (MessageReactionCountUpdated | None, default: None) –

    Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

    Added in version 20.8.

  • business_connection (BusinessConnection | None, default: None) –

    The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

    Added in version 21.1.

  • business_message (Message | None, default: None) –

    New message from a connected business account.

    Added in version 21.1.

  • edited_business_message (Message | None, default: None) –

    New version of a message from a connected business account.

    Added in version 21.1.

  • deleted_business_messages (BusinessMessagesDeleted | None, default: None) –

    Messages were deleted from a connected business account.

    Added in version 21.1.

  • purchased_paid_media (PaidMediaPurchased | None, default: None) –

    A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

    Added in version 21.6.

update_id

The update’s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.

Type:

int

message

Optional. New incoming message of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_message

Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

channel_post

Optional. New incoming channel post of any kind - text, photo, sticker, etc.

Type:

telegram.Message

edited_channel_post

Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.

Type:

telegram.Message

inline_query

Optional. New incoming inline query.

Type:

telegram.InlineQuery

chosen_inline_result

Optional. The result of an inline query that was chosen by a user and sent to their chat partner.

Type:

telegram.ChosenInlineResult

callback_query

Optional. New incoming callback query.

Examples

Arbitrary Callback Data Bot

Type:

telegram.CallbackQuery

shipping_query

Optional. New incoming shipping query. Only for invoices with flexible price.

Type:

telegram.ShippingQuery

pre_checkout_query

Optional. New incoming pre-checkout query. Contains full information about checkout.

Type:

telegram.PreCheckoutQuery

poll

Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.

Type:

telegram.Poll

poll_answer

Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.

Type:

telegram.PollAnswer

my_chat_member

Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_member

Optional. A chat member’s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()).

Added in version 13.4.

Type:

telegram.ChatMemberUpdated

chat_join_request

Optional. A request to join the chat has been sent. The bot must have the telegram.ChatPermissions.can_invite_users administrator right in the chat to receive these updates.

Added in version 13.8.

Type:

telegram.ChatJoinRequest

chat_boost

Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostUpdated

removed_chat_boost

Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.

Added in version 20.8.

Type:

telegram.ChatBoostRemoved

message_reaction

Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.

Added in version 20.8.

Type:

telegram.MessageReactionUpdated

message_reaction_count

Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify MESSAGE_REACTION_COUNT in the list of telegram.ext.Application.run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(), telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.ext.Application.run_webhook()). The updates are grouped and can be sent with delay up to a few minutes.

Added in version 20.8.

Type:

telegram.MessageReactionCountUpdated

business_connection

Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot.

Added in version 21.1.

Type:

telegram.BusinessConnection

business_message

Optional. New message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

edited_business_message

Optional. New version of a message from a connected business account.

Added in version 21.1.

Type:

telegram.Message

deleted_business_messages

Optional. Messages were deleted from a connected business account.

Added in version 21.1.

Type:

telegram.BusinessMessagesDeleted

purchased_paid_media

Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat.

Added in version 21.6.

Type:

telegram.PaidMediaPurchased

ALL_TYPES: Final[list[str]] = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>, <UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>, <UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>, <UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>, <UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>, <UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>, <UpdateType.CHAT_JOIN_REQUEST>, <UpdateType.CHAT_BOOST>, <UpdateType.REMOVED_CHAT_BOOST>, <UpdateType.MESSAGE_REACTION>, <UpdateType.MESSAGE_REACTION_COUNT>, <UpdateType.BUSINESS_CONNECTION>, <UpdateType.BUSINESS_MESSAGE>, <UpdateType.EDITED_BUSINESS_MESSAGE>, <UpdateType.DELETED_BUSINESS_MESSAGES>, <UpdateType.PURCHASED_PAID_MEDIA>]

A list of all available update types.

Added in version 13.5.

Type:

list[str]

BUSINESS_CONNECTION: Final[str] = 'business_connection'

telegram.constants.UpdateType.BUSINESS_CONNECTION

Added in version 21.1.

BUSINESS_MESSAGE: Final[str] = 'business_message'

telegram.constants.UpdateType.BUSINESS_MESSAGE

Added in version 21.1.

CALLBACK_QUERY: Final[str] = 'callback_query'

telegram.constants.UpdateType.CALLBACK_QUERY

Added in version 13.5.

CHANNEL_POST: Final[str] = 'channel_post'

telegram.constants.UpdateType.CHANNEL_POST

Added in version 13.5.

CHAT_BOOST: Final[str] = 'chat_boost'

telegram.constants.UpdateType.CHAT_BOOST

Added in version 20.8.

CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'

telegram.constants.UpdateType.CHAT_JOIN_REQUEST

Added in version 13.8.

CHAT_MEMBER: Final[str] = 'chat_member'

telegram.constants.UpdateType.CHAT_MEMBER

Added in version 13.5.

CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'

telegram.constants.UpdateType.CHOSEN_INLINE_RESULT

Added in version 13.5.

DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'

telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGES

Added in version 21.1.

EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'

telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGE

Added in version 21.1.

EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'

telegram.constants.UpdateType.EDITED_CHANNEL_POST

Added in version 13.5.

EDITED_MESSAGE: Final[str] = 'edited_message'

telegram.constants.UpdateType.EDITED_MESSAGE

Added in version 13.5.

INLINE_QUERY: Final[str] = 'inline_query'

telegram.constants.UpdateType.INLINE_QUERY

Added in version 13.5.

MESSAGE: Final[str] = 'message'

telegram.constants.UpdateType.MESSAGE

Added in version 13.5.

MESSAGE_REACTION: Final[str] = 'message_reaction'

telegram.constants.UpdateType.MESSAGE_REACTION

Added in version 20.8.

MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'

telegram.constants.UpdateType.MESSAGE_REACTION_COUNT

Added in version 20.8.

MY_CHAT_MEMBER: Final[str] = 'my_chat_member'

telegram.constants.UpdateType.MY_CHAT_MEMBER

Added in version 13.5.

POLL: Final[str] = 'poll'

telegram.constants.UpdateType.POLL

Added in version 13.5.

POLL_ANSWER: Final[str] = 'poll_answer'

telegram.constants.UpdateType.POLL_ANSWER

Added in version 13.5.

PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'

telegram.constants.UpdateType.PRE_CHECKOUT_QUERY

Added in version 13.5.

PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'

telegram.constants.UpdateType.PURCHASED_PAID_MEDIA

Added in version 21.6.

REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'

telegram.constants.UpdateType.REMOVED_CHAT_BOOST

Added in version 20.8.

SHIPPING_QUERY: Final[str] = 'shipping_query'

telegram.constants.UpdateType.SHIPPING_QUERY

Added in version 13.5.

business_connection: BusinessConnection | None
business_message: Message | None
callback_query: CallbackQuery | None
channel_post: Message | None
chat_boost: ChatBoostUpdated | None
chat_join_request: ChatJoinRequest | None
chat_member: ChatMemberUpdated | None
chosen_inline_result: ChosenInlineResult | None
classmethod de_json(data, bot=None)[source]

See telegram.TelegramObject.de_json().

Return type:

Update

deleted_business_messages: BusinessMessagesDeleted | None
edited_business_message: Message | None
edited_channel_post: Message | None
edited_message: Message | None
property effective_chat: Chat | None

The chat that this update was sent in, no matter what kind of update this is. If no chat is associated with this update, this gives None. This is the case, if inline_query, chosen_inline_result, callback_query from inline messages, shipping_query, pre_checkout_query, poll, poll_answer, business_connection, or purchased_paid_media is present.

Changed in version 21.1: This property now also considers business_message, edited_business_message, and deleted_business_messages.

Example

If message is present, this will give telegram.Message.chat.

Type:

telegram.Chat

property effective_message: Message | None
The message included in this update, no matter what kind of

update this is. More precisely, this will be the message contained in message, edited_message, channel_post, edited_channel_post or callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.

Changed in version 21.1: This property now also considers business_message, and edited_business_message.

Tip

This property will only ever return objects of type telegram.Message or None, never telegram.MaybeInaccessibleMessage or telegram.InaccessibleMessage. Currently, this is only relevant for callback_query, as telegram.CallbackQuery.message is the only attribute considered by this property that can be an object of these types.

Type:

telegram.Message

property effective_sender: User | Chat | None

The user or chat that sent this update, no matter what kind of update this is.

Note

If no user whatsoever is associated with this update, this gives None. This is the case if any of

is present.

Example

Added in version 21.1.

Type:

telegram.User or telegram.Chat

property effective_user: User | None

The user that sent this update, no matter what kind of update this is. If no user is associated with this update, this gives None. This is the case if any of

is present.

Changed in version 21.1: This property now also considers business_connection, business_message and edited_business_message.

Changed in version 21.6: This property now also considers purchased_paid_media.

Example

Type:

telegram.User

inline_query: InlineQuery | None
message: Message | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
my_chat_member: ChatMemberUpdated | None
poll: Poll | None
poll_answer: PollAnswer | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
removed_chat_boost: ChatBoostRemoved | None
shipping_query: ShippingQuery | None
update_id: int
class spotted.handlers.warn.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

async spotted.handlers.warn.execute_ban(user_id, info)[source]

Execute the ban of a user by his user_id

Parameters:
  • user_id (int) – The user_id of the user to ban

  • info (EventInfo) – The EventInfo object

async spotted.handlers.warn.execute_warn(info, user_id, comment, from_community=False)[source]

Execute the /warn command. Add a warn to the user and auto-ban is necessary

Args:

user_id: The user_id of the interested user bot: a telegram bot instance from_community: a flag for auto-delete command invokation

async spotted.handlers.warn.warn_cmd(update, context)[source]
Handles the /warn command.

Warn a user by replying to a user’comment on the community group or to a pending spot/report.

Parameters: