You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord机器人集成删除功能报错:'async_generator'无flatten属性

解决Discord机器人删除消息功能的AttributeError问题

问题原因

在新版discord.py中,ctx.channel.history()返回异步生成器(async generator),而非旧版本具备flatten()方法的MessageHistory对象,因此直接调用.flatten()会触发AttributeError。

解决方案

方案1:转为列表后逐个删除

使用异步列表推导式将异步生成器中的消息收集为列表,再遍历删除:

@bot.command(name='del')
async def delete(ctx: commands.Context, number_of_messages: int):
    messages = [msg async for msg in ctx.channel.history(limit=number_of_messages + 1)]
    for each_message in messages:
        await each_message.delete()

方案2:迭代生成器直接删除

无需一次性加载所有消息到内存,适合删除大量消息时使用:

@bot.command(name='del')
async def delete(ctx: commands.Context, number_of_messages: int):
    async for msg in ctx.channel.history(limit=number_of_messages + 1):
        await msg.delete()

方案3:批量删除(更高效)

利用bulk_delete()方法一次性删除多条消息,注意该方法仅支持删除14天以内的消息,且机器人需要对应权限:

@bot.command(name='del')
async def delete(ctx: commands.Context, number_of_messages: int):
    messages = [msg async for msg in ctx.channel.history(limit=number_of_messages + 1)]
    await ctx.channel.bulk_delete(messages)

内容的提问来源于stack exchange,提问作者Fadaaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 15:17:11