Discord.py消息变量为None引发edit报错,如何解决?
问题解决方法
核心问题点
interaction.response.send_message()执行后返回的是None,直接把它赋值给变量根本拿不到消息对象- 按钮回调类无法直接访问命令函数里的局部变量,导致你存的消息变量在回调里变成空值
具体解决步骤
1. 正确获取已发送的消息对象
别直接存 send_message 的返回值,发送完消息后用 original_response() 获取真实的消息对象:
# 错误写法 msg = await interaction.response.send_message(embed=my_embed, view=my_view) # 正确写法 await interaction.response.send_message(embed=my_embed, view=my_view) msg = await interaction.original_response()
2. 让按钮回调能访问到消息对象
有两种实用方式:
- 方式一:把消息对象传入按钮类
给按钮类加初始化参数,把消息对象存为实例属性:
class NextButton(discord.ui.Button): def __init__(self, target_msg): super().__init__(label="下一页", style=discord.ButtonStyle.green) self.target_msg = target_msg async def callback(self, interaction: discord.Interaction): # 直接用保存的消息对象编辑 new_embed = discord.Embed(title="更新后的标题", description="更新后的内容") await self.target_msg.edit(embed=new_embed)
在命令函数里创建按钮时传入消息对象:
msg = await interaction.original_response() view = discord.ui.View() view.add_item(NextButton(msg)) # 注意:要先获取msg再创建按钮,确保传的是有效对象
- 方式二:在回调中重新获取消息
如果不想传递变量,直接在回调里调用original_response()获取原消息:
async def callback(self, interaction: discord.Interaction): msg = await interaction.original_response() new_embed = discord.Embed(title="更新后的标题", description="更新后的内容") await msg.edit(embed=new_embed)
额外提醒
- 确认机器人拥有编辑消息的权限
- 如果是后续发送的跟进消息,要用
await interaction.followup.fetch_message(消息ID)来获取对应消息
内容的提问来源于stack exchange,提问作者Retr0
相关产品推荐
相关产品推荐

