简体   繁体   中英

How to keep track of messages sent in discord.py

I want to keep track and assign a number to every message sent in discord.py, I'm building an antispam bot and basically every time someone sends a message I want it to add to a counter of how many messages the user has sent in a certain amount of time, I then want it to reset that counter every say 5 seconds.

@b.event
async def on_message(message):
    await b.process_commands(message)
    #Add 1 to a user specific counter
    if counter > 5:
        await message.send("Stop sending messages")
    #Reset the counter every 20 seconds

First, you'll want to create a dictionary to keep track of how many messages each user sends.

spam_logger = {}

Secondly when a message is sent, you want to add the user to the dictionary. If the user exists in the dictionary, we add one to how many messages they sent, if they don't exist in the dictionary, we add their name and give it a value of one.

@client.event 
async def on_message(message):
    global spam_logger
    try:
        spam_logger[str(message.author)] += 1
    except KeyError:
        spam_logger[str(message.author)] = 1

Thirdly, we want to check if a user has sent more than 5 messages.

    for name, messages_sent in spam_logger.items():
        if messages_sent >= 5:
            await message.channel.send(f'Stop sending messages!')

Finally, we want to clear the list every 5 seconds.

@tasks.loop(seconds=5)
async def clear_spam_logger():
    global spam_logger
    spam_logger.clear()

@clear_spam_logger.before_loop
async def before():
    await client.wait_until_ready()

clear_spam_logger.start()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM