How to get the most recent message of a channel in discord.py?

Viewed 10211

Is there a way to get the most recent message of a specific channel using discord.py? I looked at the official docs and didn't find a way to.

2 Answers

I've now figured it out by myself:

For a discord.Client class you just need these lines of code for the last message:


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

If you use a discord.ext.commands.Bot @thegamecracks' answer is correct.

(Answer uses discord.ext.commands.Bot instead of discord.Client; I haven't worked with the lower level parts of the API, so this may not apply to discord.Client)

In this case, you can use Bot.get_channel(ID) to acquire the channel you want to inspect.

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

Then, you can use channel.last_message_id to get the ID of the last message, and acquire the message with channel.fetch_message(ID).

message = await channel.fetch_message(
    channel.last_message_id)

Combined, a command to get the last message of a channel may look like this:

@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
Related