0

Im trying to make a game using discord.py. I need a way to save the data So.. when I stopped the bot and run it again the data will not disappear

Here is my current code:

async def token():
  global counter
  counter = 0
  while True:
    await asyncio.sleep(5)
    counter += 1

@client.event
async def on_message(message):

  if message.content.startswith('check'):
    await message.channel.send(counter)

client.loop.create_task(token())
Pokero
  • 43
  • 2
  • 9
  • have you looked at file operations in python: https://realpython.com/read-write-files-python/? – Krishna Chaurasia Jan 22 '21 at 06:51
  • yes............ – Pokero Jan 22 '21 at 07:00
  • does it not solve your problem? – Krishna Chaurasia Jan 22 '21 at 07:00
  • What specifically do you need help with? Whatever data you want to persist needs to be written to disk before the bot shuts down, and read when the bot starts up. You can serialize your data in any number of ways: `pickle`, `json`, `xml`, `toml`... take your pick. As it stands, your question gives us nothing to go on. I suggest you look into one of those libraries, they should tell you all that you need to know. – ZeroKnight Jan 22 '21 at 07:23
  • whenever i can. – Pokero Jan 22 '21 at 08:22

1 Answers1

1

The answer to this question depends on the way your python program will shut down, if you shut it down 'the normal way' a try-finally loop would do the trick. Something like this:

with open('counter.txt', 'r') as f:
    counter = int(f.readline())
try:
    client.run(TOKEN)
finally:
    with open('counter.txt', 'w') as f:
        f.write(counter)

However if you 'kill' the program that finally part might not run, a solution to this would be to kill the bot from within discord, with a command containing client.close()

Another way is to modify your counter function so it would always save the current counter whenever it changes

async def token():
  global counter
  counter = 0
  while True:
    await asyncio.sleep(5)
    counter += 1
    with open('counter.txt', 'w') as f:
        f.write(counter)

Also note that as your program is right now you set the counter to 0, you'll need to add loading the value too (this:)

with open('counter.txt', 'r') as f:
    counter = int(f.readline())

Ofcourse if you dont just want to save a simple counter, you're going to have to use json or pickle, but the method stays the same

FierySpectre
  • 642
  • 3
  • 9
  • How do I read a specific line in the counter.txt ? – Pokero Jan 23 '21 at 09:58
  • This might help you for reading specific line in a txt file: https://stackoverflow.com/questions/2081836/reading-specific-lines-only I advise to not use .txt for saving anything though, it's easier to use pickle or json, use json if you need a readable file and pickle if you need to just save things. (with those you can just save and get back object like lists, dicts, etc) – FierySpectre Jan 23 '21 at 10:01