如何用Discord.py获取频道倒数第二条消息并编辑其嵌入内容
解决方法
错误原因
在Discord.py v2.0及以上版本中,channel.history()返回的是异步生成器(async_generator),不再提供flatten()方法,这是触发AttributeError的直接原因。
修正后的代码
@bot.command() async def edit(ctx, gif): channel = ctx.channel # 从频道历史中获取最近2条消息,按时间倒序排列(最新的在前) messages = [msg async for msg in channel.history(limit=2)] # 倒数第二条消息是列表的第二个元素(索引1) target_msg = messages[1] # 删除触发命令的消息 await ctx.message.delete() # 检查目标消息是否存在嵌入内容 if not target_msg.embeds: await ctx.send("目标消息中没有嵌入内容!") return # 修改嵌入的图片 embed = target_msg.embeds[0] embed.set_image(url=gif) # 编辑目标消息的嵌入 await target_msg.edit(embed=embed)
关键优化说明
- 用异步列表推导式
[msg async for msg in channel.history(limit=2)]替代已废弃的flatten(),正确收集异步生成器中的消息对象。 - 直接使用历史中获取的
target_msg,无需再次调用fetch_message(),减少不必要的API请求。 - 添加嵌入存在性检查,避免因目标消息无嵌入导致索引错误。
- 修改嵌入后直接传递修改后的
embed对象,逻辑更清晰。
内容的提问来源于stack exchange,提问作者IhaveAquestionnn
相关产品推荐
相关产品推荐

