lite.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # sqlite db functionality
  2. import sqlite3 as lite
  3. class SqliteDB:
  4. def __init__(self, bot=None):
  5. self.bot = bot
  6. self._prepare_database()
  7. self.con.close()
  8. def _prepare_database(self, create_string=None):
  9. self._open()
  10. if create_string:
  11. self.cur.execute(create_string)
  12. self.cur.execute('CREATE TABLE IF NOT EXISTS admins (id INTEGER PRIMARY KEY AUTOINCREMENT, username CHAR(32) DEFAULT NULL UNIQUE)')
  13. self.cur.execute('CREATE TABLE IF NOT EXISTS img (id INTEGER PRIMARY KEY, url CHAR(128) DEFAULT NULL, user CHAR(32) DEFAULT NULL, time DATETIME DEFAULT CURRENT_TIMESTAMP, channel CHAR(32) DEFAULT NULL)')
  14. self.cur.execute('CREATE TABLE IF NOT EXISTS lastfm (lastfm_username CHAR(64) NOT NULL, nick CHAR(32) NOT NULL)')
  15. self.cur.execute('CREATE TABLE IF NOT EXISTS qdb (id INTEGER PRIMARY KEY, quote TEXT NOT NULL, date DATETIME DEFAULT CURRENT_TIMESTAMP)')
  16. self.cur.execute('CREATE TABLE IF NOT EXISTS qdb_votes (vote_id PRIMARY KEY, quote_id INTEGER NOT NULL, votes INTEGER DEFAULT 0)')
  17. def _open(self):
  18. # perhaps TODO
  19. self.con = lite.connect(self.bot.conf.getNick(self.bot.network) + ".db", check_same_thread=False)
  20. self.cur = self.con.cursor()
  21. def e(self, sql):
  22. try:
  23. self._open()
  24. self.cur.execute(sql)
  25. if "INSERT" in sql or "REPLACE" in sql:
  26. self.con.commit()
  27. self.con.close()
  28. elif "SELECT" in sql:
  29. e = self.cur.fetchall()
  30. self.con.close()
  31. return e
  32. except Exception as e:
  33. print(e)
  34. self.con.rollback()
  35. self.con.close()
  36. return None
  37. def insertImg(self, user, url, channel):
  38. self._open()
  39. if user == "" or user == None:
  40. user = "nobody"
  41. self.cur.execute("INSERT INTO img (user, url, channel) VALUES (?, ?, ?)", (user, url, channel))
  42. self.con.commit()
  43. self.con.close()
  44. def getImgs(self):
  45. self._open()
  46. try:
  47. self.cur.execute("SELECT * FROM img ORDER BY time DESC")
  48. data = self.cur.fetchall()
  49. self.con.close()
  50. except:
  51. self.con.close()
  52. return None
  53. return data
  54. def isAdmin(self, username):
  55. self._open()
  56. try:
  57. self.cur.execute("SELECT * FROM admins WHERE username = ?",(username,))
  58. data = self.cur.fetchall()
  59. self.con.close()
  60. except Exception as e:
  61. self.con.close()
  62. return None
  63. return data