似乎找不到让我的电报机器人等待用户输入的方法

2024-04-29 11:53:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个电报机器人,从genius API获取歌词。 当bot请求艺术家时,它会立即发送歌曲标题的问题,但我正在尝试使bot像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

Tags: textname标题messagesongartistbotupdate
1条回答
网友
1楼 · 发布于 2024-04-29 11:53:15

您可能正在寻找^{},它可以处理对话

预浸

首先,我们需要导入以下模块并定义Dispatcher,它接受bot的所有处理程序

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

有关筛选器的更多信息,请查看文档here。这里我们只需要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)]
))

会话处理程序的处理程序

对话以entry_points开始,并以不同的状态进行。每一个都需要一个处理程序。例如,我们为entry_points定义了一个名为introCommandHandler,当用户输入命令/start时调用它

def intro(update: Update, context: CallbackContext) -> int:
    update.message.reply_text('Enter artist')
    # Specify the succeeding state to enter
    return ARTIST

artisttitle这样的其他处理程序也很简单。例如:

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函数,用于在用户键入命令/quit时结束对话

def quit(update: Update, context: CallbackContext):
    return ConversationHandler.END

旁注

使用ConversationHandler的一个优点是,您可以随时添加任何新状态以询问更多问题ConversationHandler还使邮件过滤更容易

您还可以看一个会话bothere的示例,它利用ConversationHandler

相关问题 更多 >