discord.py机器人报错50006:无法发送空消息,此前代码正常
Discord.py 机器人报错:Cannot send an empty message 解决指南
问题背景
原本正常运行的discord.py机器人命令(who/nhie/truth/dare),未修改代码的情况下突然抛出「无法发送空消息」的错误,报错示例来自truth命令。
相关代码
@bot.command() async def who(ctx): r1=random.choice(MostLikely) embed=discord.Embed(title=r1, color=0xC964F0) await ctx.send(embed=embed) @bot.command() async def nhie(ctx): r2=random.choice(Nhie) embed=discord.Embed(title=r2, color=0xC964F0) await ctx.send(embed=embed) @bot.command() async def truth(ctx): r3=random.choice(Truth) embed=discord.Embed(title=r3, color=0xC964F0) await ctx.send(embed=embed) @bot.command() async def dare(ctx): r4=random.choice(Dare) embed=discord.Embed(title=r4, color=0xC964F0) await ctx.send(embed=embed)
完整报错信息
Ignoring exception in command truth: Traceback (most recent call last): File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 92, in wrapped ret = await coro(*args, **kwargs) File "main.py", line 1254, in truth await ctx.send(embed=embed) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 1089, in send data = await state.http.send_message( File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 262, in request raise HTTPException(r, data) discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 977, in invoke await ctx.command.invoke(ctx) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 870, in invoke await injected(*ctx.args, **ctx.kwargs) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 101, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
原因分析
错误核心是Discord API拒绝发送空内容的Embed,结合代码逻辑,触发原因只有两种:
- 对应的内容列表(
Truth/Dare/MostLikely/Nhie)被意外清空,比如数据文件损坏、加载逻辑失效、其他代码误写清空操作 - 列表中存在空字符串元素,
random.choice()随机选中了空元素
解决步骤
1. 验证数据源完整性
- 检查
Truth等列表的初始化逻辑,确认是否从文件(如JSON、TXT)加载数据,文件是否存在、内容是否完整 - 排查代码中是否有其他地方修改了这些列表,比如误写
Truth = []导致列表被重置
2. 添加空值校验与过滤
在生成Embed前,先确保选中的内容有效,避免发送空消息。修改后的truth命令示例:
@bot.command() async def truth(ctx): # 先检查列表是否为空 if not Truth: await ctx.send("当前没有可用的Truth内容!") return # 过滤掉列表中的空元素和空白字符串 valid_items = [item for item in Truth if item.strip()] if not valid_items: await ctx.send("当前Truth列表中的内容均无效!") return # 从有效内容中随机选取 r3 = random.choice(valid_items) embed = discord.Embed(title=r3, color=0xC964F0) await ctx.send(embed=embed)
可以把相同的校验逻辑封装成函数,复用在who/nhie/dare命令中,减少重复代码。
3. 排查环境或依赖变化
如果近期更换了运行环境或更新了discord.py版本,确认新版本的API调用规则是否有变化(不过此报错和API版本关联度极低,优先级低于前两步)
内容的提问来源于stack exchange,提问作者star
相关产品推荐
相关产品推荐

