ConversationHandler¶
- class telegram.ext.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:
telegram.ext.BaseHandlerA 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, see nestedconversationbot.py.Use In
Available In
- Parameters:
entry_points (list[
telegram.ext.BaseHandler]) – 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[telegram.ext.BaseHandler]]) – 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[
telegram.ext.BaseHandler]) – 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, optional) – 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, optional) – If the conversation key should contain the Chat’s ID. Default isTrue.per_user (
bool, optional) – If the conversation key should contain the User’s ID. Default isTrue.per_message (
bool, optional) – If the conversation key should contain the Message’s ID. Default isFalse.conversation_timeout (
float|datetime.timedelta, optional) –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, optional) – The name for this conversation handler. Required for persistence.persistent (
bool, optional) –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], optional) – 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.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
Changed 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[source]¶
Determines whether the callback will run in a blocking way. Always
Truesince conversation handlers handle any non-blocking callbacks internally.- Type:
- TIMEOUT = -2[source]¶
Used as a constant to handle state when a conversation is timed out (exceeded
conversation_timeout).- Type:
- WAITING = -3[source]¶
Used as a constant to handle state when a conversation is still waiting on the previous
block=Falsehandler to finish.- Type:
- __repr__()[source]¶
Give a string representation of the ConversationHandler in the form
ConversationHandler[name=..., states={...}].If there are more than 3 states, only the first 3 states are listed.
As this class doesn’t implement
object.__str__(), the default implementation will be used, which is equivalent to__repr__().- Returns:
- property allow_reentry[source]¶
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.
- Parameters:
update (
telegram.Update|object) – Incoming update.- Returns:
- property conversation_timeout[source]¶
Optional. When this handler is inactive more than this timeout (in seconds), it will be automatically ended.
- Type:
- property entry_points[source]¶
A list of
BaseHandlerobjects that can trigger the start of the conversation.- Type:
list[
telegram.ext.BaseHandler]
- property fallbacks[source]¶
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 – The result from
check_update(). For this handler it’s a tuple of the conversation state, key, handler, and the handler’s check result.update (
telegram.Update) – Incoming telegram update.application (
telegram.ext.Application) – Application that originated the update.context (
telegram.ext.CallbackContext) – The context as provided by the application.
- property map_to_parent[source]¶
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[source]¶
Optional. The name for this
ConversationHandler.- Type:
- property persistent[source]¶
Optional. If the conversations dict for this handler should be saved.
nameis required and persistence has to be set inApplication.- Type:
- property states[source]¶
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]]