Discord.py机器人猜内鬼命令无法识别用户输入问题求助
问题原因分析
- 消息意图权限缺失:Discord.py v1.5及以上版本要求显式开启消息内容意图才能读取用户发送的纯文本内容,这是Discord官方的安全限制,未开启时机器人拿到的用户消息内容会为空。
- 代码逻辑细节错误:你在构造返回Embed时直接使用了
user_response消息对象,而非用户输入的文本属性user_response.content,会导致Embed输出异常的对象字符串而非用户输入的颜色;同时未对用户输入做标准化处理,大小写、首尾空格都会导致匹配失败。 - 实例引用错误(Cog场景):如果该命令是写在Cog插件中,大部分场景下客户端实例的命名为
self.bot而非self.client,引用错误会导致事件监听失效。
修复步骤
- 先前往Discord开发者后台的Bot管理页,开启「Message Content Intent」开关
- 初始化机器人时显式配置消息内容意图
- 修改命令逻辑的细节问题
修复后完整代码
初始化部分示例
import discord from discord.ext import commands import random import asyncio # 配置开启必需的意图 intents = discord.Intents.default() intents.message_content = True # 前缀替换为你自己的命令前缀 bot = commands.Bot(command_prefix='!', intents=intents)
修复后的命令代码
@commands.command(aliases=['gti']) async def impostor(self, ctx): def check(message): return message.author == ctx.author and message.channel == ctx.channel impostor_list = ['red', 'yellow', 'white', 'purple', 'pink', 'orange', 'lime', 'green', 'cyan', 'brown', 'blue'] impostor = random.choice(impostor_list) embed = discord.Embed(title="Guess the impostor!", description="Who is sussy? Write their color in chat within 20s to continue!", color = discord.Color.random()) embed.add_field(name="The people are:", value="```red, yellow, white, purple, pink, orange, lime, green, cyan, blue, brown```") await ctx.send(embed=embed) try: user_response = await self.bot.wait_for("message", timeout=20, check=check) # 标准化处理用户输入,避免空格、大小写导致匹配失败 user_answer = user_response.content.strip().lower() except asyncio.TimeoutError: return await ctx.send("You took too long to answer.") else: if user_answer == impostor: correct_em = discord.Embed(title=f"{user_answer} was ejected.", description=f"{user_answer} was the Impostor. Well done!", color = discord.Color.random()) return await ctx.send(embed=correct_em) else: wrong_em = discord.Embed(title=f"{user_answer} was ejected.", description=f"{user_answer} was not the Impostor.\nYou lose! {impostor} was the Impostor.") return await ctx.send(embed=wrong_em)
注意事项
- 不要给机器人授予多余的管理员权限,仅开启发送消息、读取消息、嵌入链接权限即可
- 服务器内使用时确认机器人在对应频道拥有读写消息的权限
内容的提问来源于stack exchange,提问作者Parad1se
相关产品推荐
相关产品推荐

