1

PROGRAMM

@client.event
async def on_message(message):
    my_file = open("{0}.txt".format(message.author.id), "w")
    myfile1 = open("{0}.txt".format(message.author.id), "r")
    myfile1.read()
    my_file.write(myfile1.read() ++ number)
    my_file.close()

ERROR

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\senuk\AppData\Local\Programs\Python\Python35\lib\site-
packages\discord\client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "overmind.py", line 821, in on_message
    my_file.write(myfile1.read() ++ number)

number = 1

I'm trying to read the number of messages, which would then display them in the statistics about the user, but do not understand what the error and how to fix it, maybe someone knows?

SpaRk_PWM
  • 25
  • 1
  • 9

1 Answers1

0

You are mixing read and write on same file wrongly. Essentially you want to read first, then write. You are overwriting the same file again and again with an incrementing number.

# needs import os

@client.event
async def on_message(message): 
    fileName = "{0}.txt".format(message.author.id) 

    if os.path.exists(fileName):
        with open(fileName, "r") as readFile:
            data = int(readFile.read())
    else:
        data = 0

    with open(fileName, "w") as writeFile:
        writeFile.write(str(data+1))

You could also open as r+ and truncate the file after reading - you need to follow the truncate with a seek(0) though, as truncate does nothing to the file pointer: If I truncate a file to zero in Python 3 do I also need to seek to position zero?

See:

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Now i see this error... Ignoring exception in on_message Traceback (most recent call last): File "C:\Users\senuk\AppData\Local\Programs\Python\Python35\lib\site- packages\discord\client.py", line 307, in _run_event yield from getattr(self, event)(*args, **kwargs) File "overmind.py", line 828, in on_message data = int(readFile.read()) ValueError: invalid literal for int() with base 10: ' ' – SpaRk_PWM Feb 03 '18 at 14:30
  • @SpaRk_PWM file exists but is probably empty - so check for exist first, else use 0 as `data`. See edit. – Patrick Artner Feb 03 '18 at 14:31