python - 如何将文本频道消息历史写入.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}")
解决方案
您不需要将 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
参数以便您可以控制要获取多少条消息,我将 更改write
为print
带有file
参数的 a,因为我认为这可以更容易地控制写入文件的内容。
推荐阅读
- python - 如何绕过不允许在存储桶名称中使用大写字母的 boto3 函数?
- android - Android 版本代码与 Play Console 显示的不同
- python - pandas:按特定列的 value_counts 保留数据帧的前 x%
- github - 通过正确修订的多个分支迁移到 Github
- python - 线图不显示轴上的所有日期
- c# - 如何访问子类的属性
- ruby-on-rails - 在 Rails 中,如何更改验证消息“更正以下错误”之前的文本?
- javascript - 使用一个函数中的一个值到另一个函数 nodejs express
- javascript - Javascript 对象返回失败
- django - 如何将 django-rest-framework 转换为 json 数据列表