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.ApplicationBuilderorbuilder()(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
Genericclass and accepts six type variables:The type of
bot. Must betelegram.Botor a subclass of that class.The type of the argument
contextof callback functions for (error) handlers and jobs. Must betelegram.ext.CallbackContextor a subclass of that class. This must be consistent with the following types.The type of the values of
user_data.The type of the values of
chat_data.The type of
bot_data.The type of
job_queue. Must either betelegram.ext.JobQueueor a subclass of that orNone.
Examples
Echo BotSee also
Your First Bot <Extensions---Your-first-Bot>,Architecture Overview <Architecture>Changed in version 20.0:
Initialization is now done through the
telegram.ext.ApplicationBuilder.Removed the attribute
groups.
- bot
The bot object that should be passed to the handlers.
- Type:
- update_queue
The synchronized queue that will contain the updates.
- Type:
- updater
Optional. The updater used by this application.
- Type:
- 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_datain handler callbacks for updates from that chat.Changed in version 20.0:
chat_datais now read-only. Note that the values of the mapping are still mutable, i.e. editingcontext.chat_datawithin a handler callback is possible (and encouraged), but editing the mappingapplication.chat_dataitself is not.Tip
Manually modifying
chat_datais 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:
- 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_datain handler callbacks for updates from that user.Changed in version 20.0:
user_datais now read-only. Note that the values of the mapping are still mutable, i.e. editingcontext.user_datawithin a handler callback is possible (and encouraged), but editing the mappingapplication.user_dataitself is not.Tip
Manually modifying
user_datais 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:
- persistence
The persistence class to store data that should be persistent over restarts.
- handlers
A dictionary mapping each handler group to the list of handlers registered to that group.
See also
- 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.
See also
- Type:
dict[coroutine function,
bool]
- context_types
Specifies the types used by this dispatcher for the
contextargument of handler and job callbacks.
- post_init
Optional. A callback that will be executed by
Application.run_polling()andApplication.run_webhook()after initializing the application viainitialize().- Type:
- post_shutdown
Optional. A callback that will be executed by
Application.run_polling()andApplication.run_webhook()after shutting down the application viashutdown().- Type:
- post_stop
Optional. A callback that will be executed by
Application.run_polling()andApplication.run_webhook()after stopping the application viastop().Added in version 20.1.
- Type:
- 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 BotHint
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 inprocess_error(). Defaults toTrue.
- Return type:
- 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. Iftelegram.ext.ApplicationHandlerStopis 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.ConversationHandlerafter 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.
- 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.Sequenceas input instead of just a list or tuple.group (
int|DefaultValue[int], default:0) – Specify which group the sequence ofhandlersshould be added to. Defaults to0.
- Return type:
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.
- property concurrent_updates: int
The number of concurrent updates that will be processed in parallel. A value of
0indicates 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:
- 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 thecoroutinewithprocess_error().Note
If
coroutineraises an exception, it will be set on the task created by this method even though it’s handled byprocess_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.Futureand 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 toprocess_error()as additional information for the error handlers. Moreover, the correspondingchat_dataanduser_dataentries will be updated in the next run ofupdate_persistence()after thecoroutineis finished.
- Keyword Arguments:
name (
str, optional) –The name of the task.
Added in version 20.4.
- Returns:
The created task.
- Returns:
- 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 ofupdate_persistence(), if applicable.Warning
When using
concurrent_updatesor thejob_queue,process_update()ortelegram.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.
- 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 ofupdate_persistence(), if applicable.Warning
When using
concurrent_updatesor thejob_queue,process_update()ortelegram.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.
- error_handlers: dict[Callable[[object, CCT], Coroutine[Any, Any, None]], bool | DefaultValue[bool]]
- async initialize()[source]
Initializes the Application by initializing:
The
bot, by callingtelegram.Bot.initialize().The
updater, by callingtelegram.ext.Updater.initialize().The
persistence, by loading persistent conversations and data.The
update_processorby callingtelegram.ext.BaseUpdateProcessor.initialize().
Does not call
post_init- that is only done byrun_polling()andrun_webhook().See also
- Return type:
- property job_queue: JobQueue[CCT] | None
- The
JobQueueused by the
See also
Job Queue <Extensions---JobQueue>- Type:
- The
- mark_data_for_update_persistence(chat_ids=None, user_ids=None)[source]
Mark entries of
chat_dataanduser_datato be updated on the next run ofupdate_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 usebot_datainstead.Added in version 20.3.
- Parameters:
chat_ids (
int|Collection[int] |None, default:None) – Chat IDs to mark.user_ids (
int|Collection[int] |None, default:None) – User IDs to mark.
- Return type:
- migrate_chat_data(message=None, old_chat_id=None, new_chat_id=None)[source]
Moves the contents of
chat_dataat keyold_chat_idto the keynew_chat_id. Also marks the entries to be updated accordingly in the next run ofupdate_persistence().Warning
Any data stored in
chat_dataat keynew_chat_idwill be overriddenThe key
old_chat_idofchat_datawill be deletedThis does not update the
chat_idattribute of any scheduledtelegram.ext.Job.
When using
concurrent_updatesor thejob_queue,process_update()ortelegram.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:
message (
Message|None, default:None) –A message with either
migrate_from_chat_idormigrate_to_chat_id. Mutually exclusive with passingold_chat_idandnew_chat_id.old_chat_id (
int|None, default:None) – The old chat ID. Mutually exclusive with passingmessagenew_chat_id (
int|None, default:None) – The new chat ID. Mutually exclusive with passingmessage
- Raises:
ValueError – Raised if the input is invalid.
- Return type:
- persistence: BasePersistence[UD, CD, BD] | 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 raisestelegram.ext.ApplicationHandlerStop, the error will not be handled by other error handlers. Raisingtelegram.ext.ApplicationHandlerStopalso stops processing of the update when this method is called byprocess_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:
dispatch_errorwas renamed toprocess_error().Exceptions raised by error handlers are now properly logged.
telegram.ext.ApplicationHandlerStopis no longer reraised but converted into the return value.
- Parameters:
- Returns:
True, if one of the error handlers raisedtelegram.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
ConcurrencyChanged 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:
- 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.
- 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:
handler (
BaseHandler[Any,TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]),Any]) – Atelegram.ext.BaseHandlerinstance.group (
int, default:0) – The group identifier. Default is0.
- Return type:
- 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:Run the application until the users stops it
A small wrapper is passed to
telegram.ext.Updater.start_polling.error_callbackwhich forwards errors occurring during polling toregistered error handlers. The update parameter of the callback will be set toNone.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, andpool_timeout. Use the corresponding methods intelegram.ext.ApplicationBuilderinstead.- Parameters:
poll_interval (
float, default:0.0) – Time to wait between polling updates from Telegram in seconds. Default is0.0.timeout (
int|timedelta, default:datetime.timedelta(seconds=10)) –Passed to
telegram.Bot.get_updates.timeout. Default istimedelta(seconds=10).Changed in version v22.2: |time-period-input|
bootstrap_retries (
int, default:0) –Whether the bootstrapping phase (calling
initialize()and the boostrapping oftelegram.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
Changed in version 21.11: The default value will be changed to from
-1to0. Indefinite retries during bootstrapping are not recommended.drop_pending_updates (
bool|None, default:None) – Whether to clean any pending updates on Telegram servers before actually starting to poll. Default isFalse.allowed_updates (
Sequence[str] |None, default:None) –Passed to
telegram.Bot.get_updates().Changed in version 21.9: Accepts any
collections.abc.Sequenceas input instead of just a listclose_loop (
bool, default:True) –If
True, the current event loop will be closed upon shutdown. Defaults toTrue.See also
stop_signals (DefaultValue[DVValueType] |
Sequence[int] | DefaultValue[None] |None, default:None) –Signals that will shut down the app. Pass
Noneto not use stop signals. Defaults tosignal.SIGINT,signal.SIGTERMandsignal.SIGABRTon non Windows platforms.Caution
Not every
asyncio.AbstractEventLoopimplementsasyncio.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.
- Raises:
RuntimeError – If the Application does not have an
telegram.ext.Updater.- Return type:
- 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
certandkeyare not provided, the webhook will be started directly onhttp://listen:port/url_path, so SSL can be handled by another application. Else, the webhook will be started onhttps://listen:port/url_path. Also callstelegram.Bot.set_webhook()as required.The order of execution by
run_webhook()is roughly as follows:Run the application until the users stops it
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 oftelegram.constants.SUPPORTED_WEBHOOK_PORTSunless the bot is running behind a proxy. Defaults to80.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 oftelegram.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 fromlisten,port,url_path,cert, andkey.allowed_updates (
Sequence[str] |None, default:None) –Passed to
telegram.Bot.set_webhook().Changed in version 21.9: Accepts any
collections.abc.Sequenceas input instead of just a listdrop_pending_updates (
bool|None, default:None) – Whether to clean any pending updates on Telegram servers before actually starting to poll. Default isFalse.ip_address (
str|None, default:None) – Passed totelegram.Bot.set_webhook().max_connections (
int, default:40) – Passed totelegram.Bot.set_webhook(). Defaults to40.close_loop (
bool, default:True) –If
True, the current event loop will be closed upon shutdown. Defaults toTrue.See also
stop_signals (DefaultValue[DVValueType] |
Sequence[int] | DefaultValue[None] |None, default:None) –Signals that will shut down the app. Pass
Noneto not use stop signals. Defaults tosignal.SIGINT,signal.SIGTERMandsignal.SIGABRT.Caution
Not every
asyncio.AbstractEventLoopimplementsasyncio.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_tokenfor 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-Tokenheader of an incoming request and will raise ahttp.HTTPStatus.FORBIDDENerror 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.Pathorstr. 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
listenandport. When using this param, you must also run a reverse proxy to the unix socket and set the appropriatewebhook_url.Added in version 20.8.
Changed in version 21.1: Added support to pass a socket instance itself.
- Return type:
- async shutdown()[source]
Shuts down the Application by shutting down:
botby callingtelegram.Bot.shutdown()updaterby callingtelegram.ext.Updater.shutdown()persistenceby callingupdate_persistence()andBasePersistence.flush()update_processorby callingtelegram.ext.BaseUpdateProcessor.shutdown()
Does not call
post_shutdown- that is only done byrun_polling()andrun_webhook().See also
- Raises:
RuntimeError – If the application is still
running.- Return type:
- async start()[source]
Starts
a background task that fetches updates from
update_queueand processes them viaprocess_update().job_queue, if set.a background task that calls
update_persistence()in regular intervals, ifpersistenceis set.
Note
This does not start fetching updates from Telegram. To fetch updates, you need to either start
updatermanually or use one ofrun_polling()orrun_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
- Raises:
RuntimeError – If the application is already running or was not initialized.
- Return type:
- async stop()[source]
Stops the process after processing any pending updates or tasks created by
create_task(). Also stopsjob_queue, if set. Finally, callsupdate_persistence()andBasePersistence.flush()onpersistence, 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
Note
This does not stop
updater. You need to either manually calltelegram.ext.Updater.stop()or use one ofrun_polling()orrun_webhook().Does not call
post_stop- that is only done byrun_polling()andrun_webhook().
- Raises:
RuntimeError – If the application is not running.
- Return type:
- stop_running()[source]
This method can be used to stop the execution of
run_polling()orrun_webhook()from within a handler, job or error callback. This allows a graceful shutdown of the application, i.e. the methods listed inrun_pollingandrun_webhookwill 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()orrun_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:
- async update_persistence()[source]
Updates
user_data,chat_data,bot_datainpersistencealong withcallback_data_cacheand the conversation states of any persistentConversationHandlerregistered for this application.For
user_dataandchat_data, only those entries are updated which either were used or have been manually marked viamark_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:
- property update_processor: BaseUpdateProcessor
The update processor used by this application.
See also
ConcurrencyAdded in version 20.4.
- class spotted.handlers.BotCommand(command, description, *, api_kwargs=None)[source]
Bases:
TelegramObjectThis 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
commandanddescriptionare equal.- Parameters:
command (
str) – Text of the command;telegram.BotCommand.MIN_COMMAND-telegram.BotCommand.MAX_COMMANDcharacters. Can contain only lowercase English letters, digits and underscores.description (
str) – Description of the command;telegram.BotCommand.MIN_DESCRIPTION-telegram.BotCommand.MAX_DESCRIPTIONcharacters.
- command
Text of the command;
telegram.BotCommand.MIN_COMMAND-telegram.BotCommand.MAX_COMMANDcharacters. Can contain only lowercase English letters, digits and underscores.- Type:
- description
Description of the command;
telegram.BotCommand.MIN_DESCRIPTION-telegram.BotCommand.MAX_DESCRIPTIONcharacters.- Type:
- MAX_DESCRIPTION: Final[int] = 256
telegram.constants.BotCommandLimit.MAX_DESCRIPTIONAdded in version 20.0.
- class spotted.handlers.BotCommandScopeAllPrivateChats(*, api_kwargs=None)[source]
Bases:
BotCommandScopeRepresents the scope of bot commands, covering all private chats.
Added in version 13.7.
- class spotted.handlers.BotCommandScopeChat(chat_id, *, api_kwargs=None)[source]
Bases:
BotCommandScopeRepresents 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
typeandchat_idare equal.Added in version 13.7.
- Parameters:
chat_id (
str|int) – |chat_id_group|
- chat_id
- 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
remodule for more information.Note
If your bot allows arbitrary objects as
~telegram.InlineKeyboardButton.callback_data, it may happen that the originalcallback_datafor the incomingtelegram.CallbackQuerycan not be found. This is the case when either a malicious client tempered with thetelegram.CallbackQuery.dataor the data was simply dropped from cache or not persisted. In these cases, an instance oftelegram.ext.InvalidCallbackDatawill be set astelegram.CallbackQuery.data.Added in version 13.6.
If neither
patternnorgame_patternis set, anyCallbackQuerywill be handled. If onlypatternis set, queries withgame_short_namewill not be considered and vice versa. If both patterns are set, queries with either :attr: ~telegram.CallbackQuery.game_short_name ordatamatching the defined pattern will be handledAdded in version 21.5.
Warning
When setting
blocktoFalse, you cannot rely on adding custom attributes totelegram.ext.CallbackContext. See its docs for more info.- Parameters:
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.pattern (
str|Pattern[str] |type|Callable[[object],bool|None] |None, default:None) –Pattern to test
telegram.CallbackQuery.dataagainst. If a string or a regex pattern is passed,re.match()is used ontelegram.CallbackQuery.datato determine if an update should be handled by this handler. If your bot allows arbitrary objects as~telegram.InlineKeyboardButton.callback_data, non-strings will be accepted. To filter arbitrary objects you may pass:a callable, accepting exactly one argument, namely the
telegram.CallbackQuery.data. It must returnTrueorFalse/Noneto indicate, whether the update should be handled.a
type. Iftelegram.CallbackQuery.datais an instance of that type (or a subclass), the update will be handled.
If
telegram.CallbackQuery.dataisNone, thetelegram.CallbackQueryupdate will not be handled.See also
Arbitrary callback_data <Arbitrary-callback_data>Changed in version 13.6: Added support for arbitrary callback data.
game_pattern (
str|Pattern[str] |None, default:None) –Pattern to test
telegram.CallbackQuery.game_short_nameagainst. If a string or a regex pattern is passed,re.match()is used ontelegram.CallbackQuery.game_short_nameto determine if an update should be handled by this handler.Added in version 21.5.
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 toTrue.See also
Concurrency
- callback
The callback function for this handler.
- Type:
- pattern
Optional. Regex pattern, callback or type to test
telegram.CallbackQuery.dataagainst.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:
- block
Determines whether the return value of the callback should be awaited before processing the next handler in
telegram.ext.Application.process_update().- Type:
- check_update(update)[source]
Determines whether an update should be passed to this handler’s
callback.
- 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 alistto theCallbackContextnamedCallbackContext.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_MESSAGEin the filter argument.Note
CommandHandlerdoes not handle (edited) channel posts and does not handle commands that are part of a caption. Please useMessageHandlerwith a suitable combination of filters (e.g.telegram.ext.filters.UpdateType.CHANNEL_POSTS,telegram.ext.filters.CAPTIONandtelegram.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 thetelegram.ext.PrefixHandler.Warning
When setting
blocktoFalse, you cannot rely on adding custom attributes totelegram.ext.CallbackContext. See its docs for more info.Examples
Timer BotError Handler Bot
Changed in version 20.0:
- Parameters:
command (
str|Collection[str]) – The command or list of commands this handler should listen for. Case-insensitive. Limitations are the same as fortelegram.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 fromtelegram.ext.filters.BaseFilter. Standard filters can be found intelegram.ext.filters. Filters can be combined using bitwise operators (&forand,|foror,~fornot)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 toTrue.See also
Concurrencyhas_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. IfFalse, the handler will only process if there are no args. ifint, the handler will only process if there are exactly that many args. Defaults toNone, 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.
- callback
The callback function for this handler.
- Type:
- filters
Optional. Only allow updates with these filters.
- block
Determines whether the return value of the callback should be awaited before processing the next handler in
telegram.ext.Application.process_update().- Type:
- has_args
Optional argument, otherwise all implementations of
CommandHandlerwill break. Defaults toNone, which means the handler will process any args or no args.Added in version 20.5.
- check_update(update)[source]
Determines whether an update should be passed to this handler’s
callback.
- collect_additional_context(context, update, application, check_result)[source]
Add text after the command to
CallbackContext.argsas list, split on single whitespaces and add output of data filters toCallbackContextas well.- Return type:
- filters: filters_module.BaseFilter
- class spotted.handlers.Config[source]
Bases:
objectConfigurations
- 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.
- 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:
- 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 getdefault (
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
- 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
blocktoFalse, you cannot rely on adding custom attributes totelegram.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 intelegram.ext.filters. Filters can be combined using bitwise operators (& for and, | for or, ~ for not). PassingNoneis a shortcut to passingtelegram.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 toTrue.See also
Concurrency
- filters
Only allow updates with these Filters. See
telegram.ext.filtersfor a full list of all available filters.
- callback
The callback function for this handler.
- Type:
- block
Determines whether the return value of the callback should be awaited before processing the next handler in
telegram.ext.Application.process_update().- Type:
- check_update(update)[source]
Determines whether an update should be passed to this handler’s
callback.
- collect_additional_context(context, update, application, check_result)[source]
Adds possible output of data filters to the
CallbackContext.- Return type:
- filters: filters_module.BaseFilter
- exception spotted.handlers.PTBUserWarning[source]
Bases:
UserWarningCustom 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- async spotted.handlers.approve_status_callback(update, context)[source]
Handles the approve_status callback. Pauses or resume voting on a specific pending post
- Parameters:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- async spotted.handlers.help_cmd(update, context)[source]
Handles the /help command. Sends an help message
- Parameters:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- async spotted.handlers.log_message(update, _)[source]
Log the message that caused the update
- Parameters:
update (
Update) – update eventcontext – 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- Return type:
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- class spotted.handlers.time
Bases:
objecttime([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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectConfigurations
- 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.
- 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:
- 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 getdefault (
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
- class spotted.handlers.anonym_comment.EventInfo(bot, ctx, update=None, message=None, query=None)[source]
Bases:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
spotted.handlers.approve module
Approve actions the admin can take on a pending post.
- exception spotted.handlers.approve.BadRequest(message)[source]
Bases:
NetworkErrorRaised 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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectConfigurations
- 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.
- 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:
- 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 getdefault (
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
- class spotted.handlers.approve.EventInfo(bot, ctx, update=None, message=None, query=None)[source]
Bases:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- exception spotted.handlers.approve.Forbidden(message)[source]
Bases:
TelegramErrorRaised when the bot has not enough rights to perform the requested action.
Examples
Raw API BotChanged 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:
objectClass that represents a pending post
- Parameters:
user_id (
int) – id of the user that sent the postu_message_id (
int) – id of the original message of the postg_message_id (
int) – id of the post in the groupadmin_group_id (
int) – id of the admin groupcredit_username (
str|None, default:None) – username of the user that sent the post if it’s a credit postdate (
datetime) – when the post was sent
- 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:
- Returns:
PendingPost– instance of the class
- classmethod from_group(g_message_id, admin_group_id)[source]
Retrieves a pending post from the info related to the admin group
- Parameters:
- 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
- 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:
- Returns:
list[PendingPost] – list of ids of pending posts
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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 attachedapprove (
int, default:-1) – number of approve votes known in advancereject (
int, default:-1) – number of reject votes known in advancecredited_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 callbackpending_post (
PendingPost) – pending post to rejectreason (
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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectConfigurations
- 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.
- 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:
- 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 getdefault (
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
- class spotted.handlers.autoreply.EventInfo(bot, ctx, update=None, message=None, query=None)[source]
Bases:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- class spotted.handlers.autoreply.PendingPost(user_id, u_message_id, g_message_id, admin_group_id, date, credit_username=None)[source]
Bases:
objectClass that represents a pending post
- Parameters:
user_id (
int) – id of the user that sent the postu_message_id (
int) – id of the original message of the postg_message_id (
int) – id of the post in the groupadmin_group_id (
int) – id of the admin groupcredit_username (
str|None, default:None) – username of the user that sent the post if it’s a credit postdate (
datetime) – when the post was sent
- 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:
- Returns:
PendingPost– instance of the class
- classmethod from_group(g_message_id, admin_group_id)[source]
Retrieves a pending post from the info related to the admin group
- Parameters:
- 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
- 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:
- Returns:
list[PendingPost] – list of ids of pending posts
- 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:
objectClass that represents a report
- Parameters:
user_id (
int) – id of the user that reportedadmin_group_id (
int) – id of the admin groupg_message_id (
int) – id of the post in the groupc_message_id (
int|None, default:None) – id of the post in question in the channeltarget_username (
str|None, default:None) – username of the reported userdate (
datetime|None, default:None) – when the report happened
- classmethod create_post_report(user_id, channel_id, c_message_id, admin_message)[source]
Adds the report of the user on a specific post
- classmethod create_user_report(user_id, target_username, admin_message)[source]
Adds the report of the user targeting another user
- 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
- classmethod get_post_report(user_id, channel_id, c_message_id)[source]
Gets the report of a specific user on a published post
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- async spotted.handlers.autoreply.reject_post(info, pending_post, reason=None)[source]
Rejects a pending post
- Parameters:
info (
EventInfo) – information about the callbackpending_post (
PendingPost) – pending post to rejectreason (
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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectConfigurations
- 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.
- 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:
- 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 getdefault (
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
- class spotted.handlers.ban.EventInfo(bot, ctx, update=None, message=None, query=None)[source]
Bases:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- class spotted.handlers.ban.PendingPost(user_id, u_message_id, g_message_id, admin_group_id, date, credit_username=None)[source]
Bases:
objectClass that represents a pending post
- Parameters:
user_id (
int) – id of the user that sent the postu_message_id (
int) – id of the original message of the postg_message_id (
int) – id of the post in the groupadmin_group_id (
int) – id of the admin groupcredit_username (
str|None, default:None) – username of the user that sent the post if it’s a credit postdate (
datetime) – when the post was sent
- 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:
- Returns:
PendingPost– instance of the class
- classmethod from_group(g_message_id, admin_group_id)[source]
Retrieves a pending post from the info related to the admin group
- Parameters:
- 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
- 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:
- Returns:
list[PendingPost] – list of ids of pending posts
- 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:
objectClass that represents a report
- Parameters:
user_id (
int) – id of the user that reportedadmin_group_id (
int) – id of the admin groupg_message_id (
int) – id of the post in the groupc_message_id (
int|None, default:None) – id of the post in question in the channeltarget_username (
str|None, default:None) – username of the reported userdate (
datetime|None, default:None) – when the report happened
- classmethod create_post_report(user_id, channel_id, c_message_id, admin_message)[source]
Adds the report of the user on a specific post
- classmethod create_user_report(user_id, target_username, admin_message)[source]
Adds the report of the user targeting another user
- 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
- classmethod get_post_report(user_id, channel_id, c_message_id)[source]
Gets the report of a specific user on a published post
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
objectClass that represents a user
- Parameters:
user_id (
int) – id of the userprivate_message_id (
int|None, default:None) – id of the private message sent by the user to the bot. Only used for followingban_date (
datetime|None, default:None) – datetime of when the user was banned. Only used for banned usersfollow_date (
datetime|None, default:None) – datetime of when the user started following a post. Only used for following users
- 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 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
- async get_user_sign(bot)[source]
Generates a sign for the user. It will be a random name for an anonym user
- 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.
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
EnumEnum 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:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- class spotted.handlers.cancel.PendingPost(user_id, u_message_id, g_message_id, admin_group_id, date, credit_username=None)[source]
Bases:
objectClass that represents a pending post
- Parameters:
user_id (
int) – id of the user that sent the postu_message_id (
int) – id of the original message of the postg_message_id (
int) – id of the post in the groupadmin_group_id (
int) – id of the admin groupcredit_username (
str|None, default:None) – username of the user that sent the post if it’s a credit postdate (
datetime) – when the post was sent
- 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:
- Returns:
PendingPost– instance of the class
- classmethod from_group(g_message_id, admin_group_id)[source]
Retrieves a pending post from the info related to the admin group
- Parameters:
- 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
- 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:
- Returns:
list[PendingPost] – list of ids of pending posts
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
EnumEnum 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:
objectCreate 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.
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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectConfigurations
- 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.
- 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:
- 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 getdefault (
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
- class spotted.handlers.db_backup.EventInfo(bot, ctx, update=None, message=None, query=None)[source]
Bases:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
NetworkErrorRaised 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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- exception spotted.handlers.follow_comment.Forbidden(message)[source]
Bases:
TelegramErrorRaised when the bot has not enough rights to perform the requested action.
Examples
Raw API BotChanged 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
objectClass that represents a user
- Parameters:
user_id (
int) – id of the userprivate_message_id (
int|None, default:None) – id of the private message sent by the user to the bot. Only used for followingban_date (
datetime|None, default:None) – datetime of when the user was banned. Only used for banned usersfollow_date (
datetime|None, default:None) – datetime of when the user started following a post. Only used for following users
- 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 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
- async get_user_sign(bot)[source]
Generates a sign for the user. It will be a random name for an anonym user
- 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.
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectConfigurations
- 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.
- 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:
- 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 getdefault (
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
- class spotted.handlers.follow_spot.EventInfo(bot, ctx, update=None, message=None, query=None)[source]
Bases:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- exception spotted.handlers.follow_spot.Forbidden(message)[source]
Bases:
TelegramErrorRaised when the bot has not enough rights to perform the requested action.
Examples
Raw API BotChanged 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:
TelegramObjectThis 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_appandpayare equal.Note
Exactly one of the optional fields must be used to specify type of the button.
Mind that
callback_gameis 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_datamay be an instance oftelegram.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 aTypeError.Changed in version 13.6.
After Bot API 6.1, only
HTTPSlinks will be allowed inlogin_url.
Examples
Inline Keyboard 1Inline Keyboard 2
See also
Changed in version 20.0:
web_appis 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
HTTPSURL used to automatically authorize the user. Can be used as a replacement for the Telegram Login Widget.Caution
Only
HTTPSlinks 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_DATAbytes. 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.
- 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:
- login_url
Optional. An
HTTPSURL used to automatically authorize the user. Can be used as a replacement for the Telegram Login Widget.Caution
Only
HTTPSlinks are allowed after Bot API 6.1.- Type:
- 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_DATAbytes.
- 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:
- 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:
- 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:
- copy_text
Optional. Description of the button that copies the specified text to the clipboard.
Added in version 21.7.
- Type:
- 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:
- 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:
- 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.
- MAX_CALLBACK_DATA: Final[int] = 64
telegram.constants.InlineKeyboardButtonLimit.MAX_CALLBACK_DATAAdded in version 20.0.
- MIN_CALLBACK_DATA: Final[int] = 1
telegram.constants.InlineKeyboardButtonLimit.MIN_CALLBACK_DATAAdded in version 20.0.
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- update_callback_data(callback_data)[source]
Sets
callback_datato the passed object. Intended to be used bytelegram.ext.CallbackDataCache.Added in version 13.6.
- class spotted.handlers.follow_spot.InlineKeyboardMarkup(inline_keyboard, *, api_kwargs=None)[source]
Bases:
TelegramObjectThis 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_keyboardand all the buttons are equal.An inline keyboard on a message
See also
Another kind of keyboard would be the
telegram.ReplyKeyboardMarkup.Examples
Inline Keyboard 1Inline Keyboard 2
- Parameters:
inline_keyboard (
Sequence[Sequence[InlineKeyboardButton]]) –Sequence of button rows, each represented by a sequence of
InlineKeyboardButtonobjects.Changed in version 20.0: |sequenceclassargs|
- inline_keyboard
Tuple of button rows, each represented by a tuple of
InlineKeyboardButtonobjects.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:
- 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:
- 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:
- 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:
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
objectClass that represents a user
- Parameters:
user_id (
int) – id of the userprivate_message_id (
int|None, default:None) – id of the private message sent by the user to the bot. Only used for followingban_date (
datetime|None, default:None) – datetime of when the user was banned. Only used for banned usersfollow_date (
datetime|None, default:None) – datetime of when the user started following a post. Only used for following users
- 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 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
- async get_user_sign(bot)[source]
Generates a sign for the user. It will be a random name for an anonym user
- 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.
- async spotted.handlers.follow_spot.follow_spot_callback(update, context)[source]
Handles the follow callback.
- Parameters:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectConfigurations
- 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.
- 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:
- 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 getdefault (
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
- class spotted.handlers.help.EventInfo(bot, ctx, update=None, message=None, query=None)[source]
Bases:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- class spotted.handlers.help.ParseMode(*values)[source]
Bases:
StringEnumThis enum contains the available parse modes. The enum members of this enumeration are instances of
strand can be treated as such.Added in version 20.0.
- MARKDOWN = 'Markdown'
Markdown parse mode.
Note
MARKDOWNis a legacy mode, retained by Telegram for backward compatibility. You should useMARKDOWN_V2instead.- Type:
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- async spotted.handlers.help.help_cmd(update, context)[source]
Handles the /help command. Sends an help message
- Parameters:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
spotted.handlers.job_handlers module
Scheduled jobs of the bot
- exception spotted.handlers.job_handlers.BadRequest(message)[source]
Bases:
NetworkErrorRaised when Telegram could not process the request correctly.
- 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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectConfigurations
- 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.
- 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:
- 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 getdefault (
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
- class spotted.handlers.job_handlers.DbManager[source]
Bases:
objectClass 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:
- 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)]”
- 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 INTOvalues (
tuple) – values to be inserted. If multiple_rows is true, tuple of tuples of values to be insertedcolumns (
tuple|str, default:'') – columns that will be inserted, as a tuple of stringsmultiple_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
- 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 FROMselect (
str, default:'*') – columns considered for the querywhere (
str, default:'') – where clause, with %s placeholders for the where_argswhere_args (
tuple|None, default:None) – args used in the where clausegroup_by (
str, default:'') – group by clauseorder_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 FROMset_clause (
str) – set clause, with %s placeholderswhere (
str, default:'') – where clause, with %s placeholders for the where argsargs (
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:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- exception spotted.handlers.job_handlers.Forbidden(message)[source]
Bases:
TelegramErrorRaised when the bot has not enough rights to perform the requested action.
Examples
Raw API BotChanged 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:
objectClass that represents a pending post
- Parameters:
user_id (
int) – id of the user that sent the postu_message_id (
int) – id of the original message of the postg_message_id (
int) – id of the post in the groupadmin_group_id (
int) – id of the admin groupcredit_username (
str|None, default:None) – username of the user that sent the post if it’s a credit postdate (
datetime) – when the post was sent
- 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:
- Returns:
PendingPost– instance of the class
- classmethod from_group(g_message_id, admin_group_id)[source]
Retrieves a pending post from the info related to the admin group
- Parameters:
- 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
- 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:
- Returns:
list[PendingPost] – list of ids of pending posts
- exception spotted.handlers.job_handlers.TelegramError(message)[source]
Bases:
ExceptionBase class for Telegram errors.
Tip
Objects of this type can be serialized via Python’s
picklemodule 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>
- 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:
objectClass that represents a user
- Parameters:
user_id (
int) – id of the userprivate_message_id (
int|None, default:None) – id of the private message sent by the user to the bot. Only used for followingban_date (
datetime|None, default:None) – datetime of when the user was banned. Only used for banned usersfollow_date (
datetime|None, default:None) – datetime of when the user started following a post. Only used for following users
- 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 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
- async get_user_sign(bot)[source]
Generates a sign for the user. It will be a random name for an anonym user
- 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.
- 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:
dateThe 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:
objectDifference 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:
tzinfoFixed 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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectConfigurations
- 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.
- 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:
- 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 getdefault (
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
- class spotted.handlers.mute.EventInfo(bot, ctx, update=None, message=None, query=None)[source]
Bases:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
objectClass that represents a user
- Parameters:
user_id (
int) – id of the userprivate_message_id (
int|None, default:None) – id of the private message sent by the user to the bot. Only used for followingban_date (
datetime|None, default:None) – datetime of when the user was banned. Only used for banned usersfollow_date (
datetime|None, default:None) – datetime of when the user started following a post. Only used for following users
- 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 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
- async get_user_sign(bot)[source]
Generates a sign for the user. It will be a random name for an anonym user
- 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.
- 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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectClass 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:
- 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)]”
- 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 INTOvalues (
tuple) – values to be inserted. If multiple_rows is true, tuple of tuples of values to be insertedcolumns (
tuple|str, default:'') – columns that will be inserted, as a tuple of stringsmultiple_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
- 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 FROMselect (
str, default:'*') – columns considered for the querywhere (
str, default:'') – where clause, with %s placeholders for the where_argswhere_args (
tuple|None, default:None) – args used in the where clausegroup_by (
str, default:'') – group by clauseorder_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 FROMset_clause (
str) – set clause, with %s placeholderswhere (
str, default:'') – where clause, with %s placeholders for the where argsargs (
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:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectConfigurations
- 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.
- 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:
- 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 getdefault (
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
- class spotted.handlers.reload.EventInfo(bot, ctx, update=None, message=None, query=None)[source]
Bases:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- class spotted.handlers.reply.PendingPost(user_id, u_message_id, g_message_id, admin_group_id, date, credit_username=None)[source]
Bases:
objectClass that represents a pending post
- Parameters:
user_id (
int) – id of the user that sent the postu_message_id (
int) – id of the original message of the postg_message_id (
int) – id of the post in the groupadmin_group_id (
int) – id of the admin groupcredit_username (
str|None, default:None) – username of the user that sent the post if it’s a credit postdate (
datetime) – when the post was sent
- 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:
- Returns:
PendingPost– instance of the class
- classmethod from_group(g_message_id, admin_group_id)[source]
Retrieves a pending post from the info related to the admin group
- Parameters:
- 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
- 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:
- Returns:
list[PendingPost] – list of ids of pending posts
- 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:
objectClass that represents a report
- Parameters:
user_id (
int) – id of the user that reportedadmin_group_id (
int) – id of the admin groupg_message_id (
int) – id of the post in the groupc_message_id (
int|None, default:None) – id of the post in question in the channeltarget_username (
str|None, default:None) – username of the reported userdate (
datetime|None, default:None) – when the report happened
- classmethod create_post_report(user_id, channel_id, c_message_id, admin_message)[source]
Adds the report of the user on a specific post
- classmethod create_user_report(user_id, target_username, admin_message)[source]
Adds the report of the user targeting another user
- 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
- classmethod get_post_report(user_id, channel_id, c_message_id)[source]
Gets the report of a specific user on a published post
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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
remodule for more information.Note
If your bot allows arbitrary objects as
~telegram.InlineKeyboardButton.callback_data, it may happen that the originalcallback_datafor the incomingtelegram.CallbackQuerycan not be found. This is the case when either a malicious client tempered with thetelegram.CallbackQuery.dataor the data was simply dropped from cache or not persisted. In these cases, an instance oftelegram.ext.InvalidCallbackDatawill be set astelegram.CallbackQuery.data.Added in version 13.6.
If neither
patternnorgame_patternis set, anyCallbackQuerywill be handled. If onlypatternis set, queries withgame_short_namewill not be considered and vice versa. If both patterns are set, queries with either :attr: ~telegram.CallbackQuery.game_short_name ordatamatching the defined pattern will be handledAdded in version 21.5.
Warning
When setting
blocktoFalse, you cannot rely on adding custom attributes totelegram.ext.CallbackContext. See its docs for more info.- Parameters:
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.pattern (
str|Pattern[str] |type|Callable[[object],bool|None] |None, default:None) –Pattern to test
telegram.CallbackQuery.dataagainst. If a string or a regex pattern is passed,re.match()is used ontelegram.CallbackQuery.datato determine if an update should be handled by this handler. If your bot allows arbitrary objects as~telegram.InlineKeyboardButton.callback_data, non-strings will be accepted. To filter arbitrary objects you may pass:a callable, accepting exactly one argument, namely the
telegram.CallbackQuery.data. It must returnTrueorFalse/Noneto indicate, whether the update should be handled.a
type. Iftelegram.CallbackQuery.datais an instance of that type (or a subclass), the update will be handled.
If
telegram.CallbackQuery.dataisNone, thetelegram.CallbackQueryupdate will not be handled.See also
Arbitrary callback_data <Arbitrary-callback_data>Changed in version 13.6: Added support for arbitrary callback data.
game_pattern (
str|Pattern[str] |None, default:None) –Pattern to test
telegram.CallbackQuery.game_short_nameagainst. If a string or a regex pattern is passed,re.match()is used ontelegram.CallbackQuery.game_short_nameto determine if an update should be handled by this handler.Added in version 21.5.
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 toTrue.See also
Concurrency
- callback
The callback function for this handler.
- Type:
- pattern
Optional. Regex pattern, callback or type to test
telegram.CallbackQuery.dataagainst.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:
- block
Determines whether the return value of the callback should be awaited before processing the next handler in
telegram.ext.Application.process_update().- Type:
- check_update(update)[source]
Determines whether an update should be passed to this handler’s
callback.
- collect_additional_context(context, update, application, check_result)[source]
Add the result of
re.match(pattern, update.callback_query.data)toCallbackContext.matchesas list with one element.- Return type:
- 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 alistto theCallbackContextnamedCallbackContext.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_MESSAGEin the filter argument.Note
CommandHandlerdoes not handle (edited) channel posts and does not handle commands that are part of a caption. Please useMessageHandlerwith a suitable combination of filters (e.g.telegram.ext.filters.UpdateType.CHANNEL_POSTS,telegram.ext.filters.CAPTIONandtelegram.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 thetelegram.ext.PrefixHandler.Warning
When setting
blocktoFalse, you cannot rely on adding custom attributes totelegram.ext.CallbackContext. See its docs for more info.Examples
Timer BotError Handler Bot
Changed in version 20.0:
- Parameters:
command (
str|Collection[str]) – The command or list of commands this handler should listen for. Case-insensitive. Limitations are the same as fortelegram.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 fromtelegram.ext.filters.BaseFilter. Standard filters can be found intelegram.ext.filters. Filters can be combined using bitwise operators (&forand,|foror,~fornot)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 toTrue.See also
Concurrencyhas_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. IfFalse, the handler will only process if there are no args. ifint, the handler will only process if there are exactly that many args. Defaults toNone, 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.
- callback
The callback function for this handler.
- Type:
- filters
Optional. Only allow updates with these filters.
- block
Determines whether the return value of the callback should be awaited before processing the next handler in
telegram.ext.Application.process_update().- Type:
- has_args
Optional argument, otherwise all implementations of
CommandHandlerwill break. Defaults toNone, which means the handler will process any args or no args.Added in version 20.5.
- check_update(update)[source]
Determines whether an update should be passed to this handler’s
callback.
- collect_additional_context(context, update, application, check_result)[source]
Add text after the command to
CallbackContext.argsas list, split on single whitespaces and add output of data filters toCallbackContextas well.- Return type:
- filters: filters_module.BaseFilter
- class spotted.handlers.report_spot.Config[source]
Bases:
objectConfigurations
- 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.
- 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:
- 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 getdefault (
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
- 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
ConversationHandlerheavily relies on incoming updates being processed one by one. When using this handler,telegram.ext.ApplicationBuilder.concurrent_updatesshould be set toFalse.Note
ConversationHandlerwill only accept updates that are (subclass-)instances oftelegram.Update. This is, because depending on theper_userandper_chat,ConversationHandlerrelies ontelegram.Update.effective_userand/ortelegram.Update.effective_chatin order to determine which conversation an update should belong to. Forper_message=True,ConversationHandlerusesupdate.callback_query.message.message_idwhenper_chat=Trueandupdate.callback_query.inline_message_idwhenper_chat=False. For a more detailed explanation, please see our FAQ.Finally,
ConversationHandler, does not handle (edited) channel posts.The first collection, a
listnamedentry_points, is used to initiate the conversation, for example with atelegram.ext.CommandHandlerortelegram.ext.MessageHandler.The second collection, a
dictnamedstates, 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 forTIMEOUTto define the behavior whenconversation_timeoutis exceeded, and a state forWAITINGto define behavior when a new update is received while the previousblock=Falsehandler is not finished.The third collection, a
listnamedfallbacks, 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/cancelcommand 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
Noneby default), the state will not change. If an entry point callback function returnsNone, the conversation ends immediately after the execution of this callback function. To end the conversation, the callback function must returnENDor-1. To handle the conversation timeout, use handlerTIMEOUTor-2. Finally,telegram.ext.ApplicationHandlerStopcan 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 childConversationHandlershould have the attributemap_to_parentwhich allows returning to the parent conversation at specified states within the child conversation.Note that the keys in
map_to_parentmust not appear as keys instatesattribute or else the latter will be ignored. You may mapENDto one of the parents states to continue the parent conversation after the child conversation has ended or even map a state toENDto end the parent conversation from within the child conversation. For an example on nestedConversationHandlers, seeexamples.nestedconversationbot.Examples
Conversation BotConversation Bot 2Nested Conversation BotPersistent Conversation Bot
- Parameters:
entry_points (
list[BaseHandler[Update,TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]),object]]) – A list ofBaseHandlerobjects that can trigger the start of the conversation. The first handler whosecheck_update()method returnsTruewill be used. If all returnFalse, the update is not handled.states (
dict[object,list[BaseHandler[Update,TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]),object]]]) – Adictthat defines the different states of conversation a user can be in and one or more associatedBaseHandlerobjects that should be used in that state. The first handler whosecheck_update()method returnsTruewill 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 returnedFalseoncheck_update(). The first handler whichcheck_update()method returnsTruewill be used. If all returnFalse, the update is not handled.allow_reentry (
bool, default:False) – If set toTrue, a user that is currently in a conversation can restart the conversation by triggering one of the entry points. Default isFalse.per_chat (
bool, default:True) – If the conversation key should contain the Chat’s ID. Default isTrue.per_user (
bool, default:True) – If the conversation key should contain the User’s ID. Default isTrue.per_message (
bool, default:False) – If the conversation key should contain the Message’s ID. Default isFalse.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
0orNone(default), there will be no timeout. The last received update and the correspondingcontextwill be handled by ALL the handler’s whosecheck_update()method returnsTruethat are in the stateConversationHandler.TIMEOUT.Caution
This feature relies on the
telegram.ext.Application.job_queuebeing set and hence requires that the dependencies thattelegram.ext.JobQueuerelies on are installed.Using
conversation_timeoutwith 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.
nameis required and persistence has to be set inApplication.Changed in version 20.0: Was previously named as
persistence.map_to_parent (
dict[object,object] |None, default:None) – Adictthat 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
FalseorTrueto set a default value for theBaseHandler.blocksetting of all handlers (inentry_points,statesandfallbacks). The resolution order for checking if a handler should be run non-blocking is:telegram.ext.BaseHandler.block(if set)the value passed to this parameter (if any)
telegram.ext.Defaults.block(if defaults are used)
See also
ConcurrencyChanged in version 20.0: No longer overrides the handlers settings. Resolution order was changed.
- Raises:
ValueError – If
persistentis used butnamewas not set, or whenper_message,per_chat,per_userare allFalse.
- block
Determines whether the callback will run in a blocking way. Always
Truesince conversation handlers handle any non-blocking callbacks internally.- Type:
- TIMEOUT: Final[int] = -2
Used as a constant to handle state when a conversation is timed out (exceeded
conversation_timeout).- Type:
- WAITING: Final[int] = -3
Used as a constant to handle state when a conversation is still waiting on the previous
block=Falsehandler to finish.- Type:
- property allow_reentry: bool
Determines if a user can restart a conversation with an entry point.
- Type:
- 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.
- property conversation_timeout: float | timedelta | None
Optional. When this handler is inactive more than this timeout (in seconds), it will be automatically ended.
- Type:
- property entry_points: list[BaseHandler[Update, CCT, object]]
A list of
BaseHandlerobjects 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
Falseoncheck_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 fromcheck_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:
- property map_to_parent: dict[object, object] | None
Optional. A
dictthat can be used to instruct a nestedConversationHandlerto transition into a mapped state on its parentConversationHandlerin place of a specified nested state.
- property name: str | None
Optional. The name for this
ConversationHandler.- Type:
- property persistent: bool
Optional. If the conversations dict for this handler should be saved.
nameis required and persistence has to be set inApplication.- Type:
- property states: dict[object, list[BaseHandler[Update, CCT, object]]]
A
dictthat defines the different states of conversation a user can be in and one or more associatedBaseHandlerobjects that should be used in that state.- Type:
dict[
object, list[telegram.ext.BaseHandler]]
- class spotted.handlers.report_spot.ConversationState(*values)[source]
Bases:
EnumEnum 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:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- exception spotted.handlers.report_spot.Forbidden(message)[source]
Bases:
TelegramErrorRaised when the bot has not enough rights to perform the requested action.
Examples
Raw API BotChanged 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
blocktoFalse, you cannot rely on adding custom attributes totelegram.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 intelegram.ext.filters. Filters can be combined using bitwise operators (& for and, | for or, ~ for not). PassingNoneis a shortcut to passingtelegram.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 toTrue.See also
Concurrency
- filters
Only allow updates with these Filters. See
telegram.ext.filtersfor a full list of all available filters.
- callback
The callback function for this handler.
- Type:
- block
Determines whether the return value of the callback should be awaited before processing the next handler in
telegram.ext.Application.process_update().- Type:
- check_update(update)[source]
Determines whether an update should be passed to this handler’s
callback.
- collect_additional_context(context, update, application, check_result)[source]
Adds possible output of data filters to the
CallbackContext.- Return type:
- 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:
objectClass that represents a report
- Parameters:
user_id (
int) – id of the user that reportedadmin_group_id (
int) – id of the admin groupg_message_id (
int) – id of the post in the groupc_message_id (
int|None, default:None) – id of the post in question in the channeltarget_username (
str|None, default:None) – username of the reported userdate (
datetime|None, default:None) – when the report happened
- classmethod create_post_report(user_id, channel_id, c_message_id, admin_message)[source]
Adds the report of the user on a specific post
- classmethod create_user_report(user_id, target_username, admin_message)[source]
Adds the report of the user targeting another user
- 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
- classmethod get_post_report(user_id, channel_id, c_message_id)[source]
Gets the report of a specific user on a published post
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
objectClass that represents a user
- Parameters:
user_id (
int) – id of the userprivate_message_id (
int|None, default:None) – id of the private message sent by the user to the bot. Only used for followingban_date (
datetime|None, default:None) – datetime of when the user was banned. Only used for banned usersfollow_date (
datetime|None, default:None) – datetime of when the user started following a post. Only used for following users
- 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 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
- async get_user_sign(bot)[source]
Generates a sign for the user. It will be a random name for an anonym user
- 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.
- 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
- async spotted.handlers.report_spot.report_spot_callback(update, context)[source]
Handles the report callback.
- Parameters:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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 alistto theCallbackContextnamedCallbackContext.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_MESSAGEin the filter argument.Note
CommandHandlerdoes not handle (edited) channel posts and does not handle commands that are part of a caption. Please useMessageHandlerwith a suitable combination of filters (e.g.telegram.ext.filters.UpdateType.CHANNEL_POSTS,telegram.ext.filters.CAPTIONandtelegram.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 thetelegram.ext.PrefixHandler.Warning
When setting
blocktoFalse, you cannot rely on adding custom attributes totelegram.ext.CallbackContext. See its docs for more info.Examples
Timer BotError Handler Bot
Changed in version 20.0:
- Parameters:
command (
str|Collection[str]) – The command or list of commands this handler should listen for. Case-insensitive. Limitations are the same as fortelegram.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 fromtelegram.ext.filters.BaseFilter. Standard filters can be found intelegram.ext.filters. Filters can be combined using bitwise operators (&forand,|foror,~fornot)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 toTrue.See also
Concurrencyhas_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. IfFalse, the handler will only process if there are no args. ifint, the handler will only process if there are exactly that many args. Defaults toNone, 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.
- callback
The callback function for this handler.
- Type:
- filters
Optional. Only allow updates with these filters.
- block
Determines whether the return value of the callback should be awaited before processing the next handler in
telegram.ext.Application.process_update().- Type:
- has_args
Optional argument, otherwise all implementations of
CommandHandlerwill break. Defaults toNone, which means the handler will process any args or no args.Added in version 20.5.
- check_update(update)[source]
Determines whether an update should be passed to this handler’s
callback.
- collect_additional_context(context, update, application, check_result)[source]
Add text after the command to
CallbackContext.argsas list, split on single whitespaces and add output of data filters toCallbackContextas well.- Return type:
- filters: filters_module.BaseFilter
- class spotted.handlers.report_user.Config[source]
Bases:
objectConfigurations
- 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.
- 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:
- 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 getdefault (
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
- 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
ConversationHandlerheavily relies on incoming updates being processed one by one. When using this handler,telegram.ext.ApplicationBuilder.concurrent_updatesshould be set toFalse.Note
ConversationHandlerwill only accept updates that are (subclass-)instances oftelegram.Update. This is, because depending on theper_userandper_chat,ConversationHandlerrelies ontelegram.Update.effective_userand/ortelegram.Update.effective_chatin order to determine which conversation an update should belong to. Forper_message=True,ConversationHandlerusesupdate.callback_query.message.message_idwhenper_chat=Trueandupdate.callback_query.inline_message_idwhenper_chat=False. For a more detailed explanation, please see our FAQ.Finally,
ConversationHandler, does not handle (edited) channel posts.The first collection, a
listnamedentry_points, is used to initiate the conversation, for example with atelegram.ext.CommandHandlerortelegram.ext.MessageHandler.The second collection, a
dictnamedstates, 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 forTIMEOUTto define the behavior whenconversation_timeoutis exceeded, and a state forWAITINGto define behavior when a new update is received while the previousblock=Falsehandler is not finished.The third collection, a
listnamedfallbacks, 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/cancelcommand 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
Noneby default), the state will not change. If an entry point callback function returnsNone, the conversation ends immediately after the execution of this callback function. To end the conversation, the callback function must returnENDor-1. To handle the conversation timeout, use handlerTIMEOUTor-2. Finally,telegram.ext.ApplicationHandlerStopcan 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 childConversationHandlershould have the attributemap_to_parentwhich allows returning to the parent conversation at specified states within the child conversation.Note that the keys in
map_to_parentmust not appear as keys instatesattribute or else the latter will be ignored. You may mapENDto one of the parents states to continue the parent conversation after the child conversation has ended or even map a state toENDto end the parent conversation from within the child conversation. For an example on nestedConversationHandlers, seeexamples.nestedconversationbot.Examples
Conversation BotConversation Bot 2Nested Conversation BotPersistent Conversation Bot
- Parameters:
entry_points (
list[BaseHandler[Update,TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]),object]]) – A list ofBaseHandlerobjects that can trigger the start of the conversation. The first handler whosecheck_update()method returnsTruewill be used. If all returnFalse, the update is not handled.states (
dict[object,list[BaseHandler[Update,TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]),object]]]) – Adictthat defines the different states of conversation a user can be in and one or more associatedBaseHandlerobjects that should be used in that state. The first handler whosecheck_update()method returnsTruewill 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 returnedFalseoncheck_update(). The first handler whichcheck_update()method returnsTruewill be used. If all returnFalse, the update is not handled.allow_reentry (
bool, default:False) – If set toTrue, a user that is currently in a conversation can restart the conversation by triggering one of the entry points. Default isFalse.per_chat (
bool, default:True) – If the conversation key should contain the Chat’s ID. Default isTrue.per_user (
bool, default:True) – If the conversation key should contain the User’s ID. Default isTrue.per_message (
bool, default:False) – If the conversation key should contain the Message’s ID. Default isFalse.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
0orNone(default), there will be no timeout. The last received update and the correspondingcontextwill be handled by ALL the handler’s whosecheck_update()method returnsTruethat are in the stateConversationHandler.TIMEOUT.Caution
This feature relies on the
telegram.ext.Application.job_queuebeing set and hence requires that the dependencies thattelegram.ext.JobQueuerelies on are installed.Using
conversation_timeoutwith 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.
nameis required and persistence has to be set inApplication.Changed in version 20.0: Was previously named as
persistence.map_to_parent (
dict[object,object] |None, default:None) – Adictthat 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
FalseorTrueto set a default value for theBaseHandler.blocksetting of all handlers (inentry_points,statesandfallbacks). The resolution order for checking if a handler should be run non-blocking is:telegram.ext.BaseHandler.block(if set)the value passed to this parameter (if any)
telegram.ext.Defaults.block(if defaults are used)
See also
ConcurrencyChanged in version 20.0: No longer overrides the handlers settings. Resolution order was changed.
- Raises:
ValueError – If
persistentis used butnamewas not set, or whenper_message,per_chat,per_userare allFalse.
- block
Determines whether the callback will run in a blocking way. Always
Truesince conversation handlers handle any non-blocking callbacks internally.- Type:
- TIMEOUT: Final[int] = -2
Used as a constant to handle state when a conversation is timed out (exceeded
conversation_timeout).- Type:
- WAITING: Final[int] = -3
Used as a constant to handle state when a conversation is still waiting on the previous
block=Falsehandler to finish.- Type:
- property allow_reentry: bool
Determines if a user can restart a conversation with an entry point.
- Type:
- 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.
- property conversation_timeout: float | timedelta | None
Optional. When this handler is inactive more than this timeout (in seconds), it will be automatically ended.
- Type:
- property entry_points: list[BaseHandler[Update, CCT, object]]
A list of
BaseHandlerobjects 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
Falseoncheck_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 fromcheck_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:
- property map_to_parent: dict[object, object] | None
Optional. A
dictthat can be used to instruct a nestedConversationHandlerto transition into a mapped state on its parentConversationHandlerin place of a specified nested state.
- property name: str | None
Optional. The name for this
ConversationHandler.- Type:
- property persistent: bool
Optional. If the conversations dict for this handler should be saved.
nameis required and persistence has to be set inApplication.- Type:
- property states: dict[object, list[BaseHandler[Update, CCT, object]]]
A
dictthat defines the different states of conversation a user can be in and one or more associatedBaseHandlerobjects that should be used in that state.- Type:
dict[
object, list[telegram.ext.BaseHandler]]
- class spotted.handlers.report_user.ConversationState(*values)[source]
Bases:
EnumEnum 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:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- 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
blocktoFalse, you cannot rely on adding custom attributes totelegram.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 intelegram.ext.filters. Filters can be combined using bitwise operators (& for and, | for or, ~ for not). PassingNoneis a shortcut to passingtelegram.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 toTrue.See also
Concurrency
- filters
Only allow updates with these Filters. See
telegram.ext.filtersfor a full list of all available filters.
- callback
The callback function for this handler.
- Type:
- block
Determines whether the return value of the callback should be awaited before processing the next handler in
telegram.ext.Application.process_update().- Type:
- check_update(update)[source]
Determines whether an update should be passed to this handler’s
callback.
- collect_additional_context(context, update, application, check_result)[source]
Adds possible output of data filters to the
CallbackContext.- Return type:
- 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:
objectClass that represents a report
- Parameters:
user_id (
int) – id of the user that reportedadmin_group_id (
int) – id of the admin groupg_message_id (
int) – id of the post in the groupc_message_id (
int|None, default:None) – id of the post in question in the channeltarget_username (
str|None, default:None) – username of the reported userdate (
datetime|None, default:None) – when the report happened
- classmethod create_post_report(user_id, channel_id, c_message_id, admin_message)[source]
Adds the report of the user on a specific post
- classmethod create_user_report(user_id, target_username, admin_message)[source]
Adds the report of the user targeting another user
- 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
- classmethod get_post_report(user_id, channel_id, c_message_id)[source]
Gets the report of a specific user on a published post
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- class spotted.handlers.rules.ParseMode(*values)[source]
Bases:
StringEnumThis enum contains the available parse modes. The enum members of this enumeration are instances of
strand can be treated as such.Added in version 20.0.
- MARKDOWN = 'Markdown'
Markdown parse mode.
Note
MARKDOWNis a legacy mode, retained by Telegram for backward compatibility. You should useMARKDOWN_V2instead.- Type:
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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’]
- async spotted.handlers.rules.rules_cmd(update, context)[source]
Handles the /rules command. Sends a message containing the rules
- Parameters:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- exception spotted.handlers.sban.TelegramError(message)[source]
Bases:
ExceptionBase class for Telegram errors.
Tip
Objects of this type can be serialized via Python’s
picklemodule 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>
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
objectClass that represents a user
- Parameters:
user_id (
int) – id of the userprivate_message_id (
int|None, default:None) – id of the private message sent by the user to the bot. Only used for followingban_date (
datetime|None, default:None) – datetime of when the user was banned. Only used for banned usersfollow_date (
datetime|None, default:None) – datetime of when the user started following a post. Only used for following users
- 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 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
- async get_user_sign(bot)[source]
Generates a sign for the user. It will be a random name for an anonym user
- 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.
- 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.
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- class spotted.handlers.settings.ParseMode(*values)[source]
Bases:
StringEnumThis enum contains the available parse modes. The enum members of this enumeration are instances of
strand can be treated as such.Added in version 20.0.
- MARKDOWN = 'Markdown'
Markdown parse mode.
Note
MARKDOWNis a legacy mode, retained by Telegram for backward compatibility. You should useMARKDOWN_V2instead.- Type:
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
objectClass that represents a user
- Parameters:
user_id (
int) – id of the userprivate_message_id (
int|None, default:None) – id of the private message sent by the user to the bot. Only used for followingban_date (
datetime|None, default:None) – datetime of when the user was banned. Only used for banned usersfollow_date (
datetime|None, default:None) – datetime of when the user started following a post. Only used for following users
- 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 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
- async get_user_sign(bot)[source]
Generates a sign for the user. It will be a random name for an anonym user
- 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.
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectConfigurations
- 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.
- 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:
- 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 getdefault (
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
- class spotted.handlers.spam_comment.EventInfo(bot, ctx, update=None, message=None, query=None)[source]
Bases:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- Return type:
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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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
remodule for more information.Note
If your bot allows arbitrary objects as
~telegram.InlineKeyboardButton.callback_data, it may happen that the originalcallback_datafor the incomingtelegram.CallbackQuerycan not be found. This is the case when either a malicious client tempered with thetelegram.CallbackQuery.dataor the data was simply dropped from cache or not persisted. In these cases, an instance oftelegram.ext.InvalidCallbackDatawill be set astelegram.CallbackQuery.data.Added in version 13.6.
If neither
patternnorgame_patternis set, anyCallbackQuerywill be handled. If onlypatternis set, queries withgame_short_namewill not be considered and vice versa. If both patterns are set, queries with either :attr: ~telegram.CallbackQuery.game_short_name ordatamatching the defined pattern will be handledAdded in version 21.5.
Warning
When setting
blocktoFalse, you cannot rely on adding custom attributes totelegram.ext.CallbackContext. See its docs for more info.- Parameters:
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.pattern (
str|Pattern[str] |type|Callable[[object],bool|None] |None, default:None) –Pattern to test
telegram.CallbackQuery.dataagainst. If a string or a regex pattern is passed,re.match()is used ontelegram.CallbackQuery.datato determine if an update should be handled by this handler. If your bot allows arbitrary objects as~telegram.InlineKeyboardButton.callback_data, non-strings will be accepted. To filter arbitrary objects you may pass:a callable, accepting exactly one argument, namely the
telegram.CallbackQuery.data. It must returnTrueorFalse/Noneto indicate, whether the update should be handled.a
type. Iftelegram.CallbackQuery.datais an instance of that type (or a subclass), the update will be handled.
If
telegram.CallbackQuery.dataisNone, thetelegram.CallbackQueryupdate will not be handled.See also
Arbitrary callback_data <Arbitrary-callback_data>Changed in version 13.6: Added support for arbitrary callback data.
game_pattern (
str|Pattern[str] |None, default:None) –Pattern to test
telegram.CallbackQuery.game_short_nameagainst. If a string or a regex pattern is passed,re.match()is used ontelegram.CallbackQuery.game_short_nameto determine if an update should be handled by this handler.Added in version 21.5.
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 toTrue.See also
Concurrency
- callback
The callback function for this handler.
- Type:
- pattern
Optional. Regex pattern, callback or type to test
telegram.CallbackQuery.dataagainst.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:
- block
Determines whether the return value of the callback should be awaited before processing the next handler in
telegram.ext.Application.process_update().- Type:
- check_update(update)[source]
Determines whether an update should be passed to this handler’s
callback.
- collect_additional_context(context, update, application, check_result)[source]
Add the result of
re.match(pattern, update.callback_query.data)toCallbackContext.matchesas list with one element.- Return type:
- 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 alistto theCallbackContextnamedCallbackContext.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_MESSAGEin the filter argument.Note
CommandHandlerdoes not handle (edited) channel posts and does not handle commands that are part of a caption. Please useMessageHandlerwith a suitable combination of filters (e.g.telegram.ext.filters.UpdateType.CHANNEL_POSTS,telegram.ext.filters.CAPTIONandtelegram.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 thetelegram.ext.PrefixHandler.Warning
When setting
blocktoFalse, you cannot rely on adding custom attributes totelegram.ext.CallbackContext. See its docs for more info.Examples
Timer BotError Handler Bot
Changed in version 20.0:
- Parameters:
command (
str|Collection[str]) – The command or list of commands this handler should listen for. Case-insensitive. Limitations are the same as fortelegram.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 fromtelegram.ext.filters.BaseFilter. Standard filters can be found intelegram.ext.filters. Filters can be combined using bitwise operators (&forand,|foror,~fornot)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 toTrue.See also
Concurrencyhas_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. IfFalse, the handler will only process if there are no args. ifint, the handler will only process if there are exactly that many args. Defaults toNone, 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.
- callback
The callback function for this handler.
- Type:
- filters
Optional. Only allow updates with these filters.
- block
Determines whether the return value of the callback should be awaited before processing the next handler in
telegram.ext.Application.process_update().- Type:
- has_args
Optional argument, otherwise all implementations of
CommandHandlerwill break. Defaults toNone, which means the handler will process any args or no args.Added in version 20.5.
- check_update(update)[source]
Determines whether an update should be passed to this handler’s
callback.
- collect_additional_context(context, update, application, check_result)[source]
Add text after the command to
CallbackContext.argsas list, split on single whitespaces and add output of data filters toCallbackContextas well.- Return type:
- filters: filters_module.BaseFilter
- class spotted.handlers.spot.Config[source]
Bases:
objectConfigurations
- 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.
- 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:
- 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 getdefault (
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
- 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
ConversationHandlerheavily relies on incoming updates being processed one by one. When using this handler,telegram.ext.ApplicationBuilder.concurrent_updatesshould be set toFalse.Note
ConversationHandlerwill only accept updates that are (subclass-)instances oftelegram.Update. This is, because depending on theper_userandper_chat,ConversationHandlerrelies ontelegram.Update.effective_userand/ortelegram.Update.effective_chatin order to determine which conversation an update should belong to. Forper_message=True,ConversationHandlerusesupdate.callback_query.message.message_idwhenper_chat=Trueandupdate.callback_query.inline_message_idwhenper_chat=False. For a more detailed explanation, please see our FAQ.Finally,
ConversationHandler, does not handle (edited) channel posts.The first collection, a
listnamedentry_points, is used to initiate the conversation, for example with atelegram.ext.CommandHandlerortelegram.ext.MessageHandler.The second collection, a
dictnamedstates, 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 forTIMEOUTto define the behavior whenconversation_timeoutis exceeded, and a state forWAITINGto define behavior when a new update is received while the previousblock=Falsehandler is not finished.The third collection, a
listnamedfallbacks, 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/cancelcommand 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
Noneby default), the state will not change. If an entry point callback function returnsNone, the conversation ends immediately after the execution of this callback function. To end the conversation, the callback function must returnENDor-1. To handle the conversation timeout, use handlerTIMEOUTor-2. Finally,telegram.ext.ApplicationHandlerStopcan 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 childConversationHandlershould have the attributemap_to_parentwhich allows returning to the parent conversation at specified states within the child conversation.Note that the keys in
map_to_parentmust not appear as keys instatesattribute or else the latter will be ignored. You may mapENDto one of the parents states to continue the parent conversation after the child conversation has ended or even map a state toENDto end the parent conversation from within the child conversation. For an example on nestedConversationHandlers, seeexamples.nestedconversationbot.Examples
Conversation BotConversation Bot 2Nested Conversation BotPersistent Conversation Bot
- Parameters:
entry_points (
list[BaseHandler[Update,TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]),object]]) – A list ofBaseHandlerobjects that can trigger the start of the conversation. The first handler whosecheck_update()method returnsTruewill be used. If all returnFalse, the update is not handled.states (
dict[object,list[BaseHandler[Update,TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]),object]]]) – Adictthat defines the different states of conversation a user can be in and one or more associatedBaseHandlerobjects that should be used in that state. The first handler whosecheck_update()method returnsTruewill 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 returnedFalseoncheck_update(). The first handler whichcheck_update()method returnsTruewill be used. If all returnFalse, the update is not handled.allow_reentry (
bool, default:False) – If set toTrue, a user that is currently in a conversation can restart the conversation by triggering one of the entry points. Default isFalse.per_chat (
bool, default:True) – If the conversation key should contain the Chat’s ID. Default isTrue.per_user (
bool, default:True) – If the conversation key should contain the User’s ID. Default isTrue.per_message (
bool, default:False) – If the conversation key should contain the Message’s ID. Default isFalse.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
0orNone(default), there will be no timeout. The last received update and the correspondingcontextwill be handled by ALL the handler’s whosecheck_update()method returnsTruethat are in the stateConversationHandler.TIMEOUT.Caution
This feature relies on the
telegram.ext.Application.job_queuebeing set and hence requires that the dependencies thattelegram.ext.JobQueuerelies on are installed.Using
conversation_timeoutwith 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.
nameis required and persistence has to be set inApplication.Changed in version 20.0: Was previously named as
persistence.map_to_parent (
dict[object,object] |None, default:None) – Adictthat 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
FalseorTrueto set a default value for theBaseHandler.blocksetting of all handlers (inentry_points,statesandfallbacks). The resolution order for checking if a handler should be run non-blocking is:telegram.ext.BaseHandler.block(if set)the value passed to this parameter (if any)
telegram.ext.Defaults.block(if defaults are used)
See also
ConcurrencyChanged in version 20.0: No longer overrides the handlers settings. Resolution order was changed.
- Raises:
ValueError – If
persistentis used butnamewas not set, or whenper_message,per_chat,per_userare allFalse.
- block
Determines whether the callback will run in a blocking way. Always
Truesince conversation handlers handle any non-blocking callbacks internally.- Type:
- TIMEOUT: Final[int] = -2
Used as a constant to handle state when a conversation is timed out (exceeded
conversation_timeout).- Type:
- WAITING: Final[int] = -3
Used as a constant to handle state when a conversation is still waiting on the previous
block=Falsehandler to finish.- Type:
- property allow_reentry: bool
Determines if a user can restart a conversation with an entry point.
- Type:
- 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.
- property conversation_timeout: float | timedelta | None
Optional. When this handler is inactive more than this timeout (in seconds), it will be automatically ended.
- Type:
- property entry_points: list[BaseHandler[Update, CCT, object]]
A list of
BaseHandlerobjects 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
Falseoncheck_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 fromcheck_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:
- property map_to_parent: dict[object, object] | None
Optional. A
dictthat can be used to instruct a nestedConversationHandlerto transition into a mapped state on its parentConversationHandlerin place of a specified nested state.
- property name: str | None
Optional. The name for this
ConversationHandler.- Type:
- property persistent: bool
Optional. If the conversations dict for this handler should be saved.
nameis required and persistence has to be set inApplication.- Type:
- property states: dict[object, list[BaseHandler[Update, CCT, object]]]
A
dictthat defines the different states of conversation a user can be in and one or more associatedBaseHandlerobjects that should be used in that state.- Type:
dict[
object, list[telegram.ext.BaseHandler]]
- class spotted.handlers.spot.ConversationState(*values)[source]
Bases:
EnumEnum 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:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- 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
blocktoFalse, you cannot rely on adding custom attributes totelegram.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 intelegram.ext.filters. Filters can be combined using bitwise operators (& for and, | for or, ~ for not). PassingNoneis a shortcut to passingtelegram.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 toTrue.See also
Concurrency
- filters
Only allow updates with these Filters. See
telegram.ext.filtersfor a full list of all available filters.
- callback
The callback function for this handler.
- Type:
- block
Determines whether the return value of the callback should be awaited before processing the next handler in
telegram.ext.Application.process_update().- Type:
- check_update(update)[source]
Determines whether an update should be passed to this handler’s
callback.
- collect_additional_context(context, update, application, check_result)[source]
Adds possible output of data filters to the
CallbackContext.- Return type:
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
objectClass that represents a user
- Parameters:
user_id (
int) – id of the userprivate_message_id (
int|None, default:None) – id of the private message sent by the user to the bot. Only used for followingban_date (
datetime|None, default:None) – datetime of when the user was banned. Only used for banned usersfollow_date (
datetime|None, default:None) – datetime of when the user started following a post. Only used for following users
- 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 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
- async get_user_sign(bot)[source]
Generates a sign for the user. It will be a random name for an anonym user
- 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.
- 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
- 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’]
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
- 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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- class spotted.handlers.start.ParseMode(*values)[source]
Bases:
StringEnumThis enum contains the available parse modes. The enum members of this enumeration are instances of
strand can be treated as such.Added in version 20.0.
- MARKDOWN = 'Markdown'
Markdown parse mode.
Note
MARKDOWNis a legacy mode, retained by Telegram for backward compatibility. You should useMARKDOWN_V2instead.- Type:
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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’]
- async spotted.handlers.start.start_cmd(update, context)[source]
Handles the /start command. Sends a welcoming message
- Parameters:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- exception spotted.handlers.unmute.TelegramError(message)[source]
Bases:
ExceptionBase class for Telegram errors.
Tip
Objects of this type can be serialized via Python’s
picklemodule 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>
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
objectClass that represents a user
- Parameters:
user_id (
int) – id of the userprivate_message_id (
int|None, default:None) – id of the private message sent by the user to the bot. Only used for followingban_date (
datetime|None, default:None) – datetime of when the user was banned. Only used for banned usersfollow_date (
datetime|None, default:None) – datetime of when the user started following a post. Only used for following users
- 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 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
- async get_user_sign(bot)[source]
Generates a sign for the user. It will be a random name for an anonym user
- 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.
- 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.
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler
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.BaseHandleror by thetelegram.ext.Applicationin an error handler added bytelegram.ext.Application.add_error_handleror to the callback of atelegram.ext.Job.Note
telegram.ext.Applicationwill 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 sameCallbackContextobject (of course with proper attributes likematchesdiffering). 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 onCallbackContextmight 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.blockset toFalseortelegram.ext.Application.concurrent_updatesset toTrue. 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
Genericclass and accepts four type variables:The type of
bot. Must betelegram.Botor a subclass of that class.
Examples
Context Types BotCustom 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 withblock=False.- Type:
- matches
Optional. If the associated update originated from a
filters.Regex, this will contain a list of match objects for every pattern wherere.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.PrefixHandlerortelegram.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:
- job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Jobor in error handlers if the error is caused by a job.Changed in version 20.0:
jobis now also present in error handlers if the error is caused by a job.- Type:
- property application: Application[BT, ST, UD, CD, BD, Any]
The application associated with this context.
- Type:
- property bot: BT
The bot associated with this context.
- Type:
- 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 todict.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 todict.Warning
When a group chat migrates to a supergroup, its chat id will change and the
chat_dataneeds to be transferred. For details see ourwiki 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
- 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
KeyErrorin 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 | RuntimeError –
KeyError, if the callback query can not be found in the cache andRuntimeError, if the bot doesn’t allow for arbitrary callback data.- Return type:
- classmethod from_error(update, error, application, job=None, coroutine=None)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the error handlers.Changed in version 20.0: Removed arguments
async_argsandasync_kwargs.- Parameters:
update (
object) – The update associated with the error. May beNone, 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 withblock=False.Added in version 20.0.
Changed in version 20.2: Accepts
asyncio.Futureand 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.CallbackContextto be passed to a job callback.See also
telegram.ext.JobQueue()- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- classmethod from_update(update, application)[source]
Constructs an instance of
telegram.ext.CallbackContextto be passed to the handlers.- Parameters:
- Returns:
TypeVar(CCT, bound= CallbackContext[Any, Any, Any, Any]) –telegram.ext.CallbackContext
- property job_queue: JobQueue[ST] | None
The
JobQueueused by thetelegram.ext.Application.See also
Job Queue <Extensions---JobQueue>- Type:
- property match: Match[str] | None
The first match from
matches. Useful if you are only filtering using a single regex filter. ReturnsNoneifmatchesis empty.- Type:
- async refresh_data()[source]
If
applicationuses persistence, callstelegram.ext.BasePersistence.refresh_bot_data()onbot_data,telegram.ext.BasePersistence.refresh_chat_data()onchat_dataandtelegram.ext.BasePersistence.refresh_user_data()onuser_data, if appropriate.Will be called by
telegram.ext.Application.process_update()andtelegram.ext.Job.run().Added in version 13.6.
- Return type:
- property update_queue: Queue[object]
The
asyncio.Queueinstance used by thetelegram.ext.Applicationand (usually) thetelegram.ext.Updaterassociated with this context.- Type:
- 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 todict.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:
objectConfigurations
- 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.
- 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:
- 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 getdefault (
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
- class spotted.handlers.warn.EventInfo(bot, ctx, update=None, message=None, query=None)[source]
Bases:
objectClass 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
- 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 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 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 Nonemessage_id (
int|None, default:None) – id of the message to edit. It is the current message if left Nonenew_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
- 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
- property inline_keyboard: InlineKeyboardMarkup | None
InlineKeyboard attached to the message
- property is_forwarded_post: bool
Whether the message is in fact a forwarded post from the channel to the group
- 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 forreason (
str|None, default:None) – reason for the rejection, currently used on autoreply
- class spotted.handlers.warn.PendingPost(user_id, u_message_id, g_message_id, admin_group_id, date, credit_username=None)[source]
Bases:
objectClass that represents a pending post
- Parameters:
user_id (
int) – id of the user that sent the postu_message_id (
int) – id of the original message of the postg_message_id (
int) – id of the post in the groupadmin_group_id (
int) – id of the admin groupcredit_username (
str|None, default:None) – username of the user that sent the post if it’s a credit postdate (
datetime) – when the post was sent
- 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:
- Returns:
PendingPost– instance of the class
- classmethod from_group(g_message_id, admin_group_id)[source]
Retrieves a pending post from the info related to the admin group
- Parameters:
- 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
- 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:
- Returns:
list[PendingPost] – list of ids of pending posts
- 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:
objectClass that represents a report
- Parameters:
user_id (
int) – id of the user that reportedadmin_group_id (
int) – id of the admin groupg_message_id (
int) – id of the post in the groupc_message_id (
int|None, default:None) – id of the post in question in the channeltarget_username (
str|None, default:None) – username of the reported userdate (
datetime|None, default:None) – when the report happened
- classmethod create_post_report(user_id, channel_id, c_message_id, admin_message)[source]
Adds the report of the user on a specific post
- classmethod create_user_report(user_id, target_username, admin_message)[source]
Adds the report of the user targeting another user
- 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
- classmethod get_post_report(user_id, channel_id, c_message_id)[source]
Gets the report of a specific user on a published post
- 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:
TelegramObjectThis 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_idis 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_usersadministrator 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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:
- message
Optional. New incoming message of any kind - text, photo, sticker, etc.
- Type:
- 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:
- channel_post
Optional. New incoming channel post of any kind - text, photo, sticker, etc.
- Type:
- 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:
- inline_query
Optional. New incoming inline query.
- Type:
- chosen_inline_result
Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- callback_query
Optional. New incoming callback query.
Examples
Arbitrary Callback Data Bot- Type:
- shipping_query
Optional. New incoming shipping query. Only for invoices with flexible price.
- Type:
- pre_checkout_query
Optional. New incoming pre-checkout query. Contains full information about checkout.
- poll
Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot.
- Type:
- 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:
- 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.
- 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_MEMBERin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()).Added in version 13.4.
- chat_join_request
Optional. A request to join the chat has been sent. The bot must have the
telegram.ChatPermissions.can_invite_usersadministrator right in the chat to receive these updates.Added in version 13.8.
- Type:
- 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.
- 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.
- 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_REACTIONin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.ext.Application.run_webhook()). The update isn’t received for reactions set by bots.Added in version 20.8.
- 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_COUNTin the list oftelegram.ext.Application.run_polling.allowed_updatesto receive these updates (seetelegram.Bot.get_updates(),telegram.Bot.set_webhook(),telegram.ext.Application.run_polling()andtelegram.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
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.
- business_message
Optional. New message from a connected business account.
Added in version 21.1.
- Type:
- edited_business_message
Optional. New version of a message from a connected business account.
Added in version 21.1.
- Type:
- deleted_business_messages
Optional. Messages were deleted from a connected business account.
Added in version 21.1.
- 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.
- 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_CONNECTIONAdded in version 21.1.
- BUSINESS_MESSAGE: Final[str] = 'business_message'
telegram.constants.UpdateType.BUSINESS_MESSAGEAdded in version 21.1.
- CALLBACK_QUERY: Final[str] = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERYAdded in version 13.5.
- CHANNEL_POST: Final[str] = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POSTAdded in version 13.5.
- CHAT_BOOST: Final[str] = 'chat_boost'
telegram.constants.UpdateType.CHAT_BOOSTAdded in version 20.8.
- CHAT_JOIN_REQUEST: Final[str] = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUESTAdded in version 13.8.
- CHAT_MEMBER: Final[str] = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBERAdded in version 13.5.
- CHOSEN_INLINE_RESULT: Final[str] = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULTAdded in version 13.5.
- DELETED_BUSINESS_MESSAGES: Final[str] = 'deleted_business_messages'
telegram.constants.UpdateType.DELETED_BUSINESS_MESSAGESAdded in version 21.1.
- EDITED_BUSINESS_MESSAGE: Final[str] = 'edited_business_message'
telegram.constants.UpdateType.EDITED_BUSINESS_MESSAGEAdded in version 21.1.
- EDITED_CHANNEL_POST: Final[str] = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POSTAdded in version 13.5.
- EDITED_MESSAGE: Final[str] = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGEAdded in version 13.5.
- INLINE_QUERY: Final[str] = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERYAdded in version 13.5.
- MESSAGE_REACTION: Final[str] = 'message_reaction'
telegram.constants.UpdateType.MESSAGE_REACTIONAdded in version 20.8.
- MESSAGE_REACTION_COUNT: Final[str] = 'message_reaction_count'
telegram.constants.UpdateType.MESSAGE_REACTION_COUNTAdded in version 20.8.
- MY_CHAT_MEMBER: Final[str] = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBERAdded in version 13.5.
- POLL_ANSWER: Final[str] = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWERAdded in version 13.5.
- PRE_CHECKOUT_QUERY: Final[str] = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERYAdded in version 13.5.
- PURCHASED_PAID_MEDIA: Final[str] = 'purchased_paid_media'
telegram.constants.UpdateType.PURCHASED_PAID_MEDIAAdded in version 21.6.
- REMOVED_CHAT_BOOST: Final[str] = 'removed_chat_boost'
telegram.constants.UpdateType.REMOVED_CHAT_BOOSTAdded in version 20.8.
- SHIPPING_QUERY: Final[str] = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERYAdded in version 13.5.
- callback_query: CallbackQuery | None
- classmethod de_json(data, bot=None)[source]
See
telegram.TelegramObject.de_json().- Return type:
- 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, ifinline_query,chosen_inline_result,callback_queryfrom inline messages,shipping_query,pre_checkout_query,poll,poll_answer,business_connection, orpurchased_paid_mediais present.Changed in version 21.1: This property now also considers
business_message,edited_business_message, anddeleted_business_messages.Example
If
messageis present, this will givetelegram.Message.chat.- Type:
- 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_postorcallback_query(i.e.telegram.CallbackQuery.message) orNone, if none of those are present.
Changed in version 21.1: This property now also considers
business_message, andedited_business_message.Tip
This property will only ever return objects of type
telegram.MessageorNone, nevertelegram.MaybeInaccessibleMessageortelegram.InaccessibleMessage. Currently, this is only relevant forcallback_query, astelegram.CallbackQuery.messageis the only attribute considered by this property that can be an object of these types.- Type:
- property effective_sender: User | Chat | None
The user or chat that sent this update, no matter what kind of update this is.
Note
Depending on the type of update and the user’s ‘Remain anonymous’ setting, this could either be
telegram.User,telegram.ChatorNone.
If no user whatsoever is associated with this update, this gives
None. This is the case if any ofis present.
Example
If
messageis present, this will give eithertelegram.Message.from_userortelegram.Message.sender_chat.If
poll_answeris present, this will give eithertelegram.PollAnswer.userortelegram.PollAnswer.voter_chat.If
channel_postis present, this will givetelegram.Message.sender_chat.
Added in version 21.1.
- Type:
- 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 ofis present.
Changed in version 21.1: This property now also considers
business_connection,business_messageandedited_business_message.Changed in version 21.6: This property now also considers
purchased_paid_media.Example
If
messageis present, this will givetelegram.Message.from_user.If
poll_answeris present, this will givetelegram.PollAnswer.user.
- Type:
- 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:
objectClass that represents a user
- Parameters:
user_id (
int) – id of the userprivate_message_id (
int|None, default:None) – id of the private message sent by the user to the bot. Only used for followingban_date (
datetime|None, default:None) – datetime of when the user was banned. Only used for banned usersfollow_date (
datetime|None, default:None) – datetime of when the user started following a post. Only used for following users
- 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 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
- async get_user_sign(bot)[source]
Generates a sign for the user. It will be a random name for an anonym user
- 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.
- async spotted.handlers.warn.execute_ban(user_id, info)[source]
Execute the ban of a user by his user_id
- 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:
update (
Update) – update eventcontext (
CallbackContext) – context passed by the handler