1

I am stuck on a seemingly simple task with a Python Twitch IRC Bot I'm developing for my channel. I have a points system all figured out, and I thought it was working, but I found out that every time I restart the program, the list that contains balances of users resets.

This is because I declare the empty list at the beginning of the script each time the program is run. If a user chats and they aren't in the list of welcomed users, then the bot will welcome them and add their name to a list, and their balance to a corresponding list.

Is there someway I can work around this resetting problem and make it so that it won't reset the list every time the program restarts? Thanks in advance, and here's my code:

welcomed = []
balances = []

def givePoints():
    global balances
    threading.Timer(60.0, givePoints).start()
    i = 0
    for users in balances:
        balances[i] += 1
        i += 1
def welcomeUser(user):
    global welcomed
    global balances
    sendMessage(s, "Welcome, " + user + "!")
    welcomed.extend([user])
    balances.extend([0])

givePoints()
#other code here...

if '' in message:
    if user not in welcomed:
        welcomeUser(user)
break

(I had attempted to use global variables to overcome this problem, however they didn't work, although I'm guessing I didn't use them right :P)

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
lucap
  • 83
  • 2
  • 10
  • You can't make a list persist between executions of the script, but you can write the list to a file and read it when you start up. – Paul Rooney Feb 26 '16 at 04:33
  • I had thought about that, however would it insert the string versions of the text file into the list in a way that wouldn't allow it to iterate through the balances and increase them? – lucap Feb 26 '16 at 04:35
  • There are multiple ways to save lists such as `json` and `pickle`. You'd read that list back at restart and have the current values. – tdelaney Feb 26 '16 at 04:40
  • See [this](http://stackoverflow.com/questions/18229082/python-pickle-unpickle-a-list-to-from-a-file) question. – Paul Rooney Feb 26 '16 at 04:44

1 Answers1

3

Try using the json module to dump and load your list. You can catch file open problems when loading the list, and use that to initialize an empty list.

import json

def loadlist(path):
    try:
        with open(path, 'r') as listfile:
            saved_list = json.load(listfile)
    except Exception:
            saved_list = []
    return saved_list

def savelist(path, _list):
    try:
        with open(path, 'w') as listfile:
            json.dump(_list, listfile)
    except Exception:
        print("Oh, no! List wasn't saved! It'll be empty tomorrow...")
AddingColor
  • 596
  • 1
  • 5
  • 24
aghast
  • 14,785
  • 3
  • 24
  • 56