【问题标题】:How to get past messages from a specific channel in discord.py如何从 discord.py 中的特定频道获取过去的消息
【发布时间】:2021-05-21 10:56:32
【问题描述】:

基本上我想让我的机器人从特定渠道获取消息。

例子:

#general contains:
Hello
Hi
Welcome

机器人应该能够在收到类似命令后输出 您好,您好,欢迎使用

我尝试了 ctx.history,但出现了严重错误,它给了我一长串除了消息之外的所有内容。

【问题讨论】:

  • 请显示代码。如果我们不知道您尝试了什么,没有人可以帮助调试。

标签: python discord discord.py


【解决方案1】:

由于ctx 具有对应于许多不同对象的属性,ctx.history() 可能调用了“错误”history() 方法,为不同通道中的消息返回 AsyncIterator。 (请参阅此documentation search 了解可能已调用的许多 history() 方法的列表。)

因此,解决方案是指定您想要 TextChannel 历史记录:

async for message in ctx.channel.history():
    ...

或者,如果所需的通道不是调用命令的

channel = discord.utils.get(ctx.guild.channels, id=CHANNEL_ID)
async for message in channel.history():
    ...

【讨论】:

  • 如果您不想使用async for,也可以msgs = await channel.history().flatten()
  • ctx.history() 将始终引用 ctx.channel.history()。此外,ctx.channel 也可以是 DMChannel。
【解决方案2】:

我编写了一个简短的命令,用于获取给定频道的历史并将其输出到 .txt 文件:

@bot.command
async def log_channel(self, ctx):
  filename = str(ctx.channel.name)
    with open(f"{filename}.txt", "w+") as fp:
      async for msg in ctx.channel.history(limit=None):
        try:
          towrite = f"[{msg.author.name}] @ [{msg.created_at}] said: {msg.clean_content} \n"
        except:
          towrite = "message unreadable. likely an image?"
        fp.write(towrite)
  await ctx.send(file=discord.File(f"{filename}.txt"))

您调用ctx.history 时可能做错的事情是您希望它以文本形式返回消息列表 - 它没有这样做,它返回消息objects。你可以阅读更多关于discord.Messagehere的信息。从消息对象中获取文本有两种方法,可以调用discord.Message.content,也可以调用discord.Message.clean_content。就个人而言,我发现clean_content 对于诸如日志记录之类的应用程序更有用,在这些应用程序中,消息不一定会以不和谐的方式保存在提及可以适当呈现的地方。 clean_content 删除所有提及并用它们自己的文本版本替换它们,例如<#id> turns into #name. discord.Message.content 另一方面以 保持 的形式返回所有内容。它不会变成#name。选择你认为更适合你正在做的事情的那个,然后运行它。

【讨论】:

    猜你喜欢
    • 2021-07-30
    • 2020-06-29
    • 1970-01-01
    • 2021-01-12
    • 2022-08-15
    • 2021-07-28
    • 2021-09-18
    • 1970-01-01
    • 2021-03-18
    相关资源
    最近更新 更多