discord.py的cogs中使用slash命令发Embed出现AttributeError如何解决?
错误根因
discord斜杠命令属于交互类触发,其上下文对象ctx不存在message属性,你调用ctx.message会直接返回None,尝试访问None的author属性就会触发本次的AttributeError报错。
修复方案
斜杠命令上下文中可以直接通过ctx.author获取触发命令的用户对象,不需要通过ctx.message跳转。同时你当前的代码还存在多处可优化和会触发后续报错的问题,统一修正后的代码如下:
@cog_ext.cog_slash(description = "Calculate your math's query.") async def cal(self, ctx, query: str): # 直接使用局部变量,不需要绑定到self实例避免并发污染 operation = query # 注意:eval存在极高安全风险,仅做功能演示,生产环境请替换为安全的数学表达式解析方案 evaluate = eval(operation) username = ctx.author.display_name embed = discord.Embed(title = "/Cal", description = "Calculate your math queries.", colour = discord.Color.blurple()) embed.set_footer(text = f"{username}'s query evaluated.") embed.set_author(name = f"{username}'s query.", icon_url = ctx.author.avatar_url) # 补充add_field必填的name参数,否则会触发新的参数缺失报错 embed.add_field(name = "输入的计算式", value = f"{operation}", inline = False) embed.add_field(name = "计算说明", value = "After evaluated, the result is :", inline = True) embed.add_field(name = "最终结果", value = f"{evaluate}", inline = True) await ctx.send(embed = embed)
额外注意事项
- eval安全风险极高:用户可以传入任意Python代码执行,可能导致服务器文件被篡改、数据泄露等严重问题,生产环境建议替换为
simpleeval等专门的安全表达式计算库,或自行实现数学表达式解析逻辑。 - 你之前的代码中
("").join(query)是冗余操作,query本身就是字符串类型,不需要再做拼接。 - 所有请求级的临时变量不要绑定到
selfcog实例上,多个用户同时调用命令时会出现变量互相覆盖的异常。
内容的提问来源于stack exchange,提问作者Daniesh Rieza
相关产品推荐
相关产品推荐

