You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord音乐机器人询问选曲选项后如何获取命令发起用户的回复消息

Discord音乐机器人多搜索结果选择功能实现方案

你可以用discord.py内置的wait_for方法监听指定用户的后续消息,实现选择交互逻辑,修正后的完整代码如下:

ytlinks = searchForLink(link, 10)

if len(ytlinks) > 1:
    # 格式化输出可选列表,优化用户体验
    option_msg = "为你找到以下匹配结果,请输入对应序号选择:\n"
    for idx, ytlink in enumerate(ytlinks, start=1):
        option_msg += f"{idx}. {ytlink}\n"
    await ctx.send(option_msg)

    # 定义消息校验规则
    def check(msg):
        return msg.author == ctx.author and msg.channel == ctx.channel and msg.content.isdigit()

    try:
        # 等待用户回复,超时时间30秒可自行调整
        reply = await ctx.bot.wait_for('message', timeout=30.0, check=check)
        linkchoice = int(reply.content)
        if linkchoice < 1 or linkchoice > len(ytlinks):
            await ctx.send("输入的序号不在可选范围内,请重新发起指令")
            return
        selected_link = ytlinks[linkchoice - 1]
    except TimeoutError:
        await ctx.send("选择超时,请重新发起指令")
        return
else:
    # 仅1个结果时直接选中
    selected_link = ytlinks[0]

注意事项:

  • check函数用于过滤无效消息,只有指令发起者在当前频道发送的纯数字消息才会被判定为有效选择,避免其他用户消息干扰流程
  • 超时时间可根据需求调整,防止用户长时间不回复导致流程卡住
  • 可以扩展可选列表的展示内容,对接YouTube接口抓取每个链接对应的歌曲标题、时长等信息替换纯链接显示,优化使用体验

内容的提问来源于stack exchange,提问作者Gabe G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 16:09:03