首页 > 解决方案 > 如何在 discord.py 中获取频道的最新消息?

问题描述

有没有办法使用 discord.py 获取特定频道的最新消息?我查看了官方文档并没有找到方法。

标签: pythondiscorddiscord.py

解决方案


(答案使用discord.ext.commands.Bot而不是discord.Client;我没有使用 API 的较低级别部分,所以这可能不适用于discord.Client

在这种情况下,您可以使用Bot.get_channel(ID)获取要检查的通道。

channel = self.bot.get_channel(int(ID))

然后,您可以使用channel.last_message_id获取最后一条消息的 ID,并使用 获取消息channel.fetch_message(ID)

message = await channel.fetch_message(
    channel.last_message_id)

组合起来,获取频道最后一条消息的命令可能如下所示:

@commands.command(
    name='getlastmessage')
async def client_getlastmessage(self, ctx, ID):
    """Get the last message of a text channel."""
    channel = self.bot.get_channel(int(ID))
    if channel is None:
        await ctx.send('Could not find that channel.')
        return
    # NOTE: get_channel can return a TextChannel, VoiceChannel,
    # or CategoryChannel. You may want to add a check to make sure
    # the ID is for text channels only

    message = await channel.fetch_message(
        channel.last_message_id)
    # NOTE: channel.last_message_id could return None; needs a check

    await ctx.send(
        f'Last message in {channel.name} sent by {message.author.name}:\n'
        + message.content
    )
    # NOTE: message may need to be trimmed to fit within 2000 chars

推荐阅读