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

Discord.py删除命令报错:'async_generator'无'flatten'属性

解决Discord.py批量删除消息命令中的AttributeError错误

错误原因

你遇到的discord.app_commands.errors.CommandInvokeError根源是:

  • Discord.py v2.0+版本中,channel.history()返回的是异步生成器,不再有旧版本的flatten()方法;
  • 你代码里还错误地写成了flatten(缺少调用括号(),就算旧版本这样写也会引发错误)。

修复后的完整代码

import asyncio
import discord
from discord import app_commands

@bot.tree.command(name="supprimer_message")
@app_commands.describe(nombres="Combien de messages ?")
async def supprimer_message(interaction: discord.Interaction, nombres: int):
    if nombres > 1000:
        await interaction.response.send_message(
            f"Je ne peux pas supprimer autant de messages ({nombres}/1000)",
            ephemeral=True
        )
    else:
        # 先延迟交互响应,避免超时报错
        await interaction.response.defer(ephemeral=False)
        count_members = {}
        # 用异步列表推导式获取消息(替代旧的flatten())
        messages = [msg async for msg in interaction.channel.history(limit=nombres)]
        
        for message in messages:
            author_str = str(message.author)
            if author_str in count_members:
                count_members[author_str] += 1
            else:
                count_members[author_str] = 1
        
        # 生成统计字符串
        new_string = [f"**{author}**: {count}" for author, count in count_members.items()]
        final_string = '\n'.join(new_string)
        total_deleted = sum(count_members.values())
        
        # 删除消息(+1是包含触发命令的那条消息)
        await interaction.channel.purge(limit=nombres + 1)
        
        # 发送结果通知
        msg = await interaction.followup.send(
            f"{total_deleted} messages ont été supprimés !\n\n{final_string}"
        )
        await asyncio.sleep(5)
        await msg.delete()

关键修改点说明

  1. 替换flatten()的使用:
    用异步列表推导式[msg async for msg in interaction.channel.history(limit=nombres)]来获取所有消息,这是Discord.py v2.x推荐的方式。
  2. 修复交互响应逻辑:
    在else分支开头添加await interaction.response.defer(ephemeral=False),避免因为处理时间过长导致交互超时,后续用followup.send()发送结果。
  3. 修正统计逻辑:
    用sum(count_members.values())直接计算总删除消息数,替代原来错误的列表追加逻辑(原代码中deleted_messages += message_deleted会因类型不匹配报错)。
  4. 修复语法和拼写错误:
    • 把字符串拼接中的无效换行符改成'\n';
    • 修正法语拼写错误:Je ne pas → Je ne peux pas,ont était supprimer → ont été supprimés。
  5. 优化变量命名:
    调整部分变量名(如message_deleted → count),提升代码可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:15:41