1
votes

I'm trying to make a message counter with discord.py using the on_message event, but for some reason the counter just stays at 1 all the time, here is my code so you can have a better understanding on what I'm talking about.

@cord.event
async def on_message(message):
    global message_counter
    message_counter = 0
    message_counter += 1
2
You reset message_counter to 0 everytime. Just remove the line message_counter = 0. - Guillaume
Initialize message_counter somewhere else, not in on_message. - Gino Mempin
Well everytime I put it somewhere it just keeps saying local variable 'message_counter' referenced before assignment - Zen
oh wait I was able to make it work by not moving the line global variable line from the on_message event - Zen

2 Answers

0
votes

You made the variable message_counter set to 0 every time someone speaks a message.

Try making it like this:

@cord.event
message_counter = 0
async def on_message(message):
    message_counter = message_counter + 1
0
votes

You will need to use either the global or nonlocal declarations at the top of the function.

message_counter = 0

@cord.event
async def on_message(message):
    global message_counter
    message_counter += 1