不和谐机器人可以存储信息的地方在哪里[discord.py]
问题描述
我对 python 并不陌生,但对 discord.py 并不陌生.我试图通过 discord.py 手册,但没有找到可以在 discord 机器人上存储一些临时变量的位置.
I am not too new to python but new to discord.py. I have tried to go through the discord.py manual but did not find where I can store some temporary variable on a discord bot.
discord.py 手册:http://discordpy.readthedocs.io/en/最新/api.html
discord.py manual: http://discordpy.readthedocs.io/en/latest/api.html
例如,在 PHP SESSION 中,我们可以在 SESSION() 中存储信息.discord.py 有同样的东西吗?
For example, in PHP SESSION, we can store information on the SESSION(). Did discord.py has the same kind of things?
例如,如果我们有用户A"和用户B".A"将存储为A_Object"的对象,例如消息等.与B_Object"类似,但与A_Object"不同.在discord.py中,有没有这样的函数?
For example, if we have user "A" and user "B". "A" will be stored as an object of "A_Object", such as messages etc. Similar for "B_Object" but will be different from "A_Object". In discord.py, is there a function like that?
非常感谢您的帮助!
解决方案
可以使用sqlite数据库.在你的定义里面写:
You can use sqlite database. Write inside your def:
# define database
import sqlite3
conn = sqlite3.connect("my_database.db")
cursor = conn.cursor()
# get stored object from database
sql = "SELECT * FROM my_table WHERE field_1=?"
cursor.execute(sql, [(value_1)])
data = cursor.fetchall()
# if object does not exist, create it
if len(data) == 0:
sql = "INSERT INTO my_table VALUES (?, ?)"
cursor.execute(sql, [(value_1), (value_2)])
# if stored object exist and we need update it
elif ...:
sql = "UPDATE my_table SET field_2 = ? WHERE field_1 = ?"
cursor.execute(sql, [(value_2), (value_1)])
else:
# get data from first object
value_of_field_1 = data[0][0]
# get data from third object
value_of_field_2 = data[2][1]
# close database connection
conn.commit()
conn.close()
my_database.db - 是一个 sqlite db 文件,应该与 bot 的 .py 文件存储在同一文件夹中.
my_database.db - is a sqlite db file and should be stored in sa same folder with bot's .py file.
相关文章