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

