You need to enable JavaScript to run this app. discord.py框架下suggest服务器建议提交指令运行故障咨询
优惠活动
大模型
产品
解决方案
定价
更多

discord.py框架下suggest服务器建议提交指令运行故障咨询

故障原因
  • 变量引用错误+API版本不兼容:获取频道的代码行调用了未定义的message变量,同时discord.py v1.0及以上版本已废弃server属性,统一改为guild,原message.server写法已失效。
  • 缺空值校验:未判断目标频道是否存在,当服务器未创建名为suggestion-channel的频道时,会触发属性报错终止指令运行。
  • 缺权限校验:未校验机器人在目标频道的发消息、添加反应权限,以及删除用户触发消息的权限,权限不足时指令会直接报错。
  • 缺参数容错逻辑:用户触发指令未填写建议内容时,会触发参数缺失报错。
  • (v2.x版本额外问题)未开启消息内容意图:discord.py 2.0及以上版本要求开发者手动开启Message Content Intent才能读取普通消息内容,未开启会导致前缀指令完全不触发。
修复方案

修复后完整代码

@commands.command()
async def suggest(self, ctx, *, suggestion: str = None):
    # 校验建议内容是否为空
    if not suggestion:
        await ctx.send("请填写你要提交的建议内容", delete_after=5)
        await ctx.message.delete()
        return
    
    embed = discord.Embed(title=f"Suggestion from {ctx.author.name}", description=suggestion, color=discord.Color.blue())
    embed.set_footer(text=f"Suggestion created by {ctx.author}")
    # 从ctx获取当前服务器的频道列表,替换无效的旧写法
    channel = discord.utils.get(ctx.guild.channels, name="suggestion-channel")
    
    # 校验目标频道是否存在
    if not channel:
        await ctx.send("未找到建议提交频道,请联系服务器管理员处理", delete_after=5)
        await ctx.message.delete()
        return
    
    # 校验机器人权限
    me = ctx.guild.me
    if not channel.permissions_for(me).send_messages or not channel.permissions_for(me).add_reactions:
        await ctx.send("我没有在建议频道发消息/添加反应的权限,请联系管理员调整", delete_after=5)
        await ctx.message.delete()
        return
    
    try:
        message = await channel.send(embed=embed)
        await message.add_reaction("✅")
        await message.add_reaction("❌")
        await ctx.message.delete()
        await ctx.send("Thank you for your suggestion!", delete_after=3)
    except Exception as e:
        await ctx.send(f"提交失败:{str(e)}", delete_after=5)
        await ctx.message.delete()

意图配置(v2.x版本必填)

在Discord开发者后台的机器人设置页开启Message Content Intent,同时在初始化机器人的代码中声明对应意图:

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True # 开启消息内容读取权限
bot = commands.Bot(command_prefix='你设置的指令前缀', intents=intents)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 18:15:04