discord.py自定义embed命令触发'str'无send属性报错求助
报错信息
开发discord.py自定义embed命令时触发如下报错:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'send'
错误原因
你使用@client.command()装饰器注册的是全局客户端命令,并非写在Cog类中的命令,函数参数错误添加了self形参导致参数错位:
- 原本应该传入
ctx上下文对象的位置,被赋值给了self形参 - 形参列表里的
ctx实际接收到的是后续传入的字符串类型消息内容 - 后续执行
await ctx.send()时,你以为的ctx实际是字符串对象,字符串没有send方法,直接触发属性错误 - 附带逻辑问题:代码里写的
self.client.wait_for在全局命令场景下不存在,且超时分支没有加返回,会导致超时后继续执行后续embed逻辑。
修复后代码
直接替换原有命令代码即可:
@client.command() @commands.has_permissions(administrator=True) async def embed(ctx,*, msg=None): if msg == None: await ctx.send("No Message has been provided. Please write your message within 30secs.") def check(message): return message.author == ctx.author and message.channel == ctx.channel try: mes=await client.wait_for('message',check=check,timeout=30.0) except asyncio.TimeoutError: await ctx.send('Timeout! Please be quicker next time.') return else: msg=mes.content em=discord.Embed( description=msg, timestamp=datetime.utcnow(), color=discord.Color.random()).set_author( name=f'{ctx.author.name}#{ctx.author.discriminator}', icon_url=f'{ctx.author.avatar_url}') await ctx.send(embed=em)
修改点说明
- 移除了全局命令不需要的
self形参,修正参数错位问题 - 将
self.client.wait_for替换为全局实例client.wait_for,适配非Cog的命令写法 - 在超时分支添加
return,超时后直接终止命令执行,不会继续生成空内容的embed
内容的提问来源于stack exchange,提问作者CaptainMaxi
相关产品推荐
相关产品推荐

