如何从命令存储数据并加载它 discord.py

How to store data from a command and load it discord.py

我正在开发一个 discord 机器人,它有一个名为“addtoken”的命令,它要求输入名称和合同,并将令牌添加到字典中。但我想存储添加的令牌,所以当我再次启动机器人时,我有那些。这是函数,其中“blq”是另一个文件,其中我有初始字典,“tokens_dict”是包含字典的变量:

@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 

我想用数据库来做,但我是新手,仍然找不到 sqlite3 的解决方案。

即使在停止并重新启动程序后仍然存在的数据称为 persistent data。使用像 sqlite 这样的完整数据库可能很难学习,但是有更简单的解决方案。

我最喜欢的 super-easy 持久性数据库称为 pickleDB。它的工作方式类似于字典,但它会将所有内容存储在一个文件中,因此即使在重新启动程序后数据仍然存在。

使用 pip install pickleDB 安装它,然后在代码的顶部使用 import pickledb 导入它。 Create/load 在您的导入下使用 db = pickledb.load('discord.db', true) 数据库。第一部分是定义您想要的文件名,第二部分是设置自动转储。 Autodump 会自动将添加到数据库中的新内容保存在文件中,如果没有它,您每次写入数据库后都需要使用 db.dump() 以确保它被保存。现在,无论何时你想存储数据都使用 db.set(your_key, your_value),无论何时你想获取该数据都使用 db.get(your_key).

这是一个使用的例子:

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".

下面是一个示例,说明如果您改用 pickledb,您的代码段会是什么样子:

@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,因为它并未真正针对此进行优化,但对于您的用例而言,它似乎可以完美运行!

发表评论,如果您对此有任何疑问,请告诉我!