我正在尝试为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}")
答案 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
,因为我认为这样可以更轻松地控制要写入文件的内容。