使用discord.py在通道中检索先前发送的消息的命令



我一直在寻找使用@name_of_object.command()做以下列出的事情的方法。

  • 检索某通道最近x天内的消息。
  • 检索到的消息存储在具有3个参数的数组中。该数组的每个元素包含3种类型的信息,分别是消息、发送者和发送时间。

我在这里搜索了答案,并认为created_at可能对实现我想要做的事情有用。谁能告诉我一些提示或者我应该看哪些网站?

我做了什么:

我从这里引用了下面的代码

@bot.command()
async def getmsg(ctx, channel: discord.TextChannel, member: discord.Member):
msg = discord.utils.get(await channel.history(limit=100).flatten(), author=member)
# this gets the most recent message from a specified member in the past 100 messages
# in a certain text channel - just an idea of how to use its versatility


您可以使用channel.history来检索按日期过滤的消息。

要做到这一点,首先获得一个datetime-Object,指定您想要获得消息的日期(如果您想要,也可以指定到哪个日期)。在您的情况下,您应该能够使用像

这样的内容
date = datetime.datetime.now() - datetime.timedelta(days=5)

date中,我们现在有一个代表五天前的datetime-Object。

作为下一步,您可以使用channel.history()检索该日期之后的所有消息,特别是其after参数。这为您提供了一个async iterator-对象。假设您的bot命名为bot,而您使用的是discord.ext.commands,您可以执行如下操作

@bot.command()
async def test(ctx):
channel = await bot.fetch_channel(YOUR_CHANNEL_ID)
async for message in channel.history(after=date):
print(message.created_at, message.author.name, message.content)

记住将YOUR_CHANNEL_ID替换为文本通道的id(您可以通过Rightclick → Copy ID获取它)。如果您在希望从中获取消息的同一通道中运行命令,您还可以使用ctx.channel,而不是通过其id获取它。

如果你刚开始使用discord命令,我还建议你看一下这个命令介绍,它更详细地解释了一些基础知识(以及你已经找到的API参考)。

最新更新