-
Notifications
You must be signed in to change notification settings - Fork 919
Expand file tree
/
Copy pathdatabase_mysql.py
More file actions
550 lines (474 loc) · 17.5 KB
/
database_mysql.py
File metadata and controls
550 lines (474 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
"""MySQL 数据库实现
使用提供的MySQL服务器进行数据存储
"""
import logging
from datetime import datetime, timedelta
from typing import Optional, Dict, List
import pymysql
from pymysql.cursors import DictCursor
from dotenv import load_dotenv
# 加载环境变量
load_dotenv()
logger = logging.getLogger(__name__)
class MySQLDatabase:
"""MySQL 数据库管理类"""
def __init__(self):
"""初始化数据库连接"""
import os
# 从环境变量读取配置(推荐)或使用默认值
self.config = {
'host': os.getenv('MYSQL_HOST', 'localhost'),
'port': int(os.getenv('MYSQL_PORT', 3306)),
'user': os.getenv('MYSQL_USER', 'tgbot_user'),
'password': os.getenv('MYSQL_PASSWORD', 'your_password_here'),
'database': os.getenv('MYSQL_DATABASE', 'tgbot_verify'),
'charset': 'utf8mb4',
'autocommit': False,
}
logger.info(f"MySQL 数据库初始化: {self.config['user']}@{self.config['host']}/{self.config['database']}")
self.init_database()
def get_connection(self):
"""获取数据库连接"""
return pymysql.connect(**self.config)
def init_database(self):
"""初始化数据库表结构"""
conn = self.get_connection()
cursor = conn.cursor()
try:
# 用户表
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS users (
user_id BIGINT PRIMARY KEY,
username VARCHAR(255),
full_name VARCHAR(255),
balance INT DEFAULT 1,
is_blocked TINYINT(1) DEFAULT 0,
invited_by BIGINT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
last_checkin DATETIME NULL,
INDEX idx_username (username),
INDEX idx_invited_by (invited_by)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
"""
)
# 邀请记录表
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS invitations (
id INT AUTO_INCREMENT PRIMARY KEY,
inviter_id BIGINT NOT NULL,
invitee_id BIGINT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX idx_inviter (inviter_id),
INDEX idx_invitee (invitee_id),
FOREIGN KEY (inviter_id) REFERENCES users(user_id),
FOREIGN KEY (invitee_id) REFERENCES users(user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
"""
)
# 验证记录表
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS verifications (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT NOT NULL,
verification_type VARCHAR(50) NOT NULL,
verification_url TEXT,
verification_id VARCHAR(255),
status VARCHAR(50) NOT NULL,
result TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX idx_user_id (user_id),
INDEX idx_type (verification_type),
INDEX idx_created (created_at),
FOREIGN KEY (user_id) REFERENCES users(user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
"""
)
# 卡密表
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS card_keys (
id INT AUTO_INCREMENT PRIMARY KEY,
key_code VARCHAR(100) UNIQUE NOT NULL,
balance INT NOT NULL,
max_uses INT DEFAULT 1,
current_uses INT DEFAULT 0,
expire_at DATETIME NULL,
created_by BIGINT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX idx_key_code (key_code),
INDEX idx_created_by (created_by)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
"""
)
# 卡密使用记录
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS card_key_usage (
id INT AUTO_INCREMENT PRIMARY KEY,
key_code VARCHAR(100) NOT NULL,
user_id BIGINT NOT NULL,
used_at DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX idx_key_code (key_code),
INDEX idx_user_id (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
"""
)
conn.commit()
logger.info("MySQL 数据库表初始化完成")
except Exception as e:
logger.error(f"初始化数据库失败: {e}")
conn.rollback()
raise
finally:
cursor.close()
conn.close()
def create_user(
self, user_id: int, username: str, full_name: str, invited_by: Optional[int] = None
) -> bool:
"""创建新用户"""
conn = self.get_connection()
cursor = conn.cursor()
try:
cursor.execute(
"""
INSERT INTO users (user_id, username, full_name, invited_by, created_at)
VALUES (%s, %s, %s, %s, NOW())
""",
(user_id, username, full_name, invited_by),
)
if invited_by:
cursor.execute(
"UPDATE users SET balance = balance + 2 WHERE user_id = %s",
(invited_by,),
)
cursor.execute(
"""
INSERT INTO invitations (inviter_id, invitee_id, created_at)
VALUES (%s, %s, NOW())
""",
(invited_by, user_id),
)
conn.commit()
return True
except pymysql.err.IntegrityError:
conn.rollback()
return False
except Exception as e:
logger.error(f"创建用户失败: {e}")
conn.rollback()
return False
finally:
cursor.close()
conn.close()
def get_user(self, user_id: int) -> Optional[Dict]:
"""获取用户信息"""
conn = self.get_connection()
cursor = conn.cursor(DictCursor)
try:
cursor.execute("SELECT * FROM users WHERE user_id = %s", (user_id,))
row = cursor.fetchone()
if row:
# 创建新字典并转换datetime为ISO格式字符串
result = dict(row)
if result.get('created_at'):
result['created_at'] = result['created_at'].isoformat()
if result.get('last_checkin'):
result['last_checkin'] = result['last_checkin'].isoformat()
return result
return None
finally:
cursor.close()
conn.close()
def user_exists(self, user_id: int) -> bool:
"""检查用户是否存在"""
return self.get_user(user_id) is not None
def is_user_blocked(self, user_id: int) -> bool:
"""检查用户是否被拉黑"""
user = self.get_user(user_id)
return user and user["is_blocked"] == 1
def block_user(self, user_id: int) -> bool:
"""拉黑用户"""
conn = self.get_connection()
cursor = conn.cursor()
try:
cursor.execute("UPDATE users SET is_blocked = 1 WHERE user_id = %s", (user_id,))
conn.commit()
return True
except Exception as e:
logger.error(f"拉黑用户失败: {e}")
conn.rollback()
return False
finally:
cursor.close()
conn.close()
def unblock_user(self, user_id: int) -> bool:
"""取消拉黑用户"""
conn = self.get_connection()
cursor = conn.cursor()
try:
cursor.execute("UPDATE users SET is_blocked = 0 WHERE user_id = %s", (user_id,))
conn.commit()
return True
except Exception as e:
logger.error(f"取消拉黑失败: {e}")
conn.rollback()
return False
finally:
cursor.close()
conn.close()
def get_blacklist(self) -> List[Dict]:
"""获取黑名单列表"""
conn = self.get_connection()
cursor = conn.cursor(DictCursor)
try:
cursor.execute("SELECT * FROM users WHERE is_blocked = 1")
return list(cursor.fetchall())
finally:
cursor.close()
conn.close()
def add_balance(self, user_id: int, amount: int) -> bool:
"""增加用户积分"""
conn = self.get_connection()
cursor = conn.cursor()
try:
cursor.execute(
"UPDATE users SET balance = balance + %s WHERE user_id = %s",
(amount, user_id),
)
conn.commit()
return True
except Exception as e:
logger.error(f"增加积分失败: {e}")
conn.rollback()
return False
finally:
cursor.close()
conn.close()
def deduct_balance(self, user_id: int, amount: int) -> bool:
"""扣除用户积分"""
user = self.get_user(user_id)
if not user or user["balance"] < amount:
return False
conn = self.get_connection()
cursor = conn.cursor()
try:
cursor.execute(
"UPDATE users SET balance = balance - %s WHERE user_id = %s",
(amount, user_id),
)
conn.commit()
return True
except Exception as e:
logger.error(f"扣除积分失败: {e}")
conn.rollback()
return False
finally:
cursor.close()
conn.close()
def can_checkin(self, user_id: int) -> bool:
"""检查用户今天是否可以签到"""
user = self.get_user(user_id)
if not user:
return False
last_checkin = user.get("last_checkin")
if not last_checkin:
return True
last_date = datetime.fromisoformat(last_checkin).date()
today = datetime.now().date()
return last_date < today
def checkin(self, user_id: int) -> bool:
"""用户签到(修复无限签到bug)"""
conn = self.get_connection()
cursor = conn.cursor()
try:
# 使用SQL原子操作,避免竞态条件
# 只有当 last_checkin 是NULL 或者日期 < 今天时才更新
cursor.execute(
"""
UPDATE users
SET balance = balance + 1, last_checkin = NOW()
WHERE user_id = %s
AND (
last_checkin IS NULL
OR DATE(last_checkin) < CURDATE()
)
""",
(user_id,),
)
conn.commit()
# 检查是否真的更新了(affected_rows > 0 表示签到成功)
success = cursor.rowcount > 0
return success
except Exception as e:
logger.error(f"签到失败: {e}")
conn.rollback()
return False
finally:
cursor.close()
conn.close()
def add_verification(
self, user_id: int, verification_type: str, verification_url: str,
status: str, result: str = "", verification_id: str = ""
) -> bool:
"""添加验证记录"""
conn = self.get_connection()
cursor = conn.cursor()
try:
cursor.execute(
"""
INSERT INTO verifications
(user_id, verification_type, verification_url, verification_id, status, result, created_at)
VALUES (%s, %s, %s, %s, %s, %s, NOW())
""",
(user_id, verification_type, verification_url, verification_id, status, result),
)
conn.commit()
return True
except Exception as e:
logger.error(f"添加验证记录失败: {e}")
conn.rollback()
return False
finally:
cursor.close()
conn.close()
def get_user_verifications(self, user_id: int) -> List[Dict]:
"""获取用户的验证记录"""
conn = self.get_connection()
cursor = conn.cursor(DictCursor)
try:
cursor.execute(
"""
SELECT * FROM verifications
WHERE user_id = %s
ORDER BY created_at DESC
""",
(user_id,),
)
return list(cursor.fetchall())
finally:
cursor.close()
conn.close()
def create_card_key(
self, key_code: str, balance: int, created_by: int,
max_uses: int = 1, expire_days: Optional[int] = None
) -> bool:
"""创建卡密"""
conn = self.get_connection()
cursor = conn.cursor()
try:
expire_at = None
if expire_days:
expire_at = datetime.now() + timedelta(days=expire_days)
cursor.execute(
"""
INSERT INTO card_keys (key_code, balance, max_uses, created_by, created_at, expire_at)
VALUES (%s, %s, %s, %s, NOW(), %s)
""",
(key_code, balance, max_uses, created_by, expire_at),
)
conn.commit()
return True
except pymysql.err.IntegrityError:
logger.error(f"卡密已存在: {key_code}")
conn.rollback()
return False
except Exception as e:
logger.error(f"创建卡密失败: {e}")
conn.rollback()
return False
finally:
cursor.close()
conn.close()
def use_card_key(self, key_code: str, user_id: int) -> Optional[int]:
"""使用卡密,返回获得的积分数量"""
conn = self.get_connection()
cursor = conn.cursor(DictCursor)
try:
# 查询卡密
cursor.execute(
"SELECT * FROM card_keys WHERE key_code = %s",
(key_code,),
)
card = cursor.fetchone()
if not card:
return None
# 检查是否过期
if card["expire_at"] and datetime.now() > card["expire_at"]:
return -2
# 检查使用次数
if card["current_uses"] >= card["max_uses"]:
return -1
# 检查用户是否已使用过此卡密
cursor.execute(
"SELECT COUNT(*) as count FROM card_key_usage WHERE key_code = %s AND user_id = %s",
(key_code, user_id),
)
count = cursor.fetchone()
if count['count'] > 0:
return -3
# 更新使用次数
cursor.execute(
"UPDATE card_keys SET current_uses = current_uses + 1 WHERE key_code = %s",
(key_code,),
)
# 记录使用记录
cursor.execute(
"INSERT INTO card_key_usage (key_code, user_id, used_at) VALUES (%s, %s, NOW())",
(key_code, user_id),
)
# 增加用户积分
cursor.execute(
"UPDATE users SET balance = balance + %s WHERE user_id = %s",
(card["balance"], user_id),
)
conn.commit()
return card["balance"]
except Exception as e:
logger.error(f"使用卡密失败: {e}")
conn.rollback()
return None
finally:
cursor.close()
conn.close()
def get_card_key_info(self, key_code: str) -> Optional[Dict]:
"""获取卡密信息"""
conn = self.get_connection()
cursor = conn.cursor(DictCursor)
try:
cursor.execute("SELECT * FROM card_keys WHERE key_code = %s", (key_code,))
return cursor.fetchone()
finally:
cursor.close()
conn.close()
def get_all_card_keys(self, created_by: Optional[int] = None) -> List[Dict]:
"""获取所有卡密(可按创建者筛选)"""
conn = self.get_connection()
cursor = conn.cursor(DictCursor)
try:
if created_by:
cursor.execute(
"SELECT * FROM card_keys WHERE created_by = %s ORDER BY created_at DESC",
(created_by,),
)
else:
cursor.execute("SELECT * FROM card_keys ORDER BY created_at DESC")
return list(cursor.fetchall())
finally:
cursor.close()
conn.close()
def get_all_user_ids(self) -> List[int]:
"""获取所有用户ID"""
conn = self.get_connection()
cursor = conn.cursor()
try:
cursor.execute("SELECT user_id FROM users")
rows = cursor.fetchall()
return [row[0] for row in rows]
finally:
cursor.close()
conn.close()
# 创建全局实例的别名,保持与SQLite版本的兼容性
Database = MySQLDatabase