Discord.py say命令未指定发送频道时的channel变量赋值问题求助
问题原因
- 原代码中
channel:discord.TextChannel没有设置默认值,属于必填参数,用户未输入时Discord.py会直接抛出参数缺失错误,不会执行后续的if not channel判断逻辑 - 原代码中
channel=()的赋值逻辑错误,空元组没有send方法,就算执行到这里也会触发运行报错
修正方案
直接替换为以下代码即可实现需求:
import discord from typing import Optional @bot.command() async def say(ctx, channel: Optional[discord.TextChannel] = None, *, message): # 未传入频道时默认使用命令触发的当前频道 if not channel: channel = ctx.channel embed=discord.Embed( description=message, color=discord.Color.blue() ) await channel.send(embed=embed) await ctx.message.delete()
如果使用Python 3.10及以上版本,可以省略typing导入,将参数行写为:async def say(ctx, channel: discord.TextChannel | None = None, *, message):
效果验证
- 输入
!say 测试内容:未指定频道时自动在命令触发的当前频道发送嵌入消息 - 输入
!say #目标频道 测试内容:指定频道时向对应频道发送嵌入消息
内容的提问来源于stack exchange,提问作者J0ssue
相关产品推荐
相关产品推荐

