-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
4077 lines (3528 loc) · 167 KB
/
bot.py
File metadata and controls
4077 lines (3528 loc) · 167 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
# ══════════════════════════════════════════════════════════════════════════════
# INTENT_BOTv2.1
# Features: Moderation, Leveling, Economy, Tickets (Button Panel), Giveaways,
# Auto-mod, Logging, Welcome/Leave, Reaction Roles, Color Roles,
# Fun, Utility, Music (24/7 VC), AI Integration, Waifu,
# Dynamic Marketplace with Trading, and more!
# ══════════════════════════════════════════════════════════════════════════════
import discord
from discord.ext import commands, tasks
from discord import app_commands
import asyncio
import aiosqlite
import aiohttp
import datetime
import random
import json
import re
import os
import math
from typing import Optional, Literal
from collections import defaultdict
import time
import traceback
try:
import wavelink
WAVELINK_AVAILABLE = True
except ImportError:
WAVELINK_AVAILABLE = False
logger.warning("⚠️ wavelink not installed - music features disabled. Install with: pip install wavelink")
# ══════════════════════════════════════════════════════════════════════════════
# CONFIGURATION
# ══════════════════════════════════════════════════════════════════════════════
CONFIG = {
"TOKEN": "DISCORD_TOKEN", # REPLACE THIS
"GUILD_ID": 1429056625183948882,
"PREFIX": "!",
"OWNER_IDS": [],
# Channel IDs (set via commands)
"WELCOME_CHANNEL": None,
"LEAVE_CHANNEL": None,
"LOG_CHANNEL": None,
"TICKET_CATEGORY": None,
"LEVEL_UP_CHANNEL": None,
"GIVEAWAY_CHANNEL": None,
"MUSIC_VC_CHANNEL": None, # 24/7 VC channel ID
# Role IDs
"MUTE_ROLE": None,
"AUTO_ROLE": None,
"MOD_ROLES": [],
"ADMIN_ROLES": [],
# Feature Toggles
"WELCOME_ENABLED": True,
"LEVELING_ENABLED": True,
"ECONOMY_ENABLED": True,
"AUTOMOD_ENABLED": True,
"LOGGING_ENABLED": True,
"MUSIC_ENABLED": True,
# Auto-mod Settings
"BANNED_WORDS": ["badword1", "badword2"],
"ANTI_SPAM_ENABLED": True,
"ANTI_LINK_ENABLED": False,
"MAX_MENTIONS": 5,
"SPAM_THRESHOLD": 5,
"SPAM_INTERVAL": 5,
# Economy Settings
"CURRENCY_NAME": "coins",
"CURRENCY_SYMBOL": "🪙",
"DAILY_AMOUNT": 100,
"WORK_MIN": 50,
"WORK_MAX": 200,
"WORK_COOLDOWN": 3600,
# Leveling Settings
"XP_PER_MESSAGE": (15, 25),
"XP_COOLDOWN": 60,
"LEVEL_UP_MESSAGE": "🎉 Congratulations {user}! You've reached level **{level}**!",
# Lavalink Settings (for music)
"LAVALINK_URI": "http://localhost:2333",
"LAVALINK_PASSWORD": "youshallnotpass",
# AI Provider API Keys (set via !ai set <provider> <key> or put here)
"AI_KEYS": {
"gemini": "",
"openai": "",
"groq": "",
"claude": "",
"mistral": "",
"cohere": "",
"perplexity": "",
},
}
# ══════════════════════════════════════════════════════════════════════════════
# BOT SETUP
# ══════════════════════════════════════════════════════════════════════════════
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=CONFIG["PREFIX"], intents=intents, help_command=None)
bot.config = CONFIG
# In-memory caches
spam_tracker = defaultdict(list)
xp_cooldowns = {}
active_giveaways = {}
reaction_roles = {}
custom_commands = {}
warnings_cache = {}
afk_users = {}
# ══════════════════════════════════════════════════════════════════════════════
# DATABASE SETUP + MIGRATION (SAFE - NEVER DROPS DATA)
# ══════════════════════════════════════════════════════════════════════════════
async def init_database():
async with aiosqlite.connect("bot_database.db") as db:
# Original tables (unchanged)
await db.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
guild_id INTEGER,
xp INTEGER DEFAULT 0,
level INTEGER DEFAULT 1,
messages INTEGER DEFAULT 0,
balance INTEGER DEFAULT 0,
bank INTEGER DEFAULT 0,
daily_claimed TEXT,
work_claimed TEXT,
inventory TEXT DEFAULT '[]',
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, guild_id)
)
""")
await db.execute("""
CREATE TABLE IF NOT EXISTS warnings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
guild_id INTEGER,
moderator_id INTEGER,
reason TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
)
""")
await db.execute("""
CREATE TABLE IF NOT EXISTS tickets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
channel_id INTEGER,
user_id INTEGER,
guild_id INTEGER,
status TEXT DEFAULT 'open',
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
closed_at TEXT
)
""")
await db.execute("""
CREATE TABLE IF NOT EXISTS custom_commands (
name TEXT PRIMARY KEY,
guild_id INTEGER,
response TEXT,
created_by INTEGER,
uses INTEGER DEFAULT 0,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
)
""")
await db.execute("""
CREATE TABLE IF NOT EXISTS reaction_roles (
message_id INTEGER,
emoji TEXT,
role_id INTEGER,
guild_id INTEGER,
PRIMARY KEY (message_id, emoji)
)
""")
await db.execute("""
CREATE TABLE IF NOT EXISTS giveaways (
id INTEGER PRIMARY KEY AUTOINCREMENT,
message_id INTEGER,
channel_id INTEGER,
guild_id INTEGER,
prize TEXT,
winners INTEGER,
host_id INTEGER,
end_time TEXT,
ended INTEGER DEFAULT 0,
participants TEXT DEFAULT '[]'
)
""")
await db.execute("""
CREATE TABLE IF NOT EXISTS reminders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
channel_id INTEGER,
reminder TEXT,
remind_at TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
)
""")
await db.execute("""
CREATE TABLE IF NOT EXISTS server_settings (
guild_id INTEGER PRIMARY KEY,
welcome_channel INTEGER,
leave_channel INTEGER,
log_channel INTEGER,
mute_role INTEGER,
auto_role INTEGER,
welcome_message TEXT,
leave_message TEXT,
settings TEXT DEFAULT '{}'
)
""")
await db.execute("""
CREATE TABLE IF NOT EXISTS mod_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER,
user_id INTEGER,
moderator_id INTEGER,
action TEXT,
reason TEXT,
duration TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
)
""")
await db.execute("""
CREATE TABLE IF NOT EXISTS shop_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER,
name TEXT,
description TEXT,
price INTEGER,
role_id INTEGER,
stock INTEGER DEFAULT -1,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
)
""")
# ═══════════════════════════════════════════
# NEW TABLES (v2.0 migration - safe to run)
# ═══════════════════════════════════════════
# Market items master catalog
await db.execute("""
CREATE TABLE IF NOT EXISTS market_items (
item_id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE,
category TEXT DEFAULT 'misc',
description TEXT DEFAULT '',
emoji TEXT DEFAULT '📦',
base_price INTEGER DEFAULT 100,
current_price REAL DEFAULT 100.0,
total_bought INTEGER DEFAULT 0,
total_sold INTEGER DEFAULT 0,
rarity TEXT DEFAULT 'common',
tradeable INTEGER DEFAULT 1,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
)
""")
# User market inventory (row-based, better for trading)
await db.execute("""
CREATE TABLE IF NOT EXISTS user_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
guild_id INTEGER,
item_id INTEGER,
quantity INTEGER DEFAULT 1,
acquired_at TEXT DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, guild_id, item_id)
)
""")
# Trades
await db.execute("""
CREATE TABLE IF NOT EXISTS trades (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER,
sender_id INTEGER,
receiver_id INTEGER,
item_id INTEGER,
quantity INTEGER DEFAULT 1,
price INTEGER DEFAULT 0,
status TEXT DEFAULT 'pending',
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
resolved_at TEXT
)
""")
# AI tokens storage
await db.execute("""
CREATE TABLE IF NOT EXISTS ai_tokens (
guild_id INTEGER,
provider TEXT,
token TEXT,
added_by INTEGER,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (guild_id, provider)
)
""")
# Color roles for button panel
await db.execute("""
CREATE TABLE IF NOT EXISTS color_roles (
guild_id INTEGER,
role_id INTEGER,
label TEXT,
emoji TEXT DEFAULT '🎨',
style INTEGER DEFAULT 1,
PRIMARY KEY (guild_id, role_id)
)
""")
# Music queue persistence (optional)
await db.execute("""
CREATE TABLE IF NOT EXISTS music_settings (
guild_id INTEGER PRIMARY KEY,
vc_channel_id INTEGER,
volume INTEGER DEFAULT 50,
loop_mode TEXT DEFAULT 'off',
dj_role_id INTEGER
)
""")
# Waifu collection
await db.execute("""
CREATE TABLE IF NOT EXISTS waifu_collection (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
guild_id INTEGER,
waifu_name TEXT,
waifu_url TEXT,
waifu_type TEXT,
rarity TEXT DEFAULT 'common',
collected_at TEXT DEFAULT CURRENT_TIMESTAMP
)
""")
await db.commit()
print("✅ Database initialized and migrated successfully!")
async def seed_market_items():
"""Seed the market with items if empty. Safe to call multiple times."""
async with aiosqlite.connect("bot_database.db") as db:
cursor = await db.execute("SELECT COUNT(*) FROM market_items")
count = (await cursor.fetchone())[0]
if count > 0:
return # Already seeded
items = [
# Fish & Sea
("Sardine", "fish", "A tiny common fish", "🐟", 10, "common"),
("Salmon", "fish", "A healthy pink fish", "🐟", 45, "common"),
("Tuna", "fish", "A big ocean fish", "🐟", 80, "uncommon"),
("Swordfish", "fish", "A powerful predator fish", "⚔️", 200, "rare"),
("Golden Koi", "fish", "A legendary golden fish", "✨", 1500, "legendary"),
("Pufferfish", "fish", "Cute but deadly", "🐡", 120, "uncommon"),
("Octopus", "fish", "Eight-armed sea creature", "🐙", 250, "rare"),
("Whale", "fish", "The biggest catch possible", "🐋", 5000, "legendary"),
("Shrimp", "fish", "Tiny but tasty", "🦐", 15, "common"),
("Lobster", "fish", "A fancy red crustacean", "🦞", 300, "rare"),
("Crab", "fish", "A snappy little fella", "🦀", 60, "common"),
("Jellyfish", "fish", "Beautiful and dangerous", "🪼", 90, "uncommon"),
# Minerals & Gems
("Coal", "minerals", "A chunk of coal", "⚫", 5, "common"),
("Iron Ore", "minerals", "Raw iron ore", "🪨", 25, "common"),
("Copper Ore", "minerals", "Shiny copper ore", "🟤", 30, "common"),
("Silver Ore", "minerals", "Gleaming silver ore", "⚪", 80, "uncommon"),
("Gold Ore", "minerals", "Precious gold ore", "🟡", 200, "rare"),
("Diamond", "minerals", "A brilliant diamond", "💎", 1000, "epic"),
("Emerald", "minerals", "A vivid green gem", "💚", 800, "epic"),
("Ruby", "minerals", "A fiery red gem", "❤️", 850, "epic"),
("Sapphire", "minerals", "A deep blue gem", "💙", 900, "epic"),
("Amethyst", "minerals", "A purple crystal", "💜", 400, "rare"),
("Obsidian", "minerals", "Volcanic glass", "🖤", 150, "uncommon"),
("Meteorite", "minerals", "Fragment from space", "☄️", 3000, "legendary"),
# Food & Cooking
("Apple", "food", "A fresh red apple", "🍎", 8, "common"),
("Banana", "food", "A ripe banana", "🍌", 6, "common"),
("Pizza Slice", "food", "Cheesy goodness", "🍕", 25, "common"),
("Burger", "food", "A juicy burger", "🍔", 30, "common"),
("Sushi Roll", "food", "Artisanal sushi", "🍣", 75, "uncommon"),
("Steak", "food", "Premium wagyu steak", "🥩", 150, "rare"),
("Cake", "food", "A delicious cake", "🎂", 60, "uncommon"),
("Cookie", "food", "Warm chocolate chip cookie", "🍪", 12, "common"),
("Ramen", "food", "Hot bowl of ramen", "🍜", 40, "common"),
("Golden Apple", "food", "A mythical golden apple", "🍏", 2000, "legendary"),
("Taco", "food", "A crunchy taco", "🌮", 20, "common"),
("Ice Cream", "food", "Cold and sweet", "🍦", 15, "common"),
# Tools & Equipment
("Wooden Pickaxe", "tools", "A basic pickaxe", "⛏️", 50, "common"),
("Iron Pickaxe", "tools", "A sturdy pickaxe", "⛏️", 200, "uncommon"),
("Diamond Pickaxe", "tools", "The best pickaxe", "⛏️", 1500, "epic"),
("Fishing Rod", "tools", "A basic fishing rod", "🎣", 40, "common"),
("Golden Fishing Rod", "tools", "Catches rare fish easier", "🎣", 800, "rare"),
("Shovel", "tools", "For digging treasures", "🔧", 35, "common"),
("Axe", "tools", "A sharp woodcutting axe", "🪓", 45, "common"),
("Telescope", "tools", "See the stars", "🔭", 300, "rare"),
("Compass", "tools", "Never get lost", "🧭", 100, "uncommon"),
("Lantern", "tools", "Lights your way", "🏮", 60, "common"),
# Collectibles
("Common Card", "collectibles", "A common trading card", "🃏", 20, "common"),
("Rare Card", "collectibles", "A rare trading card", "🃏", 200, "rare"),
("Legendary Card", "collectibles", "A legendary trading card", "🃏", 2000, "legendary"),
("Trophy", "collectibles", "A shiny trophy", "🏆", 500, "epic"),
("Crown", "collectibles", "A royal crown", "👑", 3000, "legendary"),
("Medal", "collectibles", "A medal of honor", "🏅", 250, "rare"),
("Gem Stone", "collectibles", "A mysterious gem", "💠", 400, "rare"),
("Star Fragment", "collectibles", "Fallen from the sky", "⭐", 600, "epic"),
("Ancient Coin", "collectibles", "A coin from ancient times", "🪙", 350, "rare"),
("Lucky Clover", "collectibles", "Brings good fortune", "🍀", 150, "uncommon"),
# Tech & Digital
("USB Drive", "tech", "4GB storage device", "💾", 30, "common"),
("SSD Drive", "tech", "Fast storage", "💿", 200, "uncommon"),
("Graphics Card", "tech", "RTX quality", "🖥️", 800, "rare"),
("Laptop", "tech", "A portable computer", "💻", 1200, "epic"),
("Smartphone", "tech", "Latest model phone", "📱", 600, "rare"),
("Server Rack", "tech", "Enterprise server", "🖥️", 3000, "legendary"),
("Robot", "tech", "A tiny robot companion", "🤖", 2500, "legendary"),
("Satellite", "tech", "Your own satellite", "📡", 5000, "legendary"),
("Drone", "tech", "A flying drone", "🛸", 400, "rare"),
("VR Headset", "tech", "Virtual reality device", "🥽", 500, "rare"),
# Domains & Premium Digital
(".com Domain", "premium", "A .com domain name", "🌐", 1500, "epic"),
(".io Domain", "premium", "A .io domain name", "🌐", 2000, "epic"),
(".gg Domain", "premium", "A .gg domain name", "🌐", 2500, "legendary"),
(".dev Domain", "premium", "A .dev domain name", "🌐", 1800, "epic"),
("Nitro Classic", "premium", "Discord Nitro Classic", "💎", 3000, "legendary"),
("Nitro Full", "premium", "Discord Nitro Full", "💎", 5000, "legendary"),
("Premium Badge", "premium", "An exclusive badge", "🏷️", 4000, "legendary"),
("Custom Bot", "premium", "Your own custom bot", "🤖", 8000, "legendary"),
("Private Server", "premium", "Your own game server", "🖥️", 6000, "legendary"),
("NFT Certificate", "premium", "A unique certificate", "📜", 1000, "epic"),
# Nature & Plants
("Oak Seed", "nature", "Grow an oak tree", "🌰", 10, "common"),
("Rose", "nature", "A beautiful red rose", "🌹", 30, "common"),
("Sunflower", "nature", "A bright sunflower", "🌻", 20, "common"),
("Bonsai Tree", "nature", "A tiny perfect tree", "🌳", 300, "rare"),
("Venus Flytrap", "nature", "A carnivorous plant", "🪴", 150, "uncommon"),
("Mushroom", "nature", "A forest mushroom", "🍄", 15, "common"),
("Cactus", "nature", "A prickly cactus", "🌵", 25, "common"),
("Cherry Blossom", "nature", "A delicate blossom", "🌸", 100, "uncommon"),
("Four Leaf Clover", "nature", "Very lucky find", "🍀", 500, "epic"),
("World Tree Seed", "nature", "A mythical seed", "🌲", 10000, "legendary"),
# Potions & Magic
("Health Potion", "magic", "Restores vitality", "🧪", 50, "common"),
("Mana Potion", "magic", "Restores energy", "🧪", 50, "common"),
("Speed Potion", "magic", "Makes you faster", "⚡", 120, "uncommon"),
("Luck Potion", "magic", "Increases luck", "🍀", 300, "rare"),
("Invisibility Potion", "magic", "Become invisible", "👻", 500, "epic"),
("Love Potion", "magic", "Smells like roses", "💕", 200, "rare"),
("Dragon Scale", "magic", "From a real dragon", "🐉", 2000, "legendary"),
("Phoenix Feather", "magic", "Burns eternally", "🪶", 3000, "legendary"),
("Wizard Hat", "magic", "Pointy and magical", "🧙", 400, "rare"),
("Crystal Ball", "magic", "See the future", "🔮", 600, "epic"),
# Vehicles
("Bicycle", "vehicles", "A simple bicycle", "🚲", 100, "common"),
("Motorcycle", "vehicles", "A fast motorcycle", "🏍️", 500, "rare"),
("Sports Car", "vehicles", "A sleek sports car", "🏎️", 3000, "legendary"),
("Yacht", "vehicles", "A luxury yacht", "🛥️", 8000, "legendary"),
("Helicopter", "vehicles", "A private helicopter", "🚁", 6000, "legendary"),
("Rocket", "vehicles", "To the moon!", "🚀", 15000, "legendary"),
("Skateboard", "vehicles", "A cool skateboard", "🛹", 40, "common"),
("Sailboat", "vehicles", "A sailing boat", "⛵", 800, "rare"),
("Hot Air Balloon", "vehicles", "Float in the sky", "🎈", 1200, "epic"),
("Submarine", "vehicles", "Explore the deep", "🛟", 5000, "legendary"),
# Pets
("Kitten", "pets", "A cute little kitten", "🐱", 200, "uncommon"),
("Puppy", "pets", "A loyal puppy", "🐶", 200, "uncommon"),
("Hamster", "pets", "A tiny hamster", "🐹", 80, "common"),
("Parrot", "pets", "A colorful parrot", "🦜", 300, "rare"),
("Bunny", "pets", "A fluffy bunny", "🐰", 150, "uncommon"),
("Turtle", "pets", "A wise old turtle", "🐢", 100, "common"),
("Fox", "pets", "A clever fox", "🦊", 500, "rare"),
("Owl", "pets", "A wise owl", "🦉", 400, "rare"),
("Dragon Egg", "pets", "May hatch someday", "🥚", 5000, "legendary"),
("Unicorn", "pets", "A mythical unicorn", "🦄", 10000, "legendary"),
]
for name, cat, desc, emoji, price, rarity in items:
await db.execute(
"""INSERT OR IGNORE INTO market_items
(name, category, description, emoji, base_price, current_price, rarity)
VALUES (?, ?, ?, ?, ?, ?, ?)""",
(name, cat, desc, emoji, price, float(price), rarity)
)
await db.commit()
print(f"✅ Seeded {len(items)} market items!")
# ══════════════════════════════════════════════════════════════════════════════
# HELPER FUNCTIONS
# ══════════════════════════════════════════════════════════════════════════════
def get_level_xp(level):
return 5 * (level ** 2) + 50 * level + 100
def get_level_from_xp(xp):
level = 1
while xp >= get_level_xp(level):
xp -= get_level_xp(level)
level += 1
return level, xp
async def get_user_data(user_id, guild_id):
async with aiosqlite.connect("bot_database.db") as db:
cursor = await db.execute(
"SELECT * FROM users WHERE user_id = ? AND guild_id = ?",
(user_id, guild_id)
)
row = await cursor.fetchone()
if not row:
await db.execute(
"INSERT OR IGNORE INTO users (user_id, guild_id) VALUES (?, ?)",
(user_id, guild_id)
)
await db.commit()
cursor = await db.execute(
"SELECT * FROM users WHERE user_id = ? AND guild_id = ?",
(user_id, guild_id)
)
row = await cursor.fetchone()
columns = [description[0] for description in cursor.description]
return dict(zip(columns, row))
async def update_user_data(user_id, guild_id, **kwargs):
async with aiosqlite.connect("bot_database.db") as db:
set_clause = ", ".join([f"{k} = ?" for k in kwargs.keys()])
values = list(kwargs.values()) + [user_id, guild_id]
await db.execute(
f"UPDATE users SET {set_clause} WHERE user_id = ? AND guild_id = ?",
values
)
await db.commit()
async def log_action(guild, embed):
if not CONFIG["LOGGING_ENABLED"]:
return
log_channel_id = CONFIG.get("LOG_CHANNEL")
if log_channel_id:
channel = guild.get_channel(log_channel_id)
if channel:
try:
await channel.send(embed=embed)
except:
pass
def create_embed(title, description=None, color=discord.Color.blue(), **kwargs):
embed = discord.Embed(title=title, description=description, color=color)
embed.timestamp = datetime.datetime.now(datetime.timezone.utc)
if "author" in kwargs:
embed.set_author(name=kwargs["author"].name, icon_url=kwargs["author"].display_avatar.url)
if "footer" in kwargs:
embed.set_footer(text=kwargs["footer"])
if "thumbnail" in kwargs and kwargs["thumbnail"]:
embed.set_thumbnail(url=kwargs["thumbnail"])
if "image" in kwargs and kwargs["image"]:
embed.set_image(url=kwargs["image"])
if "fields" in kwargs:
for name, value, inline in kwargs["fields"]:
embed.add_field(name=name, value=value, inline=inline)
return embed
def parse_time(time_str):
time_regex = re.compile(r"(\d+)([smhdw])")
matches = time_regex.findall(time_str.lower())
if not matches:
return None
total_seconds = 0
for value, unit in matches:
value = int(value)
if unit == "s": total_seconds += value
elif unit == "m": total_seconds += value * 60
elif unit == "h": total_seconds += value * 3600
elif unit == "d": total_seconds += value * 86400
elif unit == "w": total_seconds += value * 604800
return total_seconds
def get_rarity_color(rarity):
colors = {
"common": discord.Color.light_grey(),
"uncommon": discord.Color.green(),
"rare": discord.Color.blue(),
"epic": discord.Color.purple(),
"legendary": discord.Color.gold()
}
return colors.get(rarity, discord.Color.default())
def calculate_market_price(base_price, total_bought, total_sold):
"""Dynamic pricing: more buys = higher price, more sells = lower price"""
demand_ratio = (total_bought + 1) / (total_sold + 1)
multiplier = math.log(demand_ratio + 1, 2) + 0.5
multiplier = max(0.3, min(multiplier, 5.0)) # clamp 30%-500%
return round(base_price * multiplier, 2)
# ══════════════════════════════════════════════════════════════════════════════
# TICKET PANEL (BUTTON-BASED) - NEW
# ══════════════════════════════════════════════════════════════════════════════
class TicketCloseConfirm(discord.ui.View):
def __init__(self):
super().__init__(timeout=60)
@discord.ui.button(label="Confirm Close", style=discord.ButtonStyle.red, custom_id="ticket:confirm_close")
async def confirm_close(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message("🔒 Closing ticket in 5 seconds...")
await asyncio.sleep(5)
async with aiosqlite.connect("bot_database.db") as db:
await db.execute(
"UPDATE tickets SET status = 'closed', closed_at = ? WHERE channel_id = ?",
(datetime.datetime.now(datetime.timezone.utc).isoformat(), interaction.channel.id)
)
await db.commit()
await interaction.channel.delete()
@discord.ui.button(label="Cancel", style=discord.ButtonStyle.grey)
async def cancel_close(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message("❌ Ticket close cancelled.", ephemeral=True)
self.stop()
class TicketControlView(discord.ui.View):
"""View shown inside ticket channel with close button"""
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Close Ticket", style=discord.ButtonStyle.red, emoji="🔒", custom_id="ticket:close")
async def close_ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
async with aiosqlite.connect("bot_database.db") as db:
cursor = await db.execute(
"SELECT * FROM tickets WHERE channel_id = ? AND status = 'open'",
(interaction.channel.id,)
)
ticket = await cursor.fetchone()
if not ticket:
return await interaction.response.send_message("❌ This is not a ticket channel!", ephemeral=True)
await interaction.response.send_message(
"Are you sure you want to close this ticket?",
view=TicketCloseConfirm(),
ephemeral=False
)
class TicketPanelView(discord.ui.View):
"""Persistent panel posted in a channel with Create Ticket button"""
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="📩 Create Ticket", style=discord.ButtonStyle.green, custom_id="ticket:create")
async def create_ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
guild = interaction.guild
user = interaction.user
async with aiosqlite.connect("bot_database.db") as db:
cursor = await db.execute(
"SELECT channel_id FROM tickets WHERE user_id = ? AND guild_id = ? AND status = 'open'",
(user.id, guild.id)
)
existing = await cursor.fetchone()
if existing:
return await interaction.response.send_message(
f"❌ You already have an open ticket: <#{existing[0]}>",
ephemeral=True
)
category = guild.get_channel(CONFIG.get("TICKET_CATEGORY")) if CONFIG.get("TICKET_CATEGORY") else None
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
user: discord.PermissionOverwrite(
view_channel=True, send_messages=True,
attach_files=True, embed_links=True
),
guild.me: discord.PermissionOverwrite(
view_channel=True, send_messages=True,
manage_channels=True, manage_messages=True
)
}
# Add mod roles to overwrites
for mod_role_id in CONFIG.get("MOD_ROLES", []):
mod_role = guild.get_role(mod_role_id)
if mod_role:
overwrites[mod_role] = discord.PermissionOverwrite(view_channel=True, send_messages=True)
for admin_role_id in CONFIG.get("ADMIN_ROLES", []):
admin_role = guild.get_role(admin_role_id)
if admin_role:
overwrites[admin_role] = discord.PermissionOverwrite(view_channel=True, send_messages=True)
channel = await guild.create_text_channel(
name=f"ticket-{user.name}".replace(" ", "-").lower()[:50],
category=category if isinstance(category, discord.CategoryChannel) else None,
overwrites=overwrites,
topic=f"Support ticket for {user} ({user.id})"
)
async with aiosqlite.connect("bot_database.db") as db:
await db.execute(
"INSERT INTO tickets (channel_id, user_id, guild_id) VALUES (?, ?, ?)",
(channel.id, user.id, guild.id)
)
await db.commit()
embed = create_embed(
title="🎫 Support Ticket",
description=(
f"Welcome {user.mention}!\n\n"
f"Please describe your issue below.\n"
f"A staff member will assist you shortly.\n\n"
f"Click 🔒 **Close Ticket** when done."
),
color=discord.Color.green(),
footer=f"Ticket by {user.name}"
)
await channel.send(user.mention, embed=embed, view=TicketControlView())
await interaction.response.send_message(f"✅ Ticket created: {channel.mention}", ephemeral=True)
# ══════════════════════════════════════════════════════════════════════════════
# COLOR ROLE PANEL (BUTTON-BASED) - NEW
# ══════════════════════════════════════════════════════════════════════════════
class ColorRoleButton(discord.ui.Button):
def __init__(self, role_id: int, label: str, emoji: str, style: int):
button_styles = {
1: discord.ButtonStyle.primary,
2: discord.ButtonStyle.secondary,
3: discord.ButtonStyle.success,
4: discord.ButtonStyle.danger
}
super().__init__(
label=label,
emoji=emoji,
style=button_styles.get(style, discord.ButtonStyle.primary),
custom_id=f"colorrole:{role_id}"
)
self.role_id = role_id
async def callback(self, interaction: discord.Interaction):
role = interaction.guild.get_role(self.role_id)
if not role:
return await interaction.response.send_message("❌ Role not found!", ephemeral=True)
member = interaction.user
# Remove other color roles from this panel first
async with aiosqlite.connect("bot_database.db") as db:
cursor = await db.execute(
"SELECT role_id FROM color_roles WHERE guild_id = ?",
(interaction.guild.id,)
)
all_color_roles = [r[0] for r in await cursor.fetchall()]
roles_to_remove = [interaction.guild.get_role(rid) for rid in all_color_roles
if rid != self.role_id and interaction.guild.get_role(rid) in member.roles]
roles_to_remove = [r for r in roles_to_remove if r]
if roles_to_remove:
await member.remove_roles(*roles_to_remove)
if role in member.roles:
await member.remove_roles(role)
await interaction.response.send_message(f"✅ Removed **{role.name}**", ephemeral=True)
else:
await member.add_roles(role)
await interaction.response.send_message(f"✅ Added **{role.name}**", ephemeral=True)
class ColorRolePanelView(discord.ui.View):
def __init__(self, roles_data):
super().__init__(timeout=None)
for role_id, label, emoji, style in roles_data:
self.add_item(ColorRoleButton(role_id, label, emoji, style))
# ══════════════════════════════════════════════════════════════════════════════
# MARKETPLACE VIEWS - NEW
# ══════════════════════════════════════════════════════════════════════════════
class MarketPageView(discord.ui.View):
def __init__(self, pages, current_page=0, author_id=None):
super().__init__(timeout=120)
self.pages = pages
self.current_page = current_page
self.author_id = author_id
@discord.ui.button(label="◀", style=discord.ButtonStyle.secondary)
async def prev_page(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.user.id != self.author_id:
return await interaction.response.send_message("❌ Not your menu!", ephemeral=True)
self.current_page = (self.current_page - 1) % len(self.pages)
await interaction.response.edit_message(embed=self.pages[self.current_page], view=self)
@discord.ui.button(label="▶", style=discord.ButtonStyle.secondary)
async def next_page(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.user.id != self.author_id:
return await interaction.response.send_message("❌ Not your menu!", ephemeral=True)
self.current_page = (self.current_page + 1) % len(self.pages)
await interaction.response.edit_message(embed=self.pages[self.current_page], view=self)
# ══════════════════════════════════════════════════════════════════════════════
# BOT EVENTS
# ══════════════════════════════════════════════════════════════════════════════
@bot.event
async def on_ready():
await init_database()
await seed_market_items()
print(f"{'═' * 50}")
print(f"🤖 Bot: {bot.user.name}")
print(f"🆔 ID: {bot.user.id}")
print(f"📊 Servers: {len(bot.guilds)}")
print(f"👥 Users: {sum(g.member_count for g in bot.guilds)}")
print(f"{'═' * 50}")
# Sync slash commands
try:
synced = await bot.tree.sync()
print(f"✅ Synced {len(synced)} slash commands")
except Exception as e:
print(f"❌ Failed to sync commands: {e}")
# Register persistent views
bot.add_view(TicketPanelView())
bot.add_view(TicketControlView())
# Load color role panels
async with aiosqlite.connect("bot_database.db") as db:
cursor = await db.execute("SELECT role_id, label, emoji, style FROM color_roles WHERE guild_id IS NOT NULL")
rows = await cursor.fetchall()
if rows:
bot.add_view(ColorRolePanelView(rows))
# Start background tasks
check_reminders.start()
check_giveaways.start()
update_status.start()
# Load reaction roles and custom commands
await load_reaction_roles()
await load_custom_commands()
# Connect to music VC if configured
if WAVELINK_AVAILABLE and CONFIG["MUSIC_ENABLED"]:
try:
node = wavelink.Node(uri=CONFIG["LAVALINK_URI"], password=CONFIG["LAVALINK_PASSWORD"])
await wavelink.Pool.connect(client=bot, nodes=[node])
print("✅ Connected to Lavalink node")
except Exception as e:
print(f"⚠️ Lavalink connection failed: {e}")
print(" Music features will be unavailable until Lavalink is running.")
@bot.event
async def on_member_join(member):
if not CONFIG["WELCOME_ENABLED"]:
return
if CONFIG.get("AUTO_ROLE"):
role = member.guild.get_role(CONFIG["AUTO_ROLE"])
if role:
try:
await member.add_roles(role)
except:
pass
if CONFIG.get("WELCOME_CHANNEL"):
channel_id = await get_guild_setting(member.guild.id, "welcome_channel")
channel = member.guild.get_channel(channel_id) if channel_id else None
if channel:
embed = create_embed(
title="👋 Welcome!",
description=f"Welcome to **{member.guild.name}**, {member.mention}!\n\n"
f"You are member **#{member.guild.member_count}**",
color=discord.Color.green(),
thumbnail=member.display_avatar.url
)
embed.add_field(name="Account Created", value=f"<t:{int(member.created_at.timestamp())}:R>", inline=True)
await channel.send(embed=embed)
log_embed = create_embed(
title="📥 Member Joined",
description=f"{member.mention} ({member.name})",
color=discord.Color.green(),
fields=[
("Account Age", f"<t:{int(member.created_at.timestamp())}:R>", True),
("Member Count", str(member.guild.member_count), True)
]
)
await log_action(member.guild, log_embed)
@bot.event
async def on_member_remove(member):
if not CONFIG["WELCOME_ENABLED"]:
return
if CONFIG.get("LEAVE_CHANNEL"):
channel_id = await get_guild_setting(member.guild.id, "leave_channel")
channel = member.guild.get_channel(channel_id) if channel_id else None
if channel:
embed = create_embed(
title="👋 Goodbye!",
description=f"**{member.name}** has left the server.\n"
f"We now have **{member.guild.member_count}** members.",
color=discord.Color.red(),
thumbnail=member.display_avatar.url
)
await channel.send(embed=embed)
log_embed = create_embed(
title="📤 Member Left",
description=f"{member.name}#{member.discriminator}",
color=discord.Color.red()
)
await log_action(member.guild, log_embed)
@bot.event
async def on_message(message):
if message.author.bot:
return
# Check AFK
if message.author.id in afk_users:
del afk_users[message.author.id]
await message.channel.send(
f"Welcome back {message.author.mention}! I've removed your AFK status.",
delete_after=5
)
for user in message.mentions:
if user.id in afk_users:
afk_data = afk_users[user.id]
await message.channel.send(
f"💤 **{user.name}** is AFK: {afk_data['reason']} - <t:{int(afk_data['time'])}:R>",
delete_after=10
)
# Custom commands
if message.content.startswith(CONFIG["PREFIX"]):
cmd_name = message.content[len(CONFIG["PREFIX"]):].split()[0].lower()
if cmd_name in custom_commands:
await message.channel.send(custom_commands[cmd_name])
async with aiosqlite.connect("bot_database.db") as db:
await db.execute(
"UPDATE custom_commands SET uses = uses + 1 WHERE name = ?",
(cmd_name,)
)
await db.commit()
# Auto-mod
if CONFIG["AUTOMOD_ENABLED"] and message.guild and not message.author.guild_permissions.administrator:
if CONFIG["ANTI_SPAM_ENABLED"]:
now = time.time()
spam_tracker[message.author.id].append(now)
spam_tracker[message.author.id] = [
t for t in spam_tracker[message.author.id]
if now - t < CONFIG["SPAM_INTERVAL"]