Reputation: 69
I'm wondering if there is a way for the bot to get the last message a user has sent in the server chat using discord.py in Python? Thanks a lot
Upvotes: 2
Views: 23942
Reputation: 1173
Old answer discord.py async (pre-rewrite)
Use log_froms
to get the messages from a channel.
and use get_all_channels
to go through all the channels.
Then search through the results for the latest version of the author. You have to go through each channel for a reasonable amount until you find a message from that person and then stop. The compare the first from each channel to get the latest time.
To get better help in the future consider joining the "discord api" discord server
Edit: Method compatible with discord.py rewrite (+1.0)
You can use channel.history()
to get the history of a channel. It by default only fetches the latest 100 messages from a channel. You can increae this limit with the limit
keyword. (e.g. channel.history(limit = 200)
You can combine this with a find
async iterator to get just the messages from the user with the id you are looking for await channel.history().find(lambda m: m.author.id == users_id)
.
You then need to loop through each text channel in the server doing this and find the latest message in channel by comparing them to the previous fetched message and keeping the one which was created newer.
Example command which find the latest message by the user.
@commands.command()
async def lastMessage(self, ctx, users_id: int):
oldestMessage = None
for channel in ctx.guild.text_channels:
fetchMessage = await channel.history().find(lambda m: m.author.id == users_id)
if fetchMessage is None:
continue
if oldestMessage is None:
oldestMessage = fetchMessage
else:
if fetchMessage.created_at > oldestMessage.created_at:
oldestMessage = fetchMessage
if (oldestMessage is not None):
await ctx.send(f"Oldest message is {oldestMessage.content}")
else:
await ctx.send("No message found.")
This is a fair slow operation in my testing due to having to make many requests to discord but should work.
Upvotes: 2