You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
kemoverse/bot/db_utils.py

58 lines
1.6 KiB

import sqlite3
import random
import config
DB_PATH = config.DB_PATH
def get_db_connection():
'''Creates a connection to the database'''
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
def get_or_create_user(username):
'''Retrieves an ID for a given user, if the user does not exist, it will be
created.'''
conn = get_db_connection()
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute('SELECT id FROM users WHERE username = ?', (username,))
user = cur.fetchone()
if user:
conn.close()
return user[0]
# New user starts with has_rolled = False
cur.execute(
'INSERT INTO users (username, has_rolled) VALUES (?, ?)',
(username, False)
)
conn.commit()
user_id = cur.lastrowid
conn.close()
return user_id
def add_pull(user_id, character_id):
'''Creates a pull in the database'''
conn = get_db_connection()
cur = conn.cursor()
cur.execute('INSERT INTO pulls (user_id, character_id) VALUES (?, ?)', (user_id, character_id))
conn.commit()
conn.close()
def get_config(key):
'''Reads the value for a specified config key from the db'''
conn = get_db_connection()
cur = conn.cursor()
cur.execute("SELECT value FROM config WHERE key = ?", (key,))
row = cur.fetchone()
conn.close()
return row[0] if row else None
def set_config(key, value):
'''Writes the value for a specified config key to the db'''
conn = get_db_connection()
cur = conn.cursor()
cur.execute("INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)", (key, value))
conn.commit()
conn.close()