【问题标题】:Command which retrieves previously sent messages in a channel using discord.py使用 discord.py 在频道中检索先前发送的消息的命令
【发布时间】:2021-08-18 07:53:57
【问题描述】:

我一直在寻找使用@name_of_object.command() 执行以下列出的操作的方法。

  • 检索过去 x 天内频道中的消息。
  • 检索到的消息存储在具有 3 个参数的数组中。该数组的每个元素都包含 3 种类型的信息,即 Message 、发送者和发送时间。

我在here 中搜索了答案,并认为created_at 可能有助于实现我想做的事情。谁能告诉我一些提示或我应该看哪些网站?

我做了什么:

我引用了here下面的代码

@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



       

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

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

    为此,首先获取一个datetime-Object,指定您希望在该日期之后获取消息的日期(如果您愿意,还可以到哪个日期)。 在你的情况下,你应该能够使用类似的东西

    date = datetime.datetime.now() - datetime.timedelta(days=5)
    

    date 中,我们现在有一个datetime-表示五天前的对象。

    下一步,您可以使用channel.history() 尤其是它的after 参数检索该日期之后的所有消息。这为您提供了一个 async iterator-object 来使用。假设您的机器人名为 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 获取它。

    如果您刚开始使用不和谐命令,我还建议您查看this introduction to commands,它更详细地解释了一些基础知识(以及您已经找到的API reference)。

    【讨论】:

    • 谢谢你。我现在正在尝试对您的代码进行一些修改的代码。
    猜你喜欢
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 2021-03-18
    • 2021-05-03
    • 2021-05-17
    • 1970-01-01
    相关资源
    最近更新 更多