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

如何将Discord机器人Poll命令的每个回答以字符串存储?

解决Discord机器人Poll命令无法获取回答的问题

你的代码存在两个关键问题导致无法获取用户回答:

1. 未将获取到的回答存入存储容器

代码里定义了answers列表,但获取到用户的message对象后,完全没有把回答内容添加进去,最终answers始终是空的。

2. 缺少消息内容读取权限

Discord.py 2.0及以上版本需要显式开启message_content意图才能读取用户发送的消息内容,默认的discord.Intents.default()不包含该权限,导致机器人无法读取消息内容。

修复后的完整代码

import asyncio
import discord
from discord.ext import commands

# 定义问题列表
questions = ["Question 1", "Question 2", "Question 3"]
# 开启必要的意图,包含消息内容读取权限
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(intents=intents, command_prefix='+')


@bot.command()
async def poll(ctx):
    # 用字典直接关联问题与回答,满足你的存储需求
    question_answer_map = {}
    for question in questions:
        await ctx.send(question)
        try:
            # 等待用户发送对应回答
            message = await bot.wait_for(
                'message',
                check=lambda m: m.channel == ctx.channel and m.author == ctx.author,
                timeout=30
            )
            # 将问题和对应的回答存入字典
            question_answer_map[question] = message.content
        except asyncio.TimeoutError:
            await ctx.send("超时未回答,问卷终止。")
            break
    
    # 检查问卷完成状态
    if len(question_answer_map) != len(questions):
        await ctx.send("你未完成全部问卷。")
    else:
        await ctx.send("问卷完成!你的回答如下:")
        # 输出所有问题与对应回答
        for q, a in question_answer_map.items():
            await ctx.send(f"**{q}**: {a}")

# 替换为你的机器人Token
bot.run("YOUR_BOT_TOKEN")

关键改动说明

  • 开启message_content意图:确保机器人有权限读取用户发送的消息内容
  • 使用字典存储关联关系:直接绑定每个问题和对应的回答,比单纯列表更贴合你的需求
  • 添加回答存入逻辑:获取到用户消息后,将内容存入字典
  • 补充交互提示:给用户发送超时、完成状态等反馈,提升使用体验

内容的提问来源于stack exchange,提问作者אופק לוי

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 18:22:49