【问题标题】:Discord.py logging messagesDiscord.py 记录消息
【发布时间】:2021-05-17 06:52:01
【问题描述】:

我有这个代码,当我输入 !snapshot 时应该记录频道中的最后 100 条消息,并将它们制作成一个文本文件:

snapshot_channel = (my snapshot channel ID)

@commands.has_permissions(administrator=True)
@bot.command()
async def snapshot(ctx):
    channel = bot.get_channel(snapshot_channel)
    await ctx.message.delete()
    messages = message in ctx.history(limit=100)
    numbers = "\n".join(
        f"{message.author}: {message.clean_content}" for message in messages
    )
    f = BytesIO(bytes(numbers, encoding="utf-8"))
    file = discord.File(fp=f, filename="snapshot.txt")
    await channel.send("Snapshot requested has completed.")
    await channel.send(file=file)

我已经导入了 BytesIO,它适用于清除消息并记录它们的不同命令,但是这段代码应该只是创建一个日志然后在通道中发送它不起作用。请你把它应该是什么样子的工作发送给我。谢谢!

【问题讨论】:

  • 任何错误/回溯?
  • discord.ext.commands.errors.CommandInvokeError: 命令引发异常:NameError: name 'message' is not defined

标签: discord.py


【解决方案1】:

TextChannel.history 是一个异步生成器,你没有正确使用它

messages = await ctx.channel.history(limit=100).flatten()
numbers = "\n".join([f"{message.author}: {message.clean_content}" for message in messages])

另一种选择是

numbers = ""
async for message in ctx.channel.history(limit=100):
    numbers += f"{message.author}: {message.clean_content}"

【讨论】:

    猜你喜欢
    • 2021-04-04
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 2021-08-11
    • 2021-08-17
    相关资源
    最近更新 更多