如何将文本通道消息历史记录写入.txt?

时间:2019-05-01 06:41:52

标签: python discord.py-rewrite

我正在尝试为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}")

1 个答案:

答案 0 :(得分:0)

您无需将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=,因为它默认使用回调的名称,每个命令都需要传递一个invocation context,我添加了一个limit参数以便您可以控制要获取多少消息,我将write更改为带有print参数的file,因为我认为这样可以更轻松地控制要写入文件的内容。