您可能正在寻找ConversationHandler
可以处理对话的 .
准备工作
首先,我们需要导入以下模块并定义Dispatcher
,这将获取您机器人的所有处理程序。
from telegram import Update
from telegram.ext import (
Updater,
Filters,
CommandHandler,
MessageHandler,
ConversationHandler,
CallbackContext
)
updater = Updater('your token here', use_context=True)
dispatcher = updater.dispatcher
对话处理程序
然后,我们将对话处理程序附加到调度程序dispatcher.add_handler
。您可以指定如下状态并定义对话处理程序。
请注意,状态必须是int
,为了可读性,我们定义了常量ARTIST
和TITLE
不同的状态。
有关过滤器的更多信息,请查看此处的文档。我们只需要Filters.text
在这里,因为我们只将文本作为MessageHandler
.
ARTIST, TITLE = 0, 1
dispatcher.add_handler(ConversationHandler(
entry_points=[CommandHandler('start', intro)],
states={
ARTIST: [MessageHandler(Filters.text, callback=artist)],
TITLE: [MessageHandler(Filters.text, callback=title)]
},
fallbacks=[CommandHandler('quit', quit)]
))
ConversationHandler 的处理程序
对话以不同的状态开始entry_points
并以不同的状态进行。这些中的每一个都需要一个处理程序。例如,我们定义了一个CommandHandler
被调用intro
的 for entry_points
,当用户输入命令时调用它/start
。
def intro(update: Update, context: CallbackContext) -> int:
update.message.reply_text('Enter artist')
# Specify the succeeding state to enter
return ARTIST
其他处理程序也喜欢artist
并且title
很简单。例如:
def artist(update: Update, context: CallbackContext) -> int:
artist_name = update.message.text
# This variable needs to be stored globally to be retrieved in the next state
artist = genius.search_artist(artist_name, max_songs=0)
update.message.reply_text('Enter song title')
# Let the conversation proceed to the next state
return TITLE
def title(update: Update, context: CallbackContext) -> int:
song_name = update.message.text
song = artist.song(song_name)
update.message.reply_text(song.lyrics)
# return ConversationHandler.END to end the conversation
return ConversationHandler.END
此外,对话需要一个回退处理程序。在代码示例中,我们定义了一个简单的退出函数来在用户键入命令时结束对话/quit
。
def quit(update: Update, context: CallbackContext):
return ConversationHandler.END
旁注
使用的一个优点ConversationHandler
是您可以随时添加任何新状态以提出更多问题。ConversationHandler
也使过滤消息更容易。
您还可以在此处查看使用ConversationHandler
.