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

Nextcord开发Discord机器人:如何响应非/命令消息及接收命令后答案?

Nextcord机器人接收命令后后续消息的解决方案

核心实现思路

当用户触发/quiz rules命令后,通过消息监听机制捕获用户后续发送的答案,同时通过条件过滤确保只响应发起测验的用户,避免交互冲突。

完整代码实现

import nextcord
import asyncio
from nextcord import Interaction, SlashOption
from nextcord.ext import commands

# 初始化Bot,必须启用消息内容意图
intents = nextcord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix="!", intents=intents)

testing_id = 1234567890  # 替换为你的测试服务器ID

@client.slash_command(guild_ids=[testing_id])
async def quiz(interaction: Interaction,
               value: str = SlashOption(
                   name="value",
                   choices=["rules"]
               )):
    if value == "rules":
        # 发送测验题目
        await interaction.response.send_message("规则测验:Discord服务器禁止发布哪种内容?\nA. 合法分享 B. 色情暴力 C. 技术讨论")
        
        # 定义消息过滤条件:仅接收发起命令的用户在当前频道的消息
        def check(msg):
            return msg.author == interaction.user and msg.channel == interaction.channel
        
        try:
            # 等待用户发送答案,超时时间30秒
            answer_msg = await client.wait_for("message", check=check, timeout=30.0)
            
            # 校验答案并回复结果
            if answer_msg.content.strip().upper() == "B":
                await interaction.followup.send("回答正确!👍")
            else:
                await interaction.followup.send(f"回答错误,正确答案是B。你输入的是{answer_msg.content}")
        except asyncio.TimeoutError:
            # 超时提示
            await interaction.followup.send("⏰ 时间到啦,你没有及时提交答案哦!")

# 运行机器人
client.run("你的机器人Token")

关键注意事项

  • 启用消息内容意图:
    • 登录Discord开发者门户,找到你的机器人应用,在「Privileged Gateway Intents」中开启Message Content Intent。
    • 初始化Bot时必须传入包含message_content=True的intents对象,否则无法监听用户消息。
  • 过滤条件check函数:
    • 严格限制消息来源为发起命令的用户和当前频道,避免其他用户的消息干扰测验流程。
  • 交互响应规范:
    • 初始回复使用interaction.response.send_message(),后续结果必须用interaction.followup.send(),符合Slash命令的交互规则。
  • 超时机制:
    • 设置合理的超时时间(示例为30秒),防止机器人长期处于等待状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 23:10:22