· 5 years ago · Aug 30, 2020, 02:50 PM
1# -*- coding: utf-8 -*-
2
3import sqlite3
4
5__all__ = ('db',)
6
7
8class SQLighter:
9
10 def __init__(self, database="bot.db"):
11 """Подключаемся к БД и сохраняем курсор соединения"""
12 self.connection = sqlite3.connect(database)
13 self.cursor = self.connection.cursor()
14
15 def create_table_user(self):
16 """Создание таблицы `user`"""
17 with self.connection:
18 self.cursor.execute("""
19 CREATE TABLE IF NOT EXISTS `user`(
20 `id` Integer primary key autoincrement,
21 `user_id` Integer NOT NULL unique,
22 `username` Varchar(30) NOT NULL unique,
23 `xp` Integer default 0,
24 `money` Integer default 0,
25 `role` Integer not null
26 `is_ban` Bool not null
27 """)
28
29 """
30 role - 1 = Админ
31 role - 2 = Гражданин
32 role - 3 = Гость
33 """
34
35 def add_user(self, user_id: int, username: str):
36 """Добавляем пользователя в бд"""
37 with self.connection:
38 self.cursor.execute(f"INSERT INTO `user`(user_id, username) VALUES({user_id}, {username})")
39
40 def delete_user(self, user_id: int):
41 """Удаление пользователя из бд"""
42 with self.connection:
43 self.cursor.execute(f"DELETE FROM `user` WHERE user_id={user_id}")
44
45 def set_user_is_ban(self, user_id: int, is_ban: bool):
46 """True - пользователь забанен, и не сможет получить доступ к боту"""
47 with self.connection:
48 self.cursor.execute(f"UPDATE `user` SET is_ban={is_ban} WHERE user_id={user_id}")
49
50 def set_user_money(self, user_id: int, money: int):
51 """Устанавливаем значения денег"""
52 with self.connection:
53 self.cursor.execute(f"UPDATE `user` SET money={money} WHERE user_id={user_id}")
54
55 def get_user(self, user_id: int) -> tuple:
56 """:return tuple
57 Возвращает информцию с пользователя
58 """
59 with self.connection:
60 return self.cursor.execute(f"SELECT `user` FROM * WHERE user_id={user_id}").fetchone()
61
62 def set_user_role(self, user_id: int, role: int = 3):
63 """Устанавливает role пользователя"""
64 with self.connection:
65 self.cursor.execute(f"UPDATE `user` SET role={role} WHERE user_id={user_id}")
66
67 def set_user_xp(self, user_id: int, xp: int):
68 with self.connection:
69 self.cursor.execute(f"UPDATE `user` SET xp={xp} WHERE user_id={user_id}")
70
71 def close(self):
72 """Закрываем соединение с БД"""
73 self.connection.close()
74
75
76db = SQLighter()
77
78if __name__ == '__main__':
79 db.create_table_user()
80