How do I get the last message sent by a certain user in a certain channel with discord.py?

Question:

I am trying to get the last message that user 476686545034674176 sent in channel 1049386904065409054 and when I try to debug it, I either get a weird output or an error that says it is a Nonetype after I got an output that should trigger if it got a message.

I tried:

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

    await tree.sync(guild=discord.Object(id=1049253865112997888))

    aviv_venting_about_his_shitass_brothers = client.get_channel(1049386904065409054)
    global last_message
    async for message in aviv_venting_about_his_shitass_brothers.history(limit=1000):
        if message.author.id == 476686545034674176:
            last_message = message

            if last_message is None:
                print('no messages found')
            elif last_message.content == None:
                print('invalid message')
            else:
                print(f'found message {last_message.content}')
                break

There is a line later in the code:

   await interaction.response.send_message(f'aviv last vented at        {datetime.datetime.fromtimestamp(last_message.created_at).strftime("%Y-%m-%d %H:%M:%S")} <@{interaction.user.id}>')

and it gives me this error:
discord.app_commands.errors.CommandInvokeError: Command ‘last_vent’ raised an exception: TypeError: ‘datetime.datetime’ object cannot be interpreted as an integer

I expected to get an output when the bot starts up and I either get no output or ‘found message’

Asked By: Tauman

||

Answers:

Your problem is not that the bot doesn’t find a matching message, its problem lies within the execution of the send_message command. Read the error message. You’re trying to pass an invalid type for an argument. I am not familiar with the intricacies of discord.py, but if I could hazard a guess, last_message.created_at already is a datetime object.

Answered By: the_strange
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.