F.M
F.M

Reputation: 1859

How to retrieve previous messages with discord.py

I have a counting channel in my server, and I want to make a bot where it removes your message if it isn't 1 number after the previous message. I tried Googling on how to retrieve previous messages but got no results.

Upvotes: 2

Views: 10114

Answers (1)

Nurqm
Nurqm

Reputation: 4743

You can use discord.TextChannel.last_message to get the last message of a channel.

@client.event
async def on_message(message):
    c_channel = discord.utils.get(message.guild.text_channels, name='counting channel')
    if message.channel == c_channel and int(c_channel.last_message.content) + 1 != int(message.content):
        await message.delete()

EDIT:

You can use channel.history if channel.last_message is not working.

@client.event
async def on_message(message):
    c_channel = discord.utils.get(message.guild.text_channels, name='counting channel')
    messages = await c_channel.history(limit=2).flatten()
    if message.channel == c_channel and int(messages[1].content) + 1 != int(message.content):
        await message.delete()

messages = await c_channel.history(limit=2).flatten() returns you the last 2 messages of a channel.

If this doesn't work, then change the int(messages[1].content) to int(messages[0].content).

Upvotes: 4

Related Questions