如何在discord.py中获取频道的最新消息?

leo*_*848 9 python discord discord.py

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

leo*_*848 11

我现在已经自己弄清楚了:

对于一个discord.Client类,您只需要最后一条消息的这些代码行:


(await self.get_channel(CHANNEL_ID).history(limit=1).flatten())[0]

Run Code Online (Sandbox Code Playgroud)

如果您使用discord.ext.commands.Bot@thegamecracks'答案是正确的。


小智 8

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

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

channel = self.bot.get_channel(int(ID))
Run Code Online (Sandbox Code Playgroud)

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

message = await channel.fetch_message(
    channel.last_message_id)
Run Code Online (Sandbox Code Playgroud)

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

@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
Run Code Online (Sandbox Code Playgroud)