0

我正在尝试制作一个从天才 API 获取歌词的电报机器人。当机器人询问艺术家时,它会立即发送歌曲标题的问题,但我试图让机器人像 python 中的 input() 命令一样工作。

我知道我可以让用户在艺术家和歌曲标题之间用逗号分隔字符串,但这将是最后的选择。

这是我正在谈论的代码。

def lyrics(update: Update, context: CallbackContext) -> None:
    update.message.reply_text("Enter artist")
    artist_name = update.message.text
    artist = genius.search_artist(artist_name, max_songs=0)
    update.message.reply_text("Enter song title")
    song_name = update.message.text
    song = artist.song(song_name)
    update.message.reply_text(song.lyrics)

还有一个没有歌词的例子

update.message.reply_text("Reply something")
reply = update.message.text
update.message.reply_text("2nd answer")
reply2 = update.message.text
4

1 回答 1

0

您可能正在寻找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,为了可读性,我们定义了常量ARTISTTITLE不同的状态。

有关过滤器的更多信息,请查看此处的文档。我们只需要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.

于 2021-01-18T18:58:22.487 回答