首页 > 解决方案 > 如何将文本频道消息历史写入.txt?

问题描述

我正在尝试为我的 Discord 机器人创建一个命令,该命令会将频道历史记录写入 .txt。

我使用 channel.history().flatten() 尝试了几种不同的尝试。我确信我的代码存在重大问题,对此我深表歉意。我对此很陌生,还没有完全掌握这些概念。非常感谢。

@client.command(name="history")
async def history():
    channel_id = XXXXXXXXXXXXXXXX
    messages = await channel.history(channel_id).flatten()
    with open("channel_messages.txt", "a", encoding="utf-8") as f:
        f.write(f"{messages}")

标签: pythondiscord.py-rewrite

解决方案


您不需要将 id 传递给TextChannel.history

@client.command()
async def history(ctx, limit: int = 100):  
    messages = await ctx.channel.history(limit=limit).flatten()
    with open("channel_messages.txt", "a+", encoding="utf-8") as f:
        print(*messages, sep="\n\n", file=f)

其他更改:删除了,name=因为它默认使用回调的名称,每个命令都需要传递一个调用上下文,我添加了一个limit参数以便您可以控制要获取多少条消息,我将 更改writeprint带有file参数的 a,因为我认为这可以更容易地控制写入文件的内容。


推荐阅读