Daniel Tam
Daniel Tam

Reputation: 926

How to Store User Data permanently without using a list in discord.py?

Basically what I'm trying to do is make a blacklist command that removes bad words whenever it is said. And I want the moderator of the server to be able to blacklist their words manually. A list only stores data for as long as the bot is running. So it doesn't work. I want to basically save a user's input permanently. How do I do that? I'm using discord.py rewrite btw.

Upvotes: 0

Views: 262

Answers (1)

Marko Borković
Marko Borković

Reputation: 1922

Well you need to save the data to disk or some kind of database. The simplest way to do it is to store all the blacklisted words in one text file.

You can use these functions:

def saveFilterToFile(filterList,  filename):
  f = open(filename, "w")
  for word in filterList:
    f.write(word+"\n")
  f.close()

def loadFilterFromFile(filename):
  f = open(filename, "r")
  filterList = f.readlines()

  #remove new lines
  for i in range(0, len(filterList)):
    filterList[i] = filterList[i][:len(filterList[i])-1] 

  f.close()
  return filterList

And simply when a new blacklisted word is added just add it to your filter list and do something like this:

saveFilterToFile(blacklistedWords, "wordblacklist.txt")

And every time your bot starts up simply load the blacklisted words from the file you saved before

blacklistedWords = loadFilterFromFile("wordblacklist.txt")

You should also modify the functions a bit to check for errors while reading, writing etc.

Upvotes: 2

Related Questions