Python开发Discord机器人无响应问题求助
问题原因及解决方法
1. 必须开启Message Content意图
Discord从2022年8月起,要求机器人必须明确申请message_content权限才能读取消息内容,你的代码未配置该意图,导致bot无法获取消息的content字段,自然不会触发ping响应。
操作步骤:
- 登录Discord开发者平台,进入你的机器人应用页面
- 切换到Bot标签页,找到Privileged Gateway Intents,开启Message Content Intent
- 在代码中添加意图配置,修改开头部分:
import discord # 创建意图对象并开启message_content权限 intents = discord.Intents.default() intents.message_content = True # 初始化bot时传入意图参数 bot = discord.Bot(intents=intents)
2. 修正on_message事件逻辑
添加忽略机器人自身消息的判断,避免触发循环;如果后续要同时处理slash命令,还需调用process_commands:
@bot.event async def on_message(message): # 忽略机器人自己发送的消息 if message.author.bot: return if message.content.lower() == "ping": await message.channel.send("pong") # 若要支持slash命令,必须加上这行 await bot.process_commands(message)
3. 实现目标中的Slash命令(/mute、/help、/clear)
你的目标是实现/mute这类slash命令,用discord.Bot()的原生应用命令装饰器更合适,以下是示例:
/ping 命令
@bot.slash_command(name="ping", description="测试机器人在线状态") async def ping(ctx): await ctx.respond("pong")
/clear 命令(清理消息)
@bot.slash_command(name="clear", description="清理指定数量的消息") async def clear(ctx, amount: int): # 检查用户权限 if not ctx.author.guild_permissions.manage_messages: await ctx.respond("你没有权限执行此命令!") return await ctx.channel.purge(limit=amount+1) # +1是清除命令本身 await ctx.respond(f"已清理{amount}条消息", ephemeral=True) # 仅自己可见回复
/help 命令
@bot.slash_command(name="help", description="查看机器人所有命令") async def help(ctx): help_text = """ **H2H 机器人命令列表** - /ping: 测试机器人在线状态 - /clear [数量]: 清理指定数量的消息 - /mute [用户]: 禁言指定用户(需管理成员权限) """ await ctx.respond(help_text, ephemeral=True)
验证
修改代码后重启bot,即可实现:
- 发送
ping消息收到pong回复 - 输入
/ping等slash命令正常响应
内容的提问来源于stack exchange,提问作者ItsMoonlight
相关产品推荐
相关产品推荐

