-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
2781 lines (2273 loc) · 96.3 KB
/
api.py
File metadata and controls
2781 lines (2273 loc) · 96.3 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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
from collections.abc import Sequence
from datetime import datetime
from typing import Any
# import asyncmy
from discord import Entitlement
from utility import get_level_for_xp, get_xp_for_level
# Remove global pool and set_pool functions
# The pool will be accessed from the bot object
_bot = None
def set_bot(bot) -> None:
global _bot
_bot = bot
def _get_pool():
if _bot and hasattr(_bot, "_pool") and _bot._pool is not None:
return _bot._pool
return None
async def execute_query(
query: str, params: Sequence[Any] | dict[str, Any] | None = None, bot=None
) -> list[tuple[Any, ...]] | None:
pool = _get_pool() if bot is None else (bot._pool if hasattr(bot, "_pool") else None)
if pool is None:
print(
"Tried to execute action without pool. Pool is not yet initialized.Returning...\nquery: ",
query,
)
return
try:
async with pool.acquire() as connection, connection.cursor() as cursor:
await cursor.execute(query, params)
result = await cursor.fetchall()
return result
except Exception as e:
print(f"An error occurred during query execution: {e}\nquery: {query}\nparams: {params}")
async def execute_action(query: str, params: Any = None, bot=None) -> Any:
pool = _get_pool() if bot is None else (bot._pool if hasattr(bot, "_pool") else None)
if pool is None:
print(
("Tried to execute action without pool. Pool is not yet initialized. Returning...\nquery: "),
query,
)
return
try:
async with pool.acquire() as connection, connection.cursor() as cursor:
await cursor.execute(query, params)
await connection.commit()
return cursor.rowcount
except Exception as e:
print(f"An error occurred during action execution: {e}\nquery: {query}\nparams: {params}")
async def execute_insert_and_get_id(query: str, params: Any = None, bot=None) -> int | None:
pool = _get_pool() if bot is None else (bot._pool if hasattr(bot, "_pool") else None)
if pool is None:
return None
try:
async with pool.acquire() as connection, connection.cursor() as cursor:
await cursor.execute(query, params)
await connection.commit()
await cursor.execute("SELECT LAST_INSERT_ID()")
last_id = await cursor.fetchone()
return last_id[0] if last_id else None
except Exception as e:
print(f"An error occurred during insert: {e}\nquery: {query}\nparams: {params}")
return None
async def create_tables(bot=None) -> None:
tables = {}
tables["warnings"] = (
"CREATE TABLE IF NOT EXISTS `warnings` ("
" `id` INT AUTO_INCREMENT PRIMARY KEY,"
" `guild_id` VARCHAR(20) NOT NULL,"
" `user_id` VARCHAR(20) NOT NULL,"
" `reason` VARCHAR(255),"
" `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,"
" `expires_at` TIMESTAMP NULL,"
" `created_by` VARCHAR(20) NOT NULL,"
" `escalation_level` INT DEFAULT 0"
") ENGINE=InnoDB"
)
tables["warn_config"] = (
"CREATE TABLE IF NOT EXISTS `warn_config` ("
" `guild_id` VARCHAR(20) PRIMARY KEY,"
" `expiration_days` INT DEFAULT 0,"
" `timeout_threshold` INT DEFAULT 0,"
" `timeout_duration` INT DEFAULT 0,"
" `kick_threshold` INT DEFAULT 0,"
" `ban_threshold` INT DEFAULT 0"
") ENGINE=InnoDB"
)
tables["channel_overwrites"] = (
"CREATE TABLE IF NOT EXISTS `channel_overwrites` ("
" `id` INT AUTO_INCREMENT PRIMARY KEY,"
" `channel_id` VARCHAR(20) NOT NULL,"
" `role_id` VARCHAR(20) NOT NULL,"
" `overwrites` JSON,"
" `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP"
") ENGINE=InnoDB"
)
tables["message_tracking_opt_out"] = (
"CREATE TABLE IF NOT EXISTS `message_tracking_opt_out` ( `user_id` VARCHAR(20) PRIMARY KEY) ENGINE=InnoDB"
)
tables["counting"] = (
"CREATE TABLE IF NOT EXISTS `counting` ("
" `channel_id` VARCHAR(20) PRIMARY KEY,"
" `progress` INT UNSIGNED DEFAULT 0,"
" `last_counter_id` VARCHAR(20) DEFAULT NULL,"
" `guild_id` VARCHAR(20)"
") ENGINE=InnoDB"
)
tables["counting_challenge"] = (
"CREATE TABLE IF NOT EXISTS `counting_challenge` ("
" `channel_id` VARCHAR(20) PRIMARY KEY,"
" `progress` INT UNSIGNED DEFAULT 0,"
" `last_counter_id` VARCHAR(20) DEFAULT NULL,"
" `guild_id` VARCHAR(20)"
") ENGINE=InnoDB"
)
tables["counting_modes"] = (
"CREATE TABLE IF NOT EXISTS `counting_modes` ("
" `channel_id` VARCHAR(20) PRIMARY KEY,"
" `progress` INT DEFAULT 0,"
" `mode` TINYINT UNSIGNED DEFAULT 0,"
" `goal` INT,"
" `last_counter_id` VARCHAR(20) DEFAULT NULL,"
" `guild_id` VARCHAR(20)"
") ENGINE=InnoDB"
)
tables["wordchain"] = (
"CREATE TABLE IF NOT EXISTS `wordchain` ("
" `channel_id` VARCHAR(20) PRIMARY KEY,"
" `word` VARCHAR(1028) DEFAULT NULL,"
" `last_user_id` VARCHAR(20) DEFAULT NULL,"
" `guild_id` VARCHAR(20)"
") ENGINE=InnoDB"
)
tables["level"] = (
"CREATE TABLE IF NOT EXISTS `level` ("
" `user_id` VARCHAR(20) NOT NULL,"
" `guild_id` VARCHAR(20) NOT NULL,"
" `xp` INT UNSIGNED DEFAULT 0,"
" `customBackground` VARCHAR(255) DEFAULT NULL,"
" `last_xp_gain` DATETIME DEFAULT NOW(),"
" `last_voice_xp_gain` DATETIME DEFAULT NOW(),"
" PRIMARY KEY(`user_id`, `guild_id`)"
") ENGINE=InnoDB"
)
tables["blacklistedUser"] = (
"CREATE TABLE IF NOT EXISTS `blacklistedUser` ("
" `user_id` VARCHAR(20) NOT NULL,"
" `guild_id` VARCHAR(20) NOT NULL,"
" `reason` VARCHAR(255) DEFAULT NULL,"
" `blacklisted_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,"
" PRIMARY KEY(`user_id`, `guild_id`)"
") ENGINE=InnoDB"
)
tables["blacklistedRole"] = (
"CREATE TABLE IF NOT EXISTS `blacklistedRole` ("
" `role_id` VARCHAR(20) NOT NULL,"
" `guild_id` VARCHAR(20) NOT NULL,"
" `reason` VARCHAR(255) DEFAULT NULL,"
" `blacklisted_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,"
" PRIMARY KEY(`role_id`, `guild_id`)"
") ENGINE=InnoDB"
)
tables["blacklistedChannel"] = (
"CREATE TABLE IF NOT EXISTS `blacklistedChannel` ("
" `channel_id` VARCHAR(20) NOT NULL,"
" `guild_id` VARCHAR(20) NOT NULL,"
" `reason` VARCHAR(255) DEFAULT NULL,"
" `blacklisted_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,"
" PRIMARY KEY(`channel_id`, `guild_id`)"
") ENGINE=InnoDB"
)
tables["userXpBoost"] = (
"CREATE TABLE IF NOT EXISTS `userXpBoost` ("
" `user_id` VARCHAR(20) NOT NULL,"
" `guild_id` VARCHAR(20) NOT NULL,"
" `boost` DECIMAL(4, 2) UNSIGNED DEFAULT 1,"
" `additive` TINYINT(1) DEFAULT 0,"
" `boosted_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,"
" PRIMARY KEY(`user_id`, `guild_id`)"
") ENGINE=InnoDB"
)
tables["roleXpBoost"] = (
"CREATE TABLE IF NOT EXISTS `roleXpBoost` ("
" `role_id` VARCHAR(20) NOT NULL,"
" `guild_id` VARCHAR(20) NOT NULL,"
" `boost` DECIMAL(4, 2) UNSIGNED DEFAULT 1,"
" `additive` TINYINT(1) DEFAULT 0,"
" `boosted_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,"
" PRIMARY KEY(`role_id`, `guild_id`)"
") ENGINE=InnoDB"
)
tables["channelXpBoost"] = (
"CREATE TABLE IF NOT EXISTS `channelXpBoost` ("
" `channel_id` VARCHAR(20) NOT NULL,"
" `guild_id` VARCHAR(20) NOT NULL,"
" `boost` DECIMAL(4, 2) UNSIGNED DEFAULT 1,"
" `additive` TINYINT(1) DEFAULT 0,"
" `boosted_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,"
" PRIMARY KEY(`channel_id`, `guild_id`)"
") ENGINE=InnoDB"
)
tables["levelRole"] = (
"CREATE TABLE IF NOT EXISTS `levelRole` ("
" `role_id` VARCHAR(20) NOT NULL,"
" `guild_id` VARCHAR(20) NOT NULL,"
" `level` INT UNSIGNED DEFAULT 0,"
" PRIMARY KEY(`role_id`, `guild_id`)"
") ENGINE=InnoDB"
)
tables["levelConfig"] = (
"CREATE TABLE IF NOT EXISTS `levelConfig` ("
" `guild_id` VARCHAR(20) PRIMARY KEY,"
" `difficulty` ENUM('easy', 'medium', 'hard', 'extreme', 'custom') "
"DEFAULT 'medium',"
" `customFormula` VARCHAR(255) DEFAULT NULL,"
" `levelUpMessageActive` TINYINT(1) DEFAULT 1,"
" `levelUpMessage` VARCHAR(1000) DEFAULT NULL,"
" `levelUpChannelId` VARCHAR(20) DEFAULT NULL,"
" `active` TINYINT(1) DEFAULT 1,"
" `textCooldown` INT DEFAULT 60,"
" `voiceCooldown` INT DEFAULT 60"
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;"
)
tables["giveaway"] = """
CREATE TABLE IF NOT EXISTS `giveaway` (
`giveawayId` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`guildId` VARCHAR(20) NOT NULL,
`title` VARCHAR(128) NOT NULL,
`description` VARCHAR(1024),
`winners` TINYINT(4) DEFAULT 1,
`withButton` TINYINT(1) DEFAULT 1,
`customName` VARCHAR(32),
`sponsor` VARCHAR(20),
`price` VARCHAR(64),
`message` VARCHAR(128),
`endtime` DATETIME NOT NULL,
`starttime` DATETIME,
`started` TINYINT(1) DEFAULT 0,
`ended` TINYINT(1) DEFAULT 0,
`newMessageRequirement` SMALLINT UNSIGNED,
`dayRequirement` SMALLINT UNSIGNED,
`voiceRequirement` SMALLINT UNSIGNED,
`sendFailed` TINYINT(1) DEFAULT 0,
`channelId` VARCHAR(20),
`messageId` VARCHAR(20) DEFAULT "pending",
`createdAt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;
"""
tables["giveawayChannelRequirement"] = """
CREATE TABLE IF NOT EXISTS `giveawayChannelRequirement` (
`giveawayId` INT UNSIGNED,
`channelId` VARCHAR(20),
`amount` SMALLINT UNSIGNED,
PRIMARY KEY(`giveawayId`, `channelId`)
) ENGINE=InnoDB;
"""
tables["giveawayParticipant"] = """
CREATE TABLE IF NOT EXISTS `giveawayParticipant` (
`userId` VARCHAR(20),
`giveawayId` INT UNSIGNED,
PRIMARY KEY(`userId`, `giveawayId`)
) ENGINE=InnoDB;
"""
tables["giveawayRoleRequirement"] = """
CREATE TABLE IF NOT EXISTS `giveawayRoleRequirement` (
`roleId` VARCHAR(20),
`giveawayId` INT UNSIGNED,
PRIMARY KEY(`roleId`, `giveawayId`)
) ENGINE=InnoDB;
"""
tables["giveawayVoiceTime"] = """
CREATE TABLE IF NOT EXISTS `giveawayVoiceTime` (
`giveawayId` INT UNSIGNED,
`userId` VARCHAR(20),
`voiceMinutes` MEDIUMINT UNSIGNED DEFAULT 0,
PRIMARY KEY(`giveawayId`, `userId`)
) ENGINE=InnoDB;
"""
tables["giveawayNewMessage"] = """
CREATE TABLE IF NOT EXISTS `giveawayNewMessage` (
`giveawayId` INT UNSIGNED,
`userId` VARCHAR(20),
`messages` MEDIUMINT UNSIGNED,
PRIMARY KEY(`giveawayId`, `userId`)
) ENGINE=InnoDB;
"""
tables["giveawayBlacklistedRole"] = """
CREATE TABLE IF NOT EXISTS `giveawayBlacklistedRole` (
`roleId` VARCHAR(20) PRIMARY KEY,
`guildId` VARCHAR(20),
`reason` VARCHAR(255) DEFAULT NULL
) ENGINE=InnoDB;
"""
tables["giveawayBlacklistedUser"] = """
CREATE TABLE IF NOT EXISTS `giveawayBlacklistedUser` (
`userId` VARCHAR(20),
`guildId` VARCHAR(20),
`reason` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY(`userId`, `guildId`)
) ENGINE=InnoDB;
"""
tables["giveawayChannelMessages"] = """
CREATE TABLE IF NOT EXISTS `giveawayChannelMessages` (
`giveawayId` INT UNSIGNED,
`channelId` VARCHAR(20),
`userId` VARCHAR(20),
`amount` MEDIUMINT UNSIGNED DEFAULT 0,
PRIMARY KEY(`giveawayId`, `channelId`, `userId`)
) ENGINE=InnoDB;
"""
tables["aiToken"] = """
CREATE TABLE IF NOT EXISTS `aiToken` (
`freeToken` SMALLINT UNSIGNED DEFAULT 500,
`plusToken` SMALLINT UNSIGNED DEFAULT 0,
`paidToken` INT UNSIGNED DEFAULT 0,
`usedToken` INT UNSIGNED DEFAULT 0,
`userId` VARCHAR(20) PRIMARY KEY
) ENGINE=InnoDB;
"""
tables["aiSituations"] = """
CREATE TABLE IF NOT EXISTS `aiSituations` (
`userId` VARCHAR(20) PRIMARY KEY,
`situation` VARCHAR(4000) DEFAULT NULL,
`name` VARCHAR(15) DEFAULT NULL,
`createdAt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`temperature` DECIMAL(3, 2) DEFAULT 1,
`top_p` DECIMAL(3, 2) DEFAULT 1,
`frequency_penalty` DECIMAL(3, 2) DEFAULT 0,
`presence_penalty` DECIMAL(3, 2) DEFAULT 0,
`unlocked` TINYINT(1) DEFAULT 0
) ENGINE=InnoDB;
"""
tables["autopublish"] = """
CREATE TABLE IF NOT EXISTS `autopublish` (
`channelId` VARCHAR(20) PRIMARY KEY
) ENGINE=InnoDB;
"""
tables["feedbackBlocked"] = """
CREATE TABLE IF NOT EXISTS `feedbackBlocked` (
`userId` VARCHAR(20) PRIMARY KEY
) ENGINE=InnoDB;
"""
tables["afkUsers"] = """
CREATE TABLE IF NOT EXISTS `afkUsers` (
`userId` VARCHAR(20) PRIMARY KEY,
`reason` VARCHAR(1024)
) ENGINE=InnoDB;
"""
tables["afkMessages"] = """
CREATE TABLE IF NOT EXISTS `afkMessages` (
`userId` VARCHAR(20),
`messageId` VARCHAR(20),
`channelId` VARCHAR(20),
PRIMARY KEY(`userId`, `messageId`)
) ENGINE=InnoDB;
"""
tables["boosterChannel"] = """
CREATE TABLE IF NOT EXISTS `boosterChannel` (
`guildId` VARCHAR(20),
`channelId` VARCHAR(20),
PRIMARY KEY(`guildId`, `channelId`)
) ENGINE=InnoDB;
"""
tables["claimedBoosterChannel"] = """
CREATE TABLE IF NOT EXISTS `claimedBoosterChannel` (
`userId` VARCHAR(20),
`channelId` VARCHAR(20),
`guildId` VARCHAR(20),
PRIMARY KEY(`userId`, `channelId`)
) ENGINE=InnoDB;
"""
tables["boosterRole"] = """
CREATE TABLE IF NOT EXISTS `boosterRole` (
`guildId` VARCHAR(20),
`roleId` VARCHAR(20),
PRIMARY KEY(`guildId`, `roleId`)
) ENGINE=InnoDB;
"""
tables["claimedBoosterRole"] = """
CREATE TABLE IF NOT EXISTS `claimedBoosterRole` (
`userId` VARCHAR(20),
`roleId` VARCHAR(20),
`guildId` VARCHAR(20),
PRIMARY KEY(`userId`, `roleId`)
) ENGINE=InnoDB;
"""
tables["logChannel"] = """
CREATE TABLE IF NOT EXISTS `logChannel` (
`guildId` VARCHAR(20),
`channelId` VARCHAR(20),
PRIMARY KEY(`guildId`, `channelId`)
) ENGINE=InnoDB;
"""
tables["logChannelBlacklist"] = """
CREATE TABLE IF NOT EXISTS `logChannelBlacklist` (
`guildId` VARCHAR(20),
`channelId` VARCHAR(20),
PRIMARY KEY(`guildId`, `channelId`)
) ENGINE=InnoDB;
"""
tables["logRoleBlacklist"] = """
CREATE TABLE IF NOT EXISTS `logRoleBlacklist` (
`guildId` VARCHAR(20),
`roleId` VARCHAR(20),
PRIMARY KEY(`guildId`, `roleId`)
) ENGINE=InnoDB;
"""
tables["logBlacklistChannel"] = """
CREATE TABLE IF NOT EXISTS `logBlacklistChannel` (
`guildId` VARCHAR(20),
`channelId` VARCHAR(20),
PRIMARY KEY(`guildId`, `channelId`)
) ENGINE=InnoDB;
"""
tables["logUserBlacklist"] = """
CREATE TABLE IF NOT EXISTS `logUserBlacklist` (
`guildId` VARCHAR(20),
`userId` VARCHAR(20),
PRIMARY KEY(`guildId`, `userId`)
) ENGINE=InnoDB;
"""
tables["logEnables"] = """
CREATE TABLE IF NOT EXISTS `logEnables` (
`guildId` VARCHAR(20),
`automodRuleCreate` TINYINT(1) DEFAULT 1,
`automodRuleUpdate` TINYINT(1) DEFAULT 1,
`automodRuleDelete` TINYINT(1) DEFAULT 1,
`automodAction` TINYINT(1) DEFAULT 0,
`guildChannelDelete` TINYINT(1) DEFAULT 1,
`guildChannelCreate` TINYINT(1) DEFAULT 1,
`guildChannelUpdate` TINYINT(1) DEFAULT 1,
`guildUpdate` TINYINT(1) DEFAULT 1,
`inviteCreate` TINYINT(1) DEFAULT 1,
`inviteDelete` TINYINT(1) DEFAULT 0,
`memberJoin` TINYINT(1) DEFAULT 1,
`memberLeave` TINYINT(1) DEFAULT 1,
`memberUpdate` TINYINT(1) DEFAULT 1,
`userUpdate` TINYINT(1) DEFAULT 1,
`memberBan` TINYINT(1) DEFAULT 1,
`memberUnban` TINYINT(1) DEFAULT 1,
`presenceUpdate` TINYINT(1) DEFAULT 1,
`messageEdit` TINYINT(1) DEFAULT 1,
`messageDelete` TINYINT(1) DEFAULT 1,
`reactionAdd` TINYINT(1) DEFAULT 0,
`reactionRemove` TINYINT(1) DEFAULT 0,
`guildRoleCreate` TINYINT(1) DEFAULT 1,
`guildRoleDelete` TINYINT(1) DEFAULT 1,
`guildRoleUpdate` TINYINT(1) DEFAULT 1,
PRIMARY KEY(`guildId`)
) ENGINE=InnoDB;
"""
tables["scheduledMessages"] = """
CREATE TABLE IF NOT EXISTS `scheduledMessages` (
`messageId` BIGINT PRIMARY KEY AUTO_INCREMENT,
`guildId` VARCHAR(20),
`channelId` VARCHAR(20),
`userId` VARCHAR(20) NOT NULL,
`content` VARCHAR(1024) NOT NULL,
`sendTime` DATETIME NOT NULL,
`repeatInterval` MEDIUMINT UNSIGNED,
`repeatAmount` MEDIUMINT UNSIGNED,
`createdAt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX `idx_sendtime` (sendTime),
INDEX `idx_user` (userId),
INDEX `idx_guild` (guildId)
) ENGINE=InnoDB;
"""
tables["reports"] = """
CREATE TABLE IF NOT EXISTS `reports` (
`id` INT AUTO_INCREMENT,
`guildId` VARCHAR(20),
`userId` VARCHAR(20),
`reporterId` VARCHAR(20),
`reason` VARCHAR(1024),
`createdAt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`accepted` TINYINT(1) DEFAULT 0,
`acceptedAt` TIMESTAMP DEFAULT NULL,
`acceptedBy` VARCHAR(20) DEFAULT NULL,
`resolved` TINYINT(1) DEFAULT 0,
`resolvedAt` TIMESTAMP DEFAULT NULL,
`resolvedBy` VARCHAR(20) DEFAULT NULL,
PRIMARY KEY(`id`)
) ENGINE=InnoDB;
"""
tables["blockedReporters"] = """
CREATE TABLE IF NOT EXISTS `blockedReporters` (
`guildId` VARCHAR(20),
`userId` VARCHAR(20),
PRIMARY KEY(`guildId`, `userId`)
) ENGINE=InnoDB;
"""
tables["reportchannel"] = """
CREATE TABLE IF NOT EXISTS `reportchannel` (
`guildId` VARCHAR(20),
`channelId` VARCHAR(20),
PRIMARY KEY(`guildId`, `channelId`)
) ENGINE=InnoDB;
"""
tables["triggerMessages"] = """
CREATE TABLE IF NOT EXISTS `triggerMessages` (
`id` INT AUTO_INCREMENT,
`guildId` VARCHAR(20),
`trigger` VARCHAR(128),
`response` VARCHAR(1024),
`caseSensitive` TINYINT(1) DEFAULT 0,
PRIMARY KEY(`id`),
INDEX `idx_guild` (`guildId`)
) ENGINE=InnoDB;
"""
tables["triggerMessagesChannel"] = """
CREATE TABLE IF NOT EXISTS `triggerMessagesChannel` (
`guildId` VARCHAR(20),
`channelId` VARCHAR(20),
`triggerId` INT,
PRIMARY KEY(`guildId`, `channelId`, `triggerId`),
FOREIGN KEY (`guildId`, `triggerId`)
REFERENCES `triggerMessages`(`guildId`, `id`)
ON DELETE CASCADE
) ENGINE=InnoDB;
"""
tables["ticketMessages"] = """
CREATE TABLE IF NOT EXISTS `ticketMessages` (
`id` INT AUTO_INCREMENT,
`guildId` VARCHAR(20),
`channelId` VARCHAR(20),
`introduction` VARCHAR(1024),
`pingRole` VARCHAR(20),
`name` VARCHAR(128),
`description` VARCHAR(1024),
`summaryChannelId` VARCHAR(20),
PRIMARY KEY(`id`),
INDEX `idx_guild` (`guildId`)
) ENGINE=InnoDB;
"""
tables["tickets"] = """
CREATE TABLE IF NOT EXISTS `tickets` (
`guildId` VARCHAR(20),
`openerId` VARCHAR(20),
`openedAt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`closed` TINYINT(1) DEFAULT 0,
`closedAt` TIMESTAMP DEFAULT NULL,
`closedBy` VARCHAR(20) DEFAULT NULL,
`channelId` VARCHAR(20),
`ticketMessageId` INT,
PRIMARY KEY(`guildId`, `channelId`, `ticketMessageId`),
FOREIGN KEY (`guildId`, `ticketMessageId`)
REFERENCES `ticketMessages`(`guildId`, `id`)
ON DELETE CASCADE
) ENGINE=InnoDB;
"""
tables["joinToCreateChannel"] = """
CREATE TABLE IF NOT EXISTS `joinToCreateChannel` (
`guildId` VARCHAR(20),
`channelId` VARCHAR(20),
PRIMARY KEY(`guildId`, `channelId`)
) ENGINE=InnoDB;
"""
tables["mediaChannel"] = """
CREATE TABLE IF NOT EXISTS `mediaChannel` (
`channelId` VARCHAR(20),
`guildId` VARCHAR(20),
PRIMARY KEY(`channelId`)
) ENGINE=InnoDB;
"""
tables["welcomeChannel"] = """
CREATE TABLE IF NOT EXISTS `welcomeChannel` (
`channelId` VARCHAR(20),
`guildId` VARCHAR(20),
`message` VARCHAR(1024) DEFAULT NULL,
`imageBackground` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY(`channelId`, `guildId`)
) ENGINE=InnoDB;
"""
tables["leaveChannel"] = """
CREATE TABLE IF NOT EXISTS `leaveChannel` (
`channelId` VARCHAR(20),
`guildId` VARCHAR(20),
`message` VARCHAR(1024) DEFAULT NULL,
`imageBackground` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY(`channelId`, `guildId`)
) ENGINE=InnoDB;
"""
tables["dynamicslowmode"] = """
CREATE TABLE IF NOT EXISTS `dynamicslowmode` (
`guildId` VARCHAR(20),
`channelId` VARCHAR(20),
`messages` INT,
`per` INT,
`resetafter` INT,
`cashedSlowmode` INT,
PRIMARY KEY(`channelId`)
) ENGINE=InnoDB;
"""
tables["dynamicslowmode_messages"] = """
CREATE TABLE IF NOT EXISTS `dynamicslowmode_messages` (
`id` INT AUTO_INCREMENT,
`channelId` VARCHAR(20),
`messageId` VARCHAR(20),
`sendTime` DATETIME,
PRIMARY KEY(`id`),
INDEX `idx_channel` (`channelId`),
INDEX `idx_message` (`messageId`),
INDEX `idx_sendtime` (`sendTime`),
FOREIGN KEY (`channelId`)
REFERENCES `dynamicslowmode`(`channelId`)
ON DELETE CASCADE
) ENGINE=InnoDB;
"""
tables["twitchOnlineNotification"] = """
CREATE TABLE IF NOT EXISTS `twitchOnlineNotification` (
`id` INT AUTO_INCREMENT,
`channelId` VARCHAR(20),
`guildId` VARCHAR(20),
`twitchUuid` VARCHAR(64),
`twitchName` VARCHAR(128),
`notificationMessage` VARCHAR(1024) DEFAULT NULL,
PRIMARY KEY(`id`),
INDEX `idx_channel` (`channelId`),
INDEX `idx_guild` (`guildId`)
) ENGINE=InnoDB;
"""
tables["brawlstarsLinkedAccounts"] = """
CREATE TABLE IF NOT EXISTS `brawlstarsLinkedAccounts` (
`userId` VARCHAR(20),
`brawlstarsTag` VARCHAR(20),
PRIMARY KEY(`userId`)
) ENGINE=InnoDB;
"""
pool = _get_pool() if bot is None else (bot._pool if hasattr(bot, "_pool") else None)
if pool is None:
return
async with pool.acquire() as conn, conn.cursor() as cursor:
await cursor.execute("SHOW TABLES")
existing = {row[0] for row in await cursor.fetchall()}
for table_name in tables:
if table_name in existing:
continue
table_query = tables[table_name]
await execute_action(table_query, bot=bot)
async def add_warning(
guild_id: str | int, user_id: str | int, reason: str, expiration_date: datetime, created_by: str | int
) -> None:
query = "INSERT INTO warnings (guild_id, user_id, reason, expires_at, created_by) VALUES (%s, %s, %s, %s, %s)"
params = (guild_id, user_id, reason, expiration_date, created_by)
await execute_action(query, params)
async def get_warnings(guild_id: str | int, user_id: str | int | None = None) -> list[tuple[Any, ...]] | None:
if user_id:
query = "SELECT * FROM warnings WHERE guild_id = %s AND user_id = %s AND (expires_at IS NULL OR expires_at > NOW())"
params = (guild_id, user_id)
result = await execute_query(query, params)
return result
else:
query = "SELECT * FROM warnings WHERE guild_id = %s AND (expires_at IS NULL OR expires_at > NOW())"
params = (guild_id,)
result = await execute_query(query, params)
return result
async def get_detailed_warnings(guild_id: str | int, user_id: str | int) -> list[tuple[Any, ...]] | None:
query = (
"SELECT id, reason, created_at, expires_at, created_by "
"FROM warnings WHERE guild_id = %s AND user_id = %s "
"ORDER BY created_at DESC"
)
params = (guild_id, user_id)
result = await execute_query(query, params)
if result is None:
return None
return [(row[0], row[1], row[2], row[3], row[4]) for row in result]
async def remove_warning(warning_id: int) -> None:
query = "DELETE FROM warnings WHERE id = %s"
params = (warning_id,)
await execute_action(query, params)
async def set_warn_config(
guild_id: str | int,
expiration_days: int,
timeout_threshold: int,
timeout_duration: int,
kick_threshold: int,
ban_threshold: int,
) -> None:
query = (
"INSERT INTO warn_config (guild_id, expiration_days, "
"timeout_threshold, timeout_duration, "
"kick_threshold, ban_threshold) "
"VALUES (%s, %s, %s, %s, %s, %s) "
"ON DUPLICATE KEY UPDATE "
"expiration_days = VALUES(expiration_days), "
"timeout_threshold = VALUES(timeout_threshold), "
"timeout_duration = VALUES(timeout_duration), "
"kick_threshold = VALUES(kick_threshold), "
"ban_threshold = VALUES(ban_threshold)"
)
params = (
guild_id,
expiration_days,
timeout_threshold,
timeout_duration,
kick_threshold,
ban_threshold,
)
await execute_action(query, params)
async def get_warn_config(guild_id: str | int) -> dict[str, Any] | None:
query = "SELECT * FROM warn_config WHERE guild_id = %s"
params = (guild_id,)
result = await execute_query(query, params)
if result:
(
_,
expiration_days,
timeout_threshold,
timeout_duration,
kick_threshold,
ban_threshold,
) = result[0]
return {
"expiration_days": expiration_days,
"timeout_threshold": timeout_threshold,
"timeout_duration": timeout_duration,
"kick_threshold": kick_threshold,
"ban_threshold": ban_threshold,
}
else:
return None
async def save_channel_overwrites(channel_id: str | int, role_id: str | int, overwrites: str) -> None:
query = "INSERT INTO channel_overwrites (channel_id, role_id, overwrites) VALUES (%s, %s, %s)"
params = (channel_id, role_id, json.dumps(overwrites))
await execute_action(query, params)
async def get_channel_overwrites(channel_id: str | int) -> dict[Any, Any]:
query = "SELECT role_id, overwrites FROM channel_overwrites WHERE channel_id = %s"
params = (channel_id,)
result = await execute_query(query, params)
if result is None:
return {}
return {row[0]: json.loads(row[1]) for row in result}
async def clear_channel_overwrites(channel_id: str | int) -> None:
query = "DELETE FROM channel_overwrites WHERE channel_id = %s"
params = (channel_id,)
await execute_action(query, params)
async def check_if_opted_out(user_id: str | int) -> bool:
query = "SELECT * FROM message_tracking_opt_out WHERE user_id = %s"
params = (user_id,)
result = await execute_query(query, params)
return result is not None and len(result) > 0
async def opt_out(user_id: str | int) -> None:
query = "INSERT INTO message_tracking_opt_out (user_id) VALUES (%s)"
params = (user_id,)
await execute_action(query, params)
async def opt_in(user_id: str | int) -> None:
query = "DELETE FROM message_tracking_opt_out WHERE user_id = %s"
params = (user_id,)
await execute_action(query, params)
async def set_counting_progress(channel_id: str | int, progress: int, guild_id: str | int) -> None:
query = "INSERT INTO counting (channel_id, progress, guild_id) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE progress = %s"
params = (channel_id, progress, guild_id, progress)
await execute_action(query, params)
async def get_counting_channel_amount(guild_id: str | int) -> int:
query = "SELECT COUNT(progress) FROM counting WHERE guild_id = %s"
params = (guild_id,)
result = await execute_query(query, params)
return len(result) if result is not None else 0
async def get_counting_progress(channel_id: str | int) -> Any:
query = "SELECT progress FROM counting WHERE channel_id = %s"
params = (channel_id,)
result = await execute_query(query, params)
return result[0][0] if result else None
async def increase_counting_progress(channel_id: str | int, last_counter_id: str | int) -> None:
query = "UPDATE counting SET progress = progress + 1, last_counter_id = %s WHERE channel_id = %s"
params = (last_counter_id, channel_id)
await execute_action(query, params)
async def get_last_counter_id(channel_id: str | int) -> str | None:
query = "SELECT last_counter_id FROM counting WHERE channel_id = %s"
params = (channel_id,)
result = await execute_query(query, params)
return result[0][0] if result else None
async def clear_counting(channel_id: str | int) -> None:
query = "DELETE FROM counting WHERE channel_id = %s"
params = (channel_id,)
await execute_action(query, params)
async def set_counting_challenge_progress(channel_id: str | int, progress: int) -> None:
query = "INSERT INTO counting_challenge (channel_id, progress) VALUES (%s, %s) ON DUPLICATE KEY UPDATE progress = %s"
params = (channel_id, progress, progress)
await execute_action(query, params)
async def get_counting_challenge_progress(channel_id: str | int) -> Any:
query = "SELECT progress FROM counting_challenge WHERE channel_id = %s"
params = (channel_id,)
result = await execute_query(query, params)
return result[0][0] if result else None
async def increase_counting_challenge_progress(channel_id: Any, last_counter_id: Any) -> None:
query = "UPDATE counting_challenge SET progress = progress + 1, last_counter_id = %s WHERE channel_id = %s"
params = (last_counter_id, channel_id)
await execute_action(query, params)
async def get_last_challenge_counter_id(channel_id: Any) -> Any:
query = "SELECT last_counter_id FROM counting_challenge WHERE channel_id = %s"
params = (channel_id,)
result = await execute_query(query, params)
return result[0][0] if result else None
async def clear_counting_challenge(channel_id: Any) -> None:
query = "DELETE FROM counting_challenge WHERE channel_id = %s"
params = (channel_id,)
await execute_action(query, params)
async def get_counting_challenge_channel_amount(guild_id: Any) -> int:
query = "SELECT COUNT(progress) FROM counting_challenge WHERE guild_id = %s"
params = (guild_id,)
result = await execute_query(query, params)
return len(result) if result is not None else 0
async def set_counting_mode(channel_id: Any, progress: Any, mode: Any, guild_id: Any) -> None:
query = "INSERT INTO counting_modes (channel_id, progress, mode, guild_id) VALUES (%s, %s, %s, %s) ON DUPLICATE KEY UPDATE progress = VALUES(progress), mode = VALUES(mode)"
params = (channel_id, progress, mode, guild_id)
await execute_action(query, params)
async def get_counting_mode_progress(channel_id: Any) -> Any:
query = "SELECT progress FROM counting_modes WHERE channel_id = %s"
params = (channel_id,)
result = await execute_query(query, params)
return result[0][0] if result else None
async def get_last_mode_counter_id(channel_id: Any) -> Any:
query = "SELECT last_counter_id FROM counting_modes WHERE channel_id = %s"
params = (channel_id,)
result = await execute_query(query, params)
return result[0][0] if result else None
async def clear_counting_mode(channel_id: Any) -> None:
query = "DELETE FROM counting_modes WHERE channel_id = %s"
params = (channel_id,)
await execute_action(query, params)
async def get_counting_mode_mode(channel_id: Any) -> Any:
query = "SELECT mode FROM counting_modes WHERE channel_id = %s"
params = (channel_id,)
result = await execute_query(query, params)
return result[0][0] if result else None
async def set_counting_mode_progress(
channel_id: Any, progress: Any, guild_id: Any, mode: Any, goal: Any, counter_id: Any
) -> None:
query = "INSERT INTO counting_modes (channel_id, progress, guild_id, mode, goal, last_counter_id) VALUES (%s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE progress = %s, last_counter_id = %s"
params = (
channel_id,
progress,
guild_id,
mode,
goal,
counter_id,
progress,
counter_id,
)
await execute_action(query, params)
async def get_count_mode_goal(channel_id: Any) -> Any:
query = "SELECT goal FROM counting_modes WHERE channel_id = %s"
params = (channel_id,)
result = await execute_query(query, params)
return result[0][0] if result else None
async def get_wordchain_word(channel_id: Any) -> Any:
query = "SELECT word FROM wordchain WHERE channel_id = %s"
params = (channel_id,)
result = await execute_query(query, params)
return result[0][0] if result else None
async def set_wordchain_word(channel_id: Any, word: Any, guild_id: Any, worder_id: Any) -> None:
query = "INSERT INTO wordchain (channel_id, word, last_user_id, guild_id) VALUES (%s, %s, %s, %s) ON DUPLICATE KEY UPDATE word = %s, last_user_id = %s"
params = (channel_id, word, worder_id, guild_id, word, worder_id)
await execute_action(query, params)
async def get_wordchain_last_user_id(channel_id: Any) -> Any:
query = "SELECT last_user_id FROM wordchain WHERE channel_id = %s"
params = (channel_id,)
result = await execute_query(query, params)
return result[0][0] if result else None
async def clear_wordchain(channel_id: Any) -> None:
query = "DELETE FROM wordchain WHERE channel_id = %s"
params = (channel_id,)
await execute_action(query, params)
async def set_level_system_status(guild_id: str, active: bool) -> None:
query = """
INSERT INTO levelConfig (guild_id, active)
VALUES (%s, %s)
ON DUPLICATE KEY UPDATE active = VALUES(active)
"""
params = (guild_id, active)
await execute_action(query, params)
async def get_level_system_status(guild_id: str) -> bool:
query = "SELECT active FROM levelConfig WHERE guild_id = %s"
params = (guild_id,)
result = await execute_query(query, params)
return result[0][0] if result else True
async def delete_level_system_data(guild_id: str) -> None:
tables = [
"level",
"blacklistedUser",
"blacklistedRole",
"blacklistedChannel",
"userXpBoost",
"roleXpBoost",
"channelXpBoost",
"levelRole",
"levelConfig",
]
for table in tables:
query = f"DELETE FROM {table} WHERE guild_id = %s"
params = (guild_id,)
await execute_action(query, params)
async def set_levelup_message_status(guild_id: str, status: bool) -> None:
query = """
INSERT INTO levelConfig (guild_id, levelUpMessageActive)
VALUES (%s, %s)
ON DUPLICATE KEY UPDATE levelUpMessageActive = VALUES(levelUpMessageActive)
"""
params = (guild_id, status)
await execute_action(query, params)