Ziqi
Ziqi

Reputation: 2554

Discord API - get messages before a date from a channel

I want to implement a command in my bot, to allow fetching messages from a channel and process them further.

I tried to look for how to fetch messages from a specific channel, but could not find an explicit answer to it, except most of the forum pages simply refer to the API page, with some saying trying the discord.utils.get method.

I am wondering if it would be something like this, but I could not find the matching methods/attributes that I can use to do this:

@bot.command(name='fetchmessages', help='....')
async def fetchmessages(ctx, from_channel_id:str, from_date:str):
    #check if the channels already exist       
    channel = discord.utils.get(ctx.guild.channels, id=from_channel_id)
    from_date = .... #code to parse the string to a date object
        
    discord.utils.get(channel.messages, # Q1
            from=from_date)             # Q2
    ####

However, I cannot really do this because

Any hints much appreciated.

Thanks

Upvotes: 2

Views: 5513

Answers (2)

Chris
Chris

Reputation: 1321

You are right that you can't use fetch_message because it only returns a single message, but you can use channel.history (link can be found here)

from datetime import datetime

@bot.command()
async def fetchmessages(ctx, from_channel_id:str, from_date:str):
    channel = client.get_channel(int(from_channel_id))
    date = datetime.strptime(from_date, '%b %d %Y %I:%M%p')
    messages = await ctx.channel.history(limit=200, after=date).flatten()
    
    #To do something with messages

Referenced this question regarding string to datetime object.

Upvotes: 1

yotam rec
yotam rec

Reputation: 575

Q1: you can use the channel.history() function but for that, you would have to have the read_message_history permissions to get access to those messages Q2: as you can read in discord.utils.get "To have a nested attribute search (i.e. search by x.y) then pass in x__y as the keyword argument." you can access whatever variable you want but instead of using '.' you need to use '_' so for example

discord.utils.get(channel.messages,created_at=from_date)

another thing that I just want to point out is the date attribute you're trying to get by has to be a datetime.datetime object

Upvotes: 1

Related Questions