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

Discord机器人channel.history调用报错:'async_generator'无flatten属性

Discord机器人channel.history报错:'async_generator' object has no attribute 'flatten' 解决方法

问题原因

discord.py版本更新后,channel.history()的返回值发生了变化——从原本带有flatten()方法的MessageHistory对象,改为了异步生成器,因此直接调用.flatten()会触发属性不存在的错误。

修复方案

方案1:异步列表推导式(简洁写法)

用异步列表推导直接将异步生成器转换为消息列表,替代原来的flatten():

if message.content.startswith("historytest"):
    # 用异步列表推导收集消息
    messages = [msg async for msg in message.channel.history(limit=5)]
    # 注意:send不能直接传Message对象列表,需提取内容转为字符串
    await message.channel.send("\n".join([msg.content for msg in messages]))

方案2:async for循环遍历收集

如果需要更灵活的处理逻辑(比如过滤特定消息),可以用async for循环逐个收集:

if message.content.startswith("historytest"):
    messages = []
    async for msg in message.channel.history(limit=5):
        messages.append(msg)
        # 这里可以加额外处理,比如只保留包含特定关键词的消息
    await message.channel.send("\n".join([msg.content for msg in messages]))

额外提示

原测试代码中await message.channel.send(messages)本身也会报错,因为Discord的send方法不支持直接发送Message对象的列表,必须提取消息内容(如msg.content)或其他属性转为字符串后再发送。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 11:17:35