Reputation:
im working on a discord bot and it has a command called "addtoken" that asks for a name and a contract, and it adds the token to a Dict. But i want to store that added tokens so when i start the bot again i have those. Here is the function where "blq" is another file where i have the initial dictionary and "tokens_dict" is the variable that has the dict on it:
@bot.command()
async def addtoken(ctx, key, value):
if(key in blq.tokens_dict.keys()):
await ctx.reply('I already have this token on my list, please add another Contract or another Value')
else:
blq.tokens_dict[key] = value
I would like to do it with a data base but im new and still can't find a solution with sqlite3.
Upvotes: 1
Views: 789
Reputation: 569
Data that sticks around even after stopping and restarting a program is called persistent data
. Using a full database like sqlite can be very challenging to learn, however there are simpler solutions out there.
My favorite super-easy persistent database is called pickleDB. It works similar to a dictionary, but it stores everything in a file so the data will still persist even after restarting the program.
Use pip install pickleDB
to install it, then at the top of your code import it with import pickledb
. Create/load the database by using db = pickledb.load('discord.db', true)
under your imports. The first part is defining what you want the filename to be and the second part is setting autodump on. Autodump automatically saves new things added to the database in the file, without it you would need to use db.dump()
after every time you write to the database to make sure it gets saved. Now whenever you want to store data use db.set(your_key, your_value)
and whenever you want to get that data use db.get(your_key)
.
Here's an example of that being put to use:
import pickledb
db = pickledb.load('discord.db', true)
db.set("message_1", "hi there") # If you where to run this program once, then remove this line, the line below would still print "hi there" since the data is persistent
print(db.get("message_1")) # prints "hi there".
and here's an example of what your segment of code would look like if you used pickledb instead:
@bot.command()
async def addtoken(ctx, key, value):
if(key in db.getall()):
await ctx.reply('I already have this token on my list, please add another Contract or another Value')
else:
db.set(key, value)
PickleDB should not be used if you are storing large amounts of data since it isn't really optimized for that, but for your use case it seems like it would work perfectly!
Leave a comment and let me know if you have any questions about it!
Upvotes: 1