将代码移入Cog后Discord机器人无法发送Embed求助
问题排查与修复方案
1. 修正inline参数类型
代码中add_field的inline参数传的是字符串"True"/"False",但Discord.py要求该参数为布尔值(不带引号的True/False)。字符串会被Python视为真值,可能导致Embed结构异常,无法正常发送。
2. 避免使用实例变量存储Embed
在Cog的命令方法里,用self.embed_v作为实例变量存在并发风险(多个用户同时调用命令时会互相覆盖),应改用局部变量。
3. 修正头像URL的获取方式
self.bot.user.avatar返回的是Avatar对象而非直接URL,需要调用.url属性获取。同时建议处理头像不存在的情况, fallback到默认头像:
icon_url = self.bot.user.avatar.url if self.bot.user.avatar else self.bot.user.default_avatar.url
4. 修复Markdown格式错误
字段值里的粗体语法不规范:"some stuff**If there's any...**"缺少空格,应调整为"some stuff\n**If there's any...**",避免解析失败。
5. 确认机器人权限
确保机器人在当前频道拥有embed_links权限(普通消息能发送大概率权限没问题,但可做二次确认)。
修正后的完整代码
@info.command(name="galax") async def galax(self, ctx): print("Command called") # 使用局部变量替代实例变量 embed_v = discord.Embed(title="Name", description="Description", color=discord.Color.random()) print("Embed declared") embed_v.set_thumbnail(url="image url here") print("Image set") # 修正头像URL获取 icon_url = self.bot.user.avatar.url if self.bot.user.avatar else self.bot.user.default_avatar.url embed_v.set_footer(text="For any further queries, please put them in help-chat", icon_url=icon_url) print("Footer set") # 修正inline参数为布尔值 embed_v.add_field(name="Server Status:", value="status", inline=True) print("status set") # 修正Markdown格式 embed_v.add_field( name="Whitelisted Players(In-Game names):", value="some stuff\n**If there's any name missing or incorrectly spelt please report it with /report or !report**", inline=False ) embed_v.add_field(name="Current Server Version:", value="version", inline=True) print("Version set") embed_v.add_field(name="Server IP:", value="ip.....", inline=True) print("IP set") await ctx.send(embed=embed_v) print("Embed sent")
内容的提问来源于stack exchange,提问作者GreatestQuince8
相关产品推荐
相关产品推荐

