discord.py交互消息30分钟后编辑报无效Webhook Token的解决办法咨询
问题解决:Discord.py交互消息超时编辑失败
问题原因
Discord 交互响应返回的消息(通过interaction.original_response()获取)使用的是临时Webhook令牌,这个令牌的有效期只有30分钟。超时后令牌失效,再调用msg.edit()就会触发401权限错误。
解决方案
方案1:改用频道直接发送消息
放弃用交互响应发送消息,直接通过频道发送普通消息,这样得到的消息对象使用机器人的全局令牌,没有时间限制。
修改后的代码示例:
async def editmsg(msg, con): await msg.edit(content=con) @app_commands.command(name='sendmsg', description='sendmsg') async def sendmsg(self, interaction: Interaction): # 直接发送频道消息,而非交互响应 msg = await interaction.channel.send(content='message') # 回复交互避免超时 await interaction.response.send_message("消息已发送", ephemeral=True) # 按钮点击时执行编辑 await editmsg(msg, 'editmessage')
方案2:保存消息ID和频道ID,超时后重新获取消息
如果必须使用交互响应的消息,提前保存消息的ID和所属频道ID,需要编辑时通过机器人客户端重新获取消息对象,再进行编辑。
修改后的代码示例:
# 实际项目建议用数据库存储,这里用全局变量做示例 saved_channel_id = None saved_message_id = None async def editmsg(client, channel_id, message_id, con): channel = await client.get_channel(channel_id) msg = await channel.fetch_message(message_id) await msg.edit(content=con) @app_commands.command(name='sendmsg', description='sendmsg') async def sendmsg(self, interaction: Interaction): await interaction.response.send_message(content='message') msg = await interaction.original_response() # 保存关键信息 global saved_channel_id, saved_message_id saved_channel_id = msg.channel.id saved_message_id = msg.id # 按钮点击时执行编辑 await editmsg(self.client, saved_channel_id, saved_message_id, 'editmessage')
注意:实际开发中不要用全局变量存储ID,推荐用数据库或缓存系统持久化这些信息,防止机器人重启后数据丢失。
内容的提问来源于stack exchange,提问作者권대현
相关产品推荐
相关产品推荐

