How To Get The Most Recent Message Of A Channel In Discord.py?
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.
Solution 1:
(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')asyncdefclient_getlastmessage(self, ctx, ID):
"""Get the last message of a text channel."""
channel = self.bot.get_channel(int(ID))
if channel isNone:
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 checkawait 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
Solution 2:
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.
Post a Comment for "How To Get The Most Recent Message Of A Channel In Discord.py?"