-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
2101 lines (1857 loc) · 87.2 KB
/
bot.py
File metadata and controls
2101 lines (1857 loc) · 87.2 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 requests
import discord
from discord import app_commands
from discord.ext import commands
import asyncio
import re
import random
from datetime import datetime, timedelta, timezone
import sqlite3
from sqlite3 import Error
import math
import time
import os
import requests.exceptions
import colorama
from colorama import Fore, Style
import pyfiglet
# Colorama'yı başlat
colorama.init()
# ASCII başlık oluştur
print("\033[36m" + r"""
███╗ ███╗ ██████╗ ██████╗ ██╗ ██╗██╗ ██╗ ██╗███████╗
████╗ ████║██╔═══██╗██╔══██╗██║ ██║██║ ██║ ██║██╔════╝
██╔████╔██║██║ ██║██║ ██║██║ ██║██║ ██║ ██║███████╗
██║╚██╔╝██║██║ ██║██║ ██║██║ ██║██║ ██║ ██║╚════██║
██║ ╚═╝ ██║╚██████╔╝██████╔╝╚██████╔╝███████╗╚██████╔╝███████║
╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝ ╚═════╝ ╚══════╝
by newt""")
# Token alma
token = input(Fore.GREEN + "Bot tokeninizi giriniz: " + Style.RESET_ALL)
# Owner ID'leri alma
owner_input = input(Fore.GREEN + "Owner ID giriniz birden fazla olacak ise virgülle ayırabilirsiniz.: " + Style.RESET_ALL)
OWNER_IDS = [int(x.strip()) for x in owner_input.split(",") if x.strip().isdigit()]
intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
intents.guilds = True
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
tree = bot.tree
# Çift loglamayı önlemek için global set
deleted_messages = set()
@bot.check
async def global_owner_check(ctx):
return ctx.author.id in OWNER_IDS
# --- SQL Veritabanı Ayarları ---
def create_connection():
try:
return sqlite3.connect('newtDATA.db')
except Error as e:
print(f"{Fore.RED}Veritabanı bağlantı hatası: {e}{Style.RESET_ALL}")
return None
def initialize_database():
commands = [
"""CREATE TABLE IF NOT EXISTS warnings (
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
count INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (guild_id, user_id)
);""",
"""CREATE TABLE IF NOT EXISTS log_channels (
guild_id INTEGER PRIMARY KEY,
channel_id INTEGER NOT NULL
);""",
"""CREATE TABLE IF NOT EXISTS autoroles (
guild_id INTEGER PRIMARY KEY,
role_id INTEGER NOT NULL
);""",
"""CREATE TABLE IF NOT EXISTS immune_users (
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
PRIMARY KEY (guild_id, user_id)
);""",
"""CREATE TABLE IF NOT EXISTS suggestions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
suggestion TEXT NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);""",
"""CREATE TABLE IF NOT EXISTS mod_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
action TEXT NOT NULL,
moderator_id INTEGER NOT NULL,
reason TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);""",
"""CREATE TABLE IF NOT EXISTS level_config (
guild_id INTEGER PRIMARY KEY,
role5_id INTEGER,
role15_id INTEGER,
role25_id INTEGER,
announcement_channels TEXT,
log_channel_id INTEGER
);""",
"""CREATE TABLE IF NOT EXISTS user_levels (
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
xp INTEGER NOT NULL DEFAULT 0,
level INTEGER NOT NULL DEFAULT 0,
last_message_time REAL,
PRIMARY KEY (guild_id, user_id)
);""",
"""CREATE TABLE IF NOT EXISTS language_roles (
guild_id INTEGER PRIMARY KEY,
role_tr INTEGER,
role_en INTEGER,
role_other INTEGER
);""",
"""CREATE TABLE IF NOT EXISTS message_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
channel_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
message_id INTEGER NOT NULL,
content TEXT NOT NULL,
attachments TEXT,
is_deleted BOOLEAN DEFAULT 0,
is_edited BOOLEAN DEFAULT 0,
moderator_id INTEGER,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);""",
"""CREATE TABLE IF NOT EXISTS server_config (
guild_id INTEGER PRIMARY KEY,
setup_complete BOOLEAN DEFAULT 0
);"""
]
conn = create_connection()
if conn:
try:
c = conn.cursor()
for command in commands:
c.execute(command)
conn.commit()
except Error as e:
print(f"{Fore.RED}Tablo oluşturma hatası: {e}{Style.RESET_ALL}")
finally:
conn.close()
# --- SQL Helper Functions ---
def get_warnings(guild_id: int, user_id: int) -> int:
conn = create_connection()
if not conn: return 0
try:
c = conn.cursor()
c.execute("SELECT count FROM warnings WHERE guild_id=? AND user_id=?", (guild_id, user_id))
result = c.fetchone()
return result[0] if result else 0
except Error as e:
print(f"{Fore.RED}Uyarı getirme hatası: {e}{Style.RESET_ALL}")
return 0
finally:
conn.close()
def add_warning(guild_id: int, user_id: int) -> int:
conn = create_connection()
if not conn: return 0
try:
c = conn.cursor()
c.execute("SELECT count FROM warnings WHERE guild_id=? AND user_id=?", (guild_id, user_id))
result = c.fetchone()
new_count = result[0] + 1 if result else 1
c.execute("""
INSERT INTO warnings (guild_id, user_id, count)
VALUES (?, ?, ?)
ON CONFLICT(guild_id, user_id)
DO UPDATE SET count = excluded.count
""", (guild_id, user_id, new_count))
conn.commit()
return new_count
except Error as e:
print(f"{Fore.RED}Uyarı ekleme hatası: {e}{Style.RESET_ALL}")
return 0
finally:
conn.close()
def remove_warning(guild_id: int, user_id: int) -> bool:
conn = create_connection()
if not conn: return False
try:
c = conn.cursor()
c.execute("SELECT count FROM warnings WHERE guild_id=? AND user_id=?", (guild_id, user_id))
result = c.fetchone()
if not result: return False
new_count = result[0] - 1
if new_count <= 0:
c.execute("DELETE FROM warnings WHERE guild_id=? AND user_id=?", (guild_id, user_id))
else:
c.execute("UPDATE warnings SET count=? WHERE guild_id=? AND user_id=?", (new_count, guild_id, user_id))
conn.commit()
return True
except Error as e:
print(f"{Fore.RED}Uyarı silme hatası: {e}{Style.RESET_ALL}")
return False
finally:
conn.close()
def set_log_channel(guild_id: int, channel_id: int):
conn = create_connection()
if not conn: return
try:
c = conn.cursor()
c.execute("""
INSERT OR REPLACE INTO log_channels (guild_id, channel_id)
VALUES (?, ?)
""", (guild_id, channel_id))
conn.commit()
except Error as e:
print(f"{Fore.RED}Log kanalı ayarlama hatası: {e}{Style.RESET_ALL}")
finally:
conn.close()
def get_log_channel(guild_id: int) -> int:
conn = create_connection()
if not conn: return None
try:
c = conn.cursor()
c.execute("SELECT channel_id FROM log_channels WHERE guild_id=?", (guild_id,))
result = c.fetchone()
return result[0] if result else None
except Error as e:
print(f"{Fore.RED}Log kanalı getirme hatası: {e}{Style.RESET_ALL}")
return None
finally:
conn.close()
def set_autorole(guild_id: int, role_id: int):
conn = create_connection()
if not conn: return
try:
c = conn.cursor()
c.execute("""
INSERT OR REPLACE INTO autoroles (guild_id, role_id)
VALUES (?, ?)
""", (guild_id, role_id))
conn.commit()
except Error as e:
print(f"{Fore.RED}Otorol ayarlama hatası: {e}{Style.RESET_ALL}")
finally:
conn.close()
def get_autorole(guild_id: int) -> int:
conn = create_connection()
if not conn: return None
try:
c = conn.cursor()
c.execute("SELECT role_id FROM autoroles WHERE guild_id=?", (guild_id,))
result = c.fetchone()
return result[0] if result else None
except Error as e:
print(f"{Fore.RED}Otorol getirme hatası: {e}{Style.RESET_ALL}")
return None
finally:
conn.close()
def add_immune_user(guild_id: int, user_id: int):
conn = create_connection()
if not conn: return
try:
c = conn.cursor()
c.execute("""
INSERT OR IGNORE INTO immune_users (guild_id, user_id)
VALUES (?, ?)
""", (guild_id, user_id))
conn.commit()
except Error as e:
print(f"{Fore.RED}Immune kullanıcı ekleme hatası: {e}{Style.RESET_ALL}")
finally:
conn.close()
def remove_immune_user(guild_id: int, user_id: int) -> bool:
conn = create_connection()
if not conn: return False
try:
c = conn.cursor()
c.execute("DELETE FROM immune_users WHERE guild_id=? AND user_id=?", (guild_id, user_id))
conn.commit()
return c.rowcount > 0
except Error as e:
print(f"{Fore.RED}Immune kullanıcı kaldırma hatası: {e}{Style.RESET_ALL}")
return False
finally:
conn.close()
def is_immune(guild_id: int, user_id: int) -> bool:
conn = create_connection()
if not conn: return False
try:
c = conn.cursor()
c.execute("SELECT 1 FROM immune_users WHERE guild_id=? AND user_id=?", (guild_id, user_id))
return c.fetchone() is not None
except Error as e:
print(f"{Fore.RED}Immune kontrol hatası: {e}{Style.RESET_ALL}")
return False
finally:
conn.close()
def add_suggestion(guild_id: int, user_id: int, suggestion: str) -> int:
conn = create_connection()
if not conn: return None
try:
c = conn.cursor()
c.execute("""
INSERT INTO suggestions (guild_id, user_id, suggestion)
VALUES (?, ?, ?)
""", (guild_id, user_id, suggestion))
conn.commit()
return c.lastrowid
except Error as e:
print(f"{Fore.RED}Öneri ekleme hatası: {e}{Style.RESET_ALL}")
return None
finally:
conn.close()
def get_suggestions(guild_id: int):
conn = create_connection()
if not conn: return []
try:
c = conn.cursor()
c.execute("SELECT id, user_id, suggestion, timestamp FROM suggestions WHERE guild_id=?", (guild_id,))
return c.fetchall()
except Error as e:
print(f"{Fore.RED}Önerileri getirme hatası: {e}{Style.RESET_ALL}")
return []
finally:
conn.close()
def add_mod_history(guild_id: int, user_id: int, action: str, moderator_id: int, reason: str = None):
conn = create_connection()
if not conn: return
try:
c = conn.cursor()
c.execute("""
INSERT INTO mod_history (guild_id, user_id, action, moderator_id, reason)
VALUES (?, ?, ?, ?, ?)
""", (guild_id, user_id, action, moderator_id, reason))
conn.commit()
except Error as e:
print(f"{Fore.RED}Mod geçmişi ekleme hatası: {e}{Style.RESET_ALL}")
finally:
conn.close()
def get_mod_history(guild_id: int, user_id: int):
conn = create_connection()
if not conn: return []
try:
c = conn.cursor()
c.execute("""
SELECT action, reason, moderator_id, timestamp
FROM mod_history
WHERE guild_id=? AND user_id=?
""", (guild_id, user_id))
return c.fetchall()
except Error as e:
print(f"{Fore.RED}Mod geçmişi getirme hatası: {e}{Style.RESET_ALL}")
return []
finally:
conn.close()
# --- Dil Rol Sistemi ---
def set_language_roles(guild_id: int, role_tr: int, role_en: int, role_other: int):
conn = create_connection()
if not conn: return
try:
c = conn.cursor()
c.execute("""
INSERT OR REPLACE INTO language_roles
(guild_id, role_tr, role_en, role_other)
VALUES (?, ?, ?, ?)
""", (guild_id, role_tr, role_en, role_other))
conn.commit()
except Error as e:
print(f"{Fore.RED}Dil rolleri ayarlama hatası: {e}{Style.RESET_ALL}")
finally:
conn.close()
def get_language_roles(guild_id: int):
conn = create_connection()
if not conn: return None
try:
c = conn.cursor()
c.execute("""
SELECT role_tr, role_en, role_other
FROM language_roles
WHERE guild_id=?
""", (guild_id,))
result = c.fetchone()
if not result: return None
return {
"role_tr": result[0],
"role_en": result[1],
"role_other": result[2]
}
except Error as e:
print(f"{Fore.RED}Dil rolleri getirme hatası: {e}{Style.RESET_ALL}")
return None
finally:
conn.close()
# --- Level Sistemi SQL Fonksiyonları ---
def set_level_config(
guild_id: int,
role5_id: int,
role15_id: int,
role25_id: int,
announcement_channel_ids: list,
log_channel_id: int
):
conn = create_connection()
if not conn: return
try:
channels_str = ",".join(str(ch_id) for ch_id in announcement_channel_ids) if announcement_channel_ids else ""
c = conn.cursor()
c.execute("""
INSERT OR REPLACE INTO level_config
(guild_id, role5_id, role15_id, role25_id, announcement_channels, log_channel_id)
VALUES (?, ?, ?, ?, ?, ?)
""", (guild_id, role5_id, role15_id, role25_id, channels_str, log_channel_id))
conn.commit()
except Error as e:
print(f"{Fore.RED}Level konfig ayarlama hatası: {e}{Style.RESET_ALL}")
finally:
conn.close()
def get_level_config(guild_id: int):
conn = create_connection()
if not conn: return None
try:
c = conn.cursor()
c.execute("""
SELECT role5_id, role15_id, role25_id, announcement_channels, log_channel_id
FROM level_config
WHERE guild_id=?
""", (guild_id,))
result = c.fetchone()
if not result: return None
channels_str = result[3]
channel_ids = [int(ch_id) for ch_id in channels_str.split(",")] if channels_str else []
return {
"role5_id": result[0],
"role15_id": result[1],
"role25_id": result[2],
"announcement_channel_ids": channel_ids,
"log_channel_id": result[4]
}
except Error as e:
print(f"{Fore.RED}Level konfig getirme hatası: {e}{Style.RESET_ALL}")
return None
finally:
conn.close()
def get_user_level(guild_id: int, user_id: int):
conn = create_connection()
if not conn: return (0, 0)
try:
c = conn.cursor()
c.execute("""
SELECT xp, level
FROM user_levels
WHERE guild_id=? AND user_id=?
""", (guild_id, user_id))
result = c.fetchone()
return result if result else (0, 0)
except Error as e:
print(f"{Fore.RED}Kullanıcı level getirme hatası: {e}{Style.RESET_ALL}")
return (0, 0)
finally:
conn.close()
def set_user_level(
guild_id: int,
user_id: int,
xp: int,
level: int,
last_message_time: float = None
):
conn = create_connection()
if not conn: return
try:
c = conn.cursor()
if last_message_time:
c.execute("""
INSERT OR REPLACE INTO user_levels
(guild_id, user_id, xp, level, last_message_time)
VALUES (?, ?, ?, ?, ?)
""", (guild_id, user_id, xp, level, last_message_time))
else:
c.execute("""
INSERT OR REPLACE INTO user_levels
(guild_id, user_id, xp, level)
VALUES (?, ?, ?, ?)
""", (guild_id, user_id, xp, level))
conn.commit()
except Error as e:
print(f"{Fore.RED}Kullanıcı level ayarlama hatası: {e}{Style.RESET_ALL}")
finally:
conn.close()
def update_user_xp(guild_id: int, user_id: int, xp_delta: int):
conn = create_connection()
if not conn: return (0, 0)
try:
c = conn.cursor()
c.execute("""
SELECT xp, level
FROM user_levels
WHERE guild_id=? AND user_id=?
""", (guild_id, user_id))
result = c.fetchone()
current_xp = result[0] if result else 0
current_level = result[1] if result else 0
new_xp = max(0, current_xp + xp_delta)
new_level = calculate_level(new_xp)
c.execute("""
INSERT OR REPLACE INTO user_levels
(guild_id, user_id, xp, level)
VALUES (?, ?, ?, ?)
""", (guild_id, user_id, new_xp, new_level))
conn.commit()
return (new_xp, new_level)
except Error as e:
print(f"{Fore.RED}XP güncelleme hatası: {e}{Style.RESET_ALL}")
return (0, 0)
finally:
conn.close()
# --- Mesaj Log Sistemi ---
def log_message(
guild_id: int,
channel_id: int,
user_id: int,
message_id: int,
content: str,
attachments: list = None,
is_deleted: bool = False,
is_edited: bool = False,
moderator_id: int = None
):
conn = create_connection()
if not conn: return
try:
attachments_str = ",".join([a.url for a in attachments]) if attachments else ""
c = conn.cursor()
c.execute("""
INSERT INTO message_logs (
guild_id, channel_id, user_id, message_id, content,
attachments, is_deleted, is_edited, moderator_id
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
guild_id, channel_id, user_id, message_id, content,
attachments_str, is_deleted, is_edited, moderator_id
))
conn.commit()
except Error as e:
print(f"{Fore.RED}Mesaj loglama hatası: {e}{Style.RESET_ALL}")
finally:
conn.close()
def get_message_logs(guild_id: int, user_id: int = None, limit: int = 10):
conn = create_connection()
if not conn: return []
try:
c = conn.cursor()
if user_id:
c.execute("""
SELECT * FROM message_logs
WHERE guild_id=? AND user_id=?
ORDER BY timestamp DESC
LIMIT ?
""", (guild_id, user_id, limit))
else:
c.execute("""
SELECT * FROM message_logs
WHERE guild_id=?
ORDER BY timestamp DESC
LIMIT ?
""", (guild_id, limit))
return c.fetchall()
except Error as e:
print(f"{Fore.RED}Mesaj logları getirme hatası: {e}{Style.RESET_ALL}")
return []
finally:
conn.close()
# --- Level Sistemi Yardımcı Fonksiyonlar ---
def calculate_level(xp: int) -> int:
level = 0
while xp >= xp_for_level(level + 1):
level += 1
return level
def xp_for_level(level: int) -> int:
return int(100 * (level ** 1.5))
# --- Global Variables ---
warn_limit = 3
mute_duration = timedelta(minutes=15)
XP_COOLDOWN = 1 # XP kazanma cooldown'u (saniye)
XP_PER_MESSAGE = 10 # Mesaj başına verilen XP
XP_PENALTY = 50 # Uyarı başına kaybedilen XP
LEVEL_ROLES = {5: "role5_id", 15: "role15_id", 25: "role25_id"}
# Küfür listesi
kufurler = [
"salak", "aptal", "mal", "am", "amına", "sikiyim", "götünü", "gotunu",
"annenin", "ananın", "oc", "oe", "ananı", "özürlü", "sik", "gavat",
"orosbu", "evladı", "orospu", "oç", "mal", "a m k", "aq", "amk", "yarram",
"yarrak", "mk", "ucube", "ifşa", "alınır", "dm", "satılır", "babanı",
"karını", "bacını", "sürtük", "pic", "piç"
]
# Küfür regex patternleri
kufur_patterns = [re.compile(rf'\b{re.escape(k)}\b', re.IGNORECASE) for k in kufurler]
# Flood kontrol
user_messages = {}
afk_users = {}
@tree.command(name="soru", description="GPT-4 API ile etkileşim kurar")
async def soru(interaction: discord.Interaction, mesaj: str):
if len(mesaj) > 1500:
await interaction.response.send_message(
"❌ Soru çok uzun! Maksimum 1500 karakter kabul edebilirim.",
ephemeral=True
)
return
await interaction.response.defer()
try:
api_url = f"https://suqul3162.vercel.app/api/gpt4?promt={mesaj}"
response = requests.get(api_url, timeout=10)
if response.status_code != 200:
error_msg = f"⚠️ API hatası (Kod: {response.status_code})"
await interaction.followup.send(error_msg)
return
cevap = response.text.strip()
if len(cevap) > 1950:
cevap = cevap[:1950] + "\n[...] (devamı kısaltıldı)"
await interaction.followup.send(
f"**Soru:** {mesaj}\n\n"
f"**Cevap:**\n{cevap}"
)
except requests.exceptions.Timeout:
await interaction.followup.send("⏳ API yanıt vermedi. Lütfen daha sonra tekrar deneyin.")
except requests.exceptions.RequestException as e:
await interaction.followup.send(f"⚠️ Hata oluştu: {str(e)}")
print(f"{Fore.RED}Soru komutu hatası: {e}{Style.RESET_ALL}")
@tree.command(name="sync")
async def sync(interaction: discord.Interaction):
try:
await tree.sync()
await interaction.response.send_message("Komutlar senkronize edildi!", ephemeral=True)
except Exception as e:
await interaction.response.send_message(f"Senkronizasyon hatası: {e}", ephemeral=True)
print(f"{Fore.RED}Senkronizasyon hatası: {e}{Style.RESET_ALL}")
# --- Dil Rol Sistemi Butonları ---
class LanguageSelect(discord.ui.View):
def __init__(self, roles):
super().__init__(timeout=None)
self.roles = roles
@discord.ui.button(label="Türkçe", style=discord.ButtonStyle.primary, custom_id="lang_tr")
async def turkish_button(self, interaction: discord.Interaction, button: discord.ui.Button):
await self.assign_role(interaction, self.roles["role_tr"])
@discord.ui.button(label="English", style=discord.ButtonStyle.success, custom_id="lang_en")
async def english_button(self, interaction: discord.Interaction, button: discord.ui.Button):
await self.assign_role(interaction, self.roles["role_en"])
@discord.ui.button(label="Diğer", style=discord.ButtonStyle.secondary, custom_id="lang_other")
async def other_button(self, interaction: discord.Interaction, button: discord.ui.Button):
await self.assign_role(interaction, self.roles["role_other"])
async def assign_role(self, interaction: discord.Interaction, role_id: int):
try:
if not role_id:
await interaction.response.send_message("Bu rol henüz ayarlanmamış!", ephemeral=True)
return
guild = interaction.guild
role = guild.get_role(role_id)
if not role:
await interaction.response.send_message("Rol bulunamadı!", ephemeral=True)
return
# Mevcut dil rollerini kaldır
lang_roles = get_language_roles(guild.id)
if lang_roles:
for r_id in lang_roles.values():
if r_id:
existing_role = guild.get_role(r_id)
if existing_role and existing_role in interaction.user.roles:
await interaction.user.remove_roles(existing_role)
# Yeni rolü ekle
await interaction.user.add_roles(role)
await interaction.response.send_message(
f"Başarıyla {role.name} rolü verildi!",
ephemeral=True
)
except Exception as e:
await interaction.response.send_message(f"Rol atama hatası: {e}", ephemeral=True)
print(f"{Fore.RED}Dil rolü atama hatası: {e}{Style.RESET_ALL}")
# --- Helper Functions ---
def embed_message(title: str, description: str, color=discord.Color.blue()):
embed = discord.Embed(
title=title,
description=description,
color=color,
timestamp=datetime.now(timezone.utc)
)
return embed
async def log_gonder(guild_id: int, embed: discord.Embed):
try:
channel_id = get_log_channel(guild_id)
if not channel_id: return
channel = bot.get_channel(channel_id)
if channel:
await channel.send(embed=embed)
except Exception as e:
print(f"{Fore.RED}Log gönderme hatası: {e}{Style.RESET_ALL}")
def parse_duration(sure: str) -> timedelta:
pattern = r"(\d+)([smhdw])"
match = re.fullmatch(pattern, sure.lower())
if not match:
raise ValueError("Geçersiz süre formatı. Örn: 10s, 1h, 1d, 1w")
value, unit = match.groups()
value = int(value)
if unit == 's': return timedelta(seconds=value)
elif unit == 'm': return timedelta(minutes=value)
elif unit == 'h': return timedelta(hours=value)
elif unit == 'd': return timedelta(days=value)
elif unit == 'w': return timedelta(weeks=value)
def is_flood(guild_id: int, user_id: int, limit=5, period=10) -> bool:
now = datetime.now(timezone.utc)
if guild_id not in user_messages:
user_messages[guild_id] = {}
if user_id not in user_messages[guild_id]:
user_messages[guild_id][user_id] = []
user_messages[guild_id][user_id] = [
t for t in user_messages[guild_id][user_id]
if (now - t).total_seconds() <= period
]
user_messages[guild_id][user_id].append(now)
return len(user_messages[guild_id][user_id]) > limit
def contains_kufur(content: str) -> bool:
content_lower = content.lower()
return any(pattern.search(content_lower) for pattern in kufur_patterns)
async def handle_level_up(guild: discord.Guild, user: discord.Member, old_level: int, new_level: int):
if old_level >= new_level:
return
config = get_level_config(guild.id)
if not config:
return
# Yeni level rol atama (5, 15, 25)
for req_level, role_key in LEVEL_ROLES.items():
role_id = config.get(role_key)
if role_id and new_level >= req_level and old_level < req_level:
role = guild.get_role(role_id)
if role and role not in user.roles:
try:
await user.add_roles(role, reason=f"Level {req_level} rolü")
except Exception as e:
print(f"{Fore.RED}Rol verme hatası: {e}{Style.RESET_ALL}")
# Level atlama duyurusu
announcement_channel_ids = config.get("announcement_channel_ids", [])
log_channel_id = config.get("log_channel_id")
embed = discord.Embed(
title="🎉 Level Atladın!",
description=f"{user.mention} **Level {new_level}** oldu!",
color=discord.Color.gold(),
timestamp=datetime.now(timezone.utc)
)
embed.set_thumbnail(url=user.display_avatar.url)
for channel_id in announcement_channel_ids:
channel = guild.get_channel(channel_id)
if channel:
try:
await channel.send(embed=embed)
except Exception as e:
print(f"{Fore.RED}Duyuru kanalına gönderim hatası: {e}{Style.RESET_ALL}")
if log_channel_id:
log_channel = guild.get_channel(log_channel_id)
if log_channel:
try:
await log_channel.send(embed=embed)
except Exception as e:
print(f"{Fore.RED}Log kanalına gönderim hatası: {e}{Style.RESET_ALL}")
# --- Events ---
@bot.event
async def on_ready():
print(f"{Fore.GREEN}{bot.user} olarak giriş yapıldı!{Style.RESET_ALL}")
initialize_database()
try:
synced = await tree.sync()
print(f"{Fore.GREEN}{len(synced)} komut senkronize edildi.{Style.RESET_ALL}")
except Exception as e:
print(f"{Fore.RED}Komut senkronizasyon hatası: {e}{Style.RESET_ALL}")
@bot.event
async def on_member_join(member):
try:
role_id = get_autorole(member.guild.id)
if not role_id: return
role = member.guild.get_role(role_id)
if role:
await member.add_roles(role, reason="OtoRol Sistemi")
except Exception as e:
print(f"{Fore.RED}Otorol verme hatası: {e}{Style.RESET_ALL}")
@bot.event
async def on_message(message):
if message.author.bot or not message.guild:
await bot.process_commands(message)
return
guild_id = message.guild.id
user_id = message.author.id
content = message.content
# Immune kullanıcı kontrolü
if is_immune(guild_id, user_id):
await bot.process_commands(message)
return
# XP Sistemi
current_time = time.time()
last_xp_time = None
conn = create_connection()
if conn:
try:
c = conn.cursor()
c.execute("""
SELECT last_message_time
FROM user_levels
WHERE guild_id=? AND user_id=?
""", (guild_id, user_id))
result = c.fetchone()
last_xp_time = result[0] if result else None
except Error:
pass
finally:
conn.close()
should_gain_xp = True
if last_xp_time and (current_time - last_xp_time) < XP_COOLDOWN:
should_gain_xp = False
if should_gain_xp:
xp, level = get_user_level(guild_id, user_id)
new_xp = xp + XP_PER_MESSAGE
new_level = calculate_level(new_xp)
if new_level > level:
await handle_level_up(message.guild, message.author, level, new_level)
set_user_level(guild_id, user_id, new_xp, new_level, current_time)
# Küfür kontrolü (regex ile geliştirilmiş)
if contains_kufur(content):
try:
await message.delete()
except Exception as e:
print(f"{Fore.RED}Mesaj silme hatası: {e}{Style.RESET_ALL}")
count = add_warning(guild_id, user_id)
add_mod_history(guild_id, user_id, "UYARI", bot.user.id, "Küfür tespit edildi")
new_xp, _ = update_user_xp(guild_id, user_id, -XP_PENALTY)
embed = embed_message(
title="🚨 Küfür Tespit Edildi!",
description=f"{message.author.mention} adlı kullanıcı küfür etti ve uyarıldı.\n"
f"Toplam uyarı: **{count}**\n"
f"XP cezası: **-{XP_PENALTY} XP** (Yeni XP: {new_xp})",
color=discord.Color.red()
)
await message.channel.send(embed=embed, delete_after=10)
await log_gonder(guild_id, embed)
if count >= warn_limit:
if message.guild.me.guild_permissions.moderate_members:
try:
await message.author.timeout(mute_duration)
add_mod_history(guild_id, user_id, "MUTE", bot.user.id, "3 uyarı sınırı aşımı")
embed2 = embed_message(
title="🔇 Kullanıcı Susturuldu",
description=f"{message.author.mention} {mute_duration.total_seconds()//60} dakika boyunca susturuldu (3 uyarı sınırı aşımı).",
color=discord.Color.orange()
)
await message.channel.send(embed=embed2)
await log_gonder(guild_id, embed2)
conn = create_connection()
if conn:
try:
c = conn.cursor()
c.execute("""
UPDATE warnings
SET count=0
WHERE guild_id=? AND user_id=?
""", (guild_id, user_id))
conn.commit()
except Error as e:
print(f"{Fore.RED}Uyarı sıfırlama hatası: {e}{Style.RESET_ALL}")
finally:
conn.close()
except Exception as e:
print(f"{Fore.RED}Susturma hatası: {e}{Style.RESET_ALL}")
# Flood kontrolü
elif is_flood(guild_id, user_id):
try:
await message.delete()
except Exception as e:
print(f"{Fore.RED}Mesaj silme hatası: {e}{Style.RESET_ALL}")
new_xp, _ = update_user_xp(guild_id, user_id, -XP_PENALTY)
embed = embed_message(
title="⚠️ Flood Koruması",
description=f"{message.author.mention} flood yapmaya çalıştı, mesaj silindi.\n"
f"XP cezası: **-{XP_PENALTY} XP** (Yeni XP: {new_xp})",
color=discord.Color.gold()
)
await message.channel.send(embed=embed, delete_after=10)
await log_gonder(guild_id, embed)
# Reklam/link kontrolü
if "http://" in content or "https://" in content or "discord.gg/" in content:
if not is_immune(guild_id, user_id):
try:
await message.delete()
except Exception as e:
print(f"{Fore.RED}Mesaj silme hatası: {e}{Style.RESET_ALL}")
new_xp, _ = update_user_xp(guild_id, user_id, -XP_PENALTY)
embed = embed_message(
title="🚫 Reklam Engellendi",
description=f"{message.author.mention} reklam/link paylaştığı için mesajı silindi.\n"
f"XP cezası: **-{XP_PENALTY} XP** (Yeni XP: {new_xp})",
color=discord.Color.dark_red()
)
await message.channel.send(embed=embed, delete_after=10)
await log_gonder(guild_id, embed)
# AFK kontrolü (geliştirilmiş)
afk_mentions = [mention for mention in message.mentions if mention.id in afk_users]
if afk_mentions:
afk_info = []
for mention in afk_mentions:
afk_msg, afk_time = afk_users[mention.id]