'py-cord: How do I delete the last n messages of a user?

I am writing an anti-spam bot in py-cord and I would like to delete a users last n messages automatically once they reach the pressure limit (= too much spam). My code for just deleting the messages so far is:

95 counter = 0
96 while counter < 10:
97    for channel in message.guild.channels:
98        for msg in channel.messages:
99            if msg.author.id == message.author.id and counter < 10:
100               await msg.delete()
101               counter += 1

and the error that I get is

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Username\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Username\OneDrive\Desktop\Dateien\Python\MessageCheck\messagecheck.py", line 98, in on_message
    for msg in channel.messages:
AttributeError: 'CategoryChannel' object has no attribute 'messages'

I tried searching for similar questions on StackOverflow, but the closest I got was 50301090, which doesn't quite answer my question as I don't want to use a command for this and it seems like it could put some strain onto the cache if it's run for some time.



Solution 1:[1]

Based upon the error, I'd say you are missing an indented block, making your first for loop do effectively nothing.

Try:

95 counter = 0
96 while counter < 10:
97    for channel in message.guild.channels:
98        for msg in channel.messages:
99            if msg.author.id == message.author.id and counter < 10:
100               await msg.delete()
101               counter += 1

Or the Error is saying you are not scoping properly.

Solution 2:[2]

It simply says that your channel which is of type CategoryChannel doesn't have a messages attribute to it which it doesn't if you look in the documentation.

Moreover what you are trying to implement already comes built-in with discord.py called purge() so you should just use that instead.

# Whatever you had here most like an on_message() listener
await channel.purge(limit=10, check=lambda msg: msg.author == person) 
# Here person is a discord.Member object which let's just say you stored from a command function

Also wanted to point out that this doesn't in fact delete the last 10 messages of the user but rather the messages sent by the user in the last 10 messages in the channel.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DD_EE
Solution 2