telegram.ext.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, run_async=False)¶ Bases:
telegram.ext.handler.Handler[telegram.update.Update]A handler to hold a conversation with a single or multiple users through Telegram updates by managing four collections of other handlers.
Note
ConversationHandlerwill only accept updates that are (subclass-)instances oftelegram.Update. This is, because depending on theper_userandper_chatConversationHandlerrelies 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 previous@run_asyncdecorated handler 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.DispatcherHandlerStopcan be used in conversations as described in the corresponding documentation.Note
In each of the described collections of handlers, a handler may in turn be a
ConversationHandler. In that case, the nestedConversationHandlershould have the attributemap_to_parentwhich allows to return to the parent conversation at specified states within the nested 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 this has ended or even map a state toENDto end the parent conversation from within the nested one. For an example on nestedConversationHandlers, see our examples.- Parameters
entry_points (List[
telegram.ext.Handler]) – A list ofHandlerobjects that can trigger the start of the conversation. The first handler whichcheck_updatemethod returnsTruewill be used. If all returnFalse, the update is not handled.states (Dict[
object, List[telegram.ext.Handler]]) – Adictthat defines the different states of conversation a user can be in and one or more associatedHandlerobjects that should be used in that state. The first handler whichcheck_updatemethod returnsTruewill be used.fallbacks (List[
telegram.ext.Handler]) – 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_updatemethod 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.per_chat (
bool, optional) – If the conversationkey should contain the Chat’s ID. Default isTrue.per_user (
bool, optional) – If the conversationkey should contain the User’s ID. Default isTrue.per_message (
bool, optional) – If the conversationkey 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 0 or
None(default), there will be no timeout. The last received update and the correspondingcontextwill be handled by ALL the handler’s who’scheck_updatemethod returnsTruethat are in the stateConversationHandler.TIMEOUT.Note
Using conversation_timeout with nested conversations is currently not supported. You can still try to use it, but it will likely behave differently from what you expect.
name (
str, optional) – The name for this conversationhandler. Required for persistence.persistent (
bool, optional) – If the conversations dict for this handler should be saved. Name is required and persistence has to be set intelegram.ext.Updatermap_to_parent (Dict[
object,object], optional) – Adictthat can be used to instruct a nested conversationhandler to transition into a mapped state on its parent conversationhandler in place of a specified nested state.run_async (
bool, optional) –Pass
Trueto override theHandler.run_asyncsetting of all handlers (inentry_points,statesandfallbacks).Note
If set to
True, you should not pass a handler instance, that needs to be run synchronously in another context.New in version 13.2.
- Raises
ValueError –
-
entry_points¶ A list of
Handlerobjects that can trigger the start of the conversation.- Type
List[
telegram.ext.Handler]
-
states¶ A
dictthat defines the different states of conversation a user can be in and one or more associatedHandlerobjects that should be used in that state.- Type
Dict[
object, List[telegram.ext.Handler]]
-
fallbacks¶ 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.Handler]
-
allow_reentry¶ Determines if a user can restart a conversation with an entry point.
- Type
bool
-
per_chat¶ If the conversationkey should contain the Chat’s ID.
- Type
bool
-
per_user¶ If the conversationkey should contain the User’s ID.
- Type
bool
-
per_message¶ If the conversationkey should contain the Message’s ID.
- Type
bool
-
conversation_timeout¶ Optional. When this handler is inactive more than this timeout (in seconds), it will be automatically ended. If this value is 0 (default), there will be no timeout. When it’s triggered, the last received update and the corresponding
contextwill be handled by ALL the handler’s who’scheck_updatemethod returnsTruethat are in the stateConversationHandler.TIMEOUT.- Type
float|datetime.timedelta
-
name¶ Optional. The name for this conversationhandler. Required for persistence
- Type
str
-
persistent¶ Optional. If the conversations dict for this handler should be saved. Name is required and persistence has to be set in
telegram.ext.Updater- Type
bool
-
map_to_parent¶ Optional. A
dictthat can be used to instruct a nested conversationhandler to transition into a mapped state on its parent conversationhandler in place of a specified nested state.- Type
Dict[
object,object]
-
run_async¶ If
True, will override theHandler.run_asyncsetting of all internal handlers on initialization.New in version 13.2.
- Type
bool
-
END: ClassVar[int] = -1¶ Used as a constant to return when a conversation is ended.
- Type
int
-
TIMEOUT: ClassVar[int] = -2¶ Used as a constant to handle state when a conversation is timed out.
- Type
int
-
WAITING: ClassVar[int] = -3¶ Used as a constant to handle state when a conversation is still waiting on the previous
@run_syncdecorated running handler to finish.- Type
int
-
check_update(update)¶ Determines whether an update should be handled by this conversationhandler, and if so in which state the conversation currently is.
- Parameters
update (
telegram.Update|object) – Incoming update.- Returns
bool
-
handle_update(update, dispatcher, check_result, context=None)¶ Send the update to the callback for the current state and Handler
- Parameters
check_result – The result from check_update. For this handler it’s a tuple of key, handler, and the handler’s check result.
update (
telegram.Update) – Incoming telegram update.dispatcher (
telegram.ext.Dispatcher) – Dispatcher that originated the Update.context (
telegram.ext.CallbackContext, optional) – The context as provided by the dispatcher.