Home > Back-end >  How can I append and save a list into another file in Discord Py?
How can I append and save a list into another file in Discord Py?

Time:09-21

I'm basically making something that will take the users content then puts it in the list. I would like to store it in another file called 'problems' how would I do that? This is my code for the main Discord Bot

import discord
import random
import problems

TOKEN = "SECRET"

client = discord.Client()

@client.event
async def on_ready():
    print("Bot is ready!")

@client.event
async def on_message(message):
    username = str(message.author).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f"{username}: {user_message} ({channel})")

    if message.author == client.user:
        return
    if message.channel.name == 'test':
        if user_message.lower() == 'hello':
            await message.channel.send(f"Hello {username}!")
            return
        elif user_message.lower() == 'bye':
            await message.channel.send(f"Bye!")
            return
        elif message.content.startswith("!store"):
            a = message.content[6:]
            await message.channel.send("Stored!")
            problemlist = problems.problem.append(a)
            print(problemlist)
    if user_message.lower() == '!code':
        await message.channel.send()
client.run(TOKEN)

Here's the inside of my problems.py

problem = []

Basically an empty list What I'm getting when it prints the problemlist is None

Also, I would like the list to persist after the bot has restarted.

CodePudding user response:

In python (and all other languages that I know of), when you import another python file, it loads it as code, so if your problems.py is as you've stated above, it executes problems = [] every time the script starts, and once the script starts, that content is cleared from memory.

If you are doing something really simple, the best approach here would be write the variable to a file, using pickle or json. I've given an example of reading and writing below.

import json

def read(filename):
    """Open the file, read it and parse the json"""
    try:
        with open(filename, 'r') as json_file:
            return json.loads(json_file.read())
    except FileNotFoundError:
        return {}

def write(filename, save_object):
    """Open the file, and write the object as json"""
    with open(filename, 'w') as json_file:
        json_file.write(json.dumps(save_object))

# Get the problems list if it exists.
problems = read('problems.json').get('problems', None) 
# If it doesn't create it.
if problems is None:
    problems = []
problems.append("problem")
write('problems.json', {'problems': problems})

This would mean the problems.json file would look something like this:

{
    "problems": [ "1", "2", "3", "4"]
}
  • Related