forked from Comon-tech/TACT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
1403 lines (1165 loc) · 54.7 KB
/
app.py
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 asyncio
import re
import time
import discord # type: ignore
from discord import app_commands # type: ignore
from discord.ext import commands # type: ignore
import dotenv # type: ignore
import os # type: ignore
import random
from bad_words import check_for_bad_words, split_msg_into_array, offensive_words
from db import user_collection, store_collection
from datetime import datetime, timedelta
from discord.ui import View, Button
from math import ceil
from collections import Counter, defaultdict
from gemini import generate_content
dotenv.load_dotenv()
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="/", intents=intents)
# Store user offenses count
user_offenses = defaultdict(int)
# Penalty system (e.g., lose 50 coins or XP after 5 offenses)
PENALTY_THRESHOLD = 5
PENALTY_AMOUNT = 50 # Amount of coins or XP to be deducted
# Cooldown tracker
shoot_cooldowns = {}
rob_cooldowns = {}
heist_participants = []
badge_list = ["🔧", "🔥", "🌟", "👨💻", "🤓", "👾", "🧙", "🔱", "🧙♂️", "👸"]
# Track last claim times in a database or dictionary
last_daily_claim = {}
# Track last hourly claim times in a database or dictionary
last_hourly_claim = {}
async def random_xp_drop():
while True:
await asyncio.sleep(random.randint(3600, 7200)) # 1-2 hours
channel = bot.get_channel("998348764282634242")
reward = random.randint(50, 150)
lucky_user = random.choice(channel.members)
user_data = get_user_data(str(lucky_user.id))
user_data["xp"] += reward
save_user_data(str(lucky_user.id), user_data)
await channel.send(f"🎉 Surprise! {lucky_user.mention} just earned {reward} XP!")
def get_user_data(user_id):
user_data = user_collection.find_one({"user_id": user_id})
if not user_data:
user_data = {"user_id": user_id, "xp": 0, "level": 1, "inventory": [], "balance": 0}
user_collection.insert_one(user_data)
return user_data
def save_user_data(user_id, data):
user_collection.update_one(
{"user_id": user_id},
{"$set": data},
upsert=True
)
print(f"User {user_id} data saved: {data}\n\n")
def award_xp(user_id, xp):
user_data = get_user_data(user_id)
user_data["xp"] += xp
# Level up if XP exceeds the threshold
while user_data["xp"] >= get_xp_needed(user_data["level"]):
user_data["level"] += 1
print(f"User {user_id} leveled up to {user_data['level']}!, with {user_data['xp']} XPs. \n\n")
save_user_data(user_id, user_data)
return user_data
# Function to provide autocomplete options
async def item_autocomplete(interaction: discord.Interaction, current: str):
# Fetch item names from the database and filter based on the user's input
all_items = [item["item_name"] for item in store_collection.find()]
matching_items = [app_commands.Choice(name=item, value=item) for item in all_items if current.lower() in item.lower()]
return matching_items[:25] # Return up to 25 matches (Discord's limit)
@bot.event
async def on_ready():
# load_data()
print(f"TACT Bot is ready! Logged in as {bot.user}")
try:
synced = await bot.tree.sync()
print(f"synced {len(synced)} command(s)")
except Exception as e:
print(e)
def get_xp_needed(level):
# XP needed for next level should be more than the previous level and have a gap of 1000
# return 5 * (level ** 2) + 50 * level + 100
return 1000 + (level - 1) ** 2 * 1000
# Function to deduct XP
async def apply_penalty(user):
user_id = str(user.id)
user_data = get_user_data(user_id) # Fetch user data from database
if not user_data:
return
# Deduct the penalty amount
user_data["xp"] -= PENALTY_AMOUNT # Deduct XP
save_user_data(user_id, user_data) # Save the updated user data
# Notify the user about the penalty
await user.send(f"🚨 ***You have used offensive words too many times. You have been penalized `{PENALTY_AMOUNT}` XP!***")
def remove_links(message):
"""
Remove URLs (e.g., GIF links) from a message.
"""
# Regex to match URLs
url_pattern = r"(https?://\S+)"
return re.sub(url_pattern, "", message).strip()
@bot.event
async def on_message(message):
# Ignore bot messages
if message.author.bot:
return
member = message.author
guild = message.guild
user_data = get_user_data(str(member.id))
current_nick = member.display_name
if user_data["level"] in range(1, 3):
role = discord.utils.get(guild.roles, name="Intermediate")
#only assign role if the user doesn't have it
if role not in member.roles:
await member.add_roles(role)
try:
for badge in badge_list:
if badge in current_nick:
print(f"Badge: {badge} is already in the nickname")
current_nick = current_nick.replace(badge, "")
print(f"replace badge: {badge} with empty string")
intermediate_badge = "🔥"
new_nick = current_nick + intermediate_badge
await member.edit(nick=new_nick)
except discord.Forbidden:
print(f"Failed to update nickname for {member.name} (insufficient permissions).")
except discord.HTTPException as e:
print(f"Error updating nickname for {member.name}: {e}")
#award XP to the user
xp_earned = random.randint(5, 10)
award_xp(str(member.id), xp_earned)
#send this message to the channel
await message.channel.send(f"🎉🎉🎉 **Role UP** \n{member.mention} has been awarded the **{role.name}** role and has been awarded **{xp_earned}**XPs!")
elif user_data["level"] in range(4, 9):
role = discord.utils.get(guild.roles, name="Novice")
#only assign role if the user doesn't have it
if role not in member.roles:
await member.add_roles(role)
try:
for badge in badge_list:
if badge in current_nick:
print(f"Badge: {badge} is already in the nickname")
current_nick = current_nick.replace(badge, "")
novice_badge = "🌟"
new_nick = current_nick + novice_badge
await member.edit(nick=new_nick)
except discord.Forbidden:
print(f"Failed to update nickname for {member.name} (insufficient permissions).")
except discord.HTTPException as e:
print(f"Error updating nickname for {member.name}: {e}")
#award XP to the user
xp_earned = random.randint(5, 10)
award_xp(str(member.id), xp_earned)
#send this message to the channel
await message.channel.send(f"🎉🎉🎉 **Role UP** \n{member.mention} has been awarded the **{role.name}** role and has been awarded **{xp_earned}**XPs!")
elif user_data["level"] in range(11, 16):
role = discord.utils.get(guild.roles, name="Techie")
#only assign role if the user doesn't have it
if role not in member.roles:
await member.add_roles(role)
try:
for badge in badge_list:
if badge in current_nick:
print(f"Badge: {badge} is already in the nickname")
current_nick = current_nick.replace(badge, "")
techie_badge = "👨💻"
new_nick = current_nick + techie_badge
await member.edit(nick=new_nick)
except discord.Forbidden:
print(f"Failed to update nickname for {member.name} (insufficient permissions).")
except discord.HTTPException as e:
print(f"Error updating nickname for {member.name}: {e}")
#award XP to the user
xp_earned = random.randint(5, 10)
award_xp(str(member.id), xp_earned)
#send this message to the channel
await message.channel.send(f"🎉🎉🎉 **Role UP** \n{member.mention} has been awarded the **{role.name}** role and has been awarded **{xp_earned}**XPs!")
elif user_data["level"] in range(17, 23):
role = discord.utils.get(guild.roles, name="Geek")
print(f"User {member.name} is at level {user_data['level']}")
#only assign role if the user doesn't have it
if role not in member.roles:
await member.add_roles(role)
try:
for badge in badge_list:
if badge in current_nick:
print(f"Badge: {badge} is already in the nickname")
current_nick = current_nick.replace(badge, "")
geek_badge = "🤓"
new_nick = current_nick + geek_badge
await member.edit(nick=new_nick)
print(f"Updated nickname for {member.name} to '{new_nick}'")
except discord.Forbidden:
print(f"Failed to update nickname for {member.name} (insufficient permissions).")
except discord.HTTPException as e:
print(f"Error updating nickname for {member.name}: {e}")
#award XP to the user
xp_earned = random.randint(5, 10)
award_xp(str(member.id), xp_earned)
#send this message to the channel
await message.channel.send(f"🎉🎉🎉 **Role UP** \n{member.mention} has been awarded the **{role.name}** role and has been awarded **{xp_earned}**XPs!")
elif user_data["level"] in range(24, 30):
role = discord.utils.get(guild.roles, name="Hacker")
#only assign role if the user doesn't have it
if role not in member.roles:
await member.add_roles(role)
try:
for badge in badge_list:
if badge in current_nick:
print(f"Badge: {badge} is already in the nickname")
current_nick = current_nick.replace(badge, "")
hacker_badge = "👾"
new_nick = current_nick + hacker_badge
await member.edit(nick=new_nick)
print(f"Updated nickname for {member.name} to '{new_nick}'")
except discord.Forbidden:
print(f"Failed to update nickname for {member.name} (insufficient permissions).")
except discord.HTTPException as e:
print(f"Error updating nickname for {member.name}: {e}")
#award XP to the user
xp_earned = random.randint(5, 10)
award_xp(str(member.id), xp_earned)
#send this message to the channel
await message.channel.send(f"🎉🎉🎉 **Role UP** \n{member.mention} has been awarded the **{role.name}** role and has been awarded **{xp_earned}**XPs !")
elif user_data["level"] in range(31, 37):
role = discord.utils.get(guild.roles, name="Guru")
#only assign role if the user doesn't have it
if role not in member.roles:
await member.add_roles(role)
try:
for badge in badge_list:
if badge in current_nick:
print(f"Badge: {badge} is already in the nickname")
current_nick = current_nick.replace(badge, "")
guru_badge = "🧙"
new_nick = current_nick + guru_badge
await member.edit(nick=new_nick)
except discord.Forbidden:
print(f"Failed to update nickname for {member.name} (insufficient permissions).")
except discord.HTTPException as e:
print(f"Error updating nickname for {member.name}: {e}")
#award XP to the user
xp_earned = random.randint(5, 10)
award_xp(str(member.id), xp_earned)
#send this message to the channel
await message.channel.send(f"🎉🎉🎉 **Role UP** \n{member.mention} has been awarded the **{role.name}** role and has been awarded **{xp_earned}**XPs!")
elif user_data["level"] in range(43, 49):
role = discord.utils.get(guild.roles, name="Godlike")
#only assign role if the user doesn't have it
if role not in member.roles:
await member.add_roles(role)
try:
for badge in badge_list:
if badge in current_nick:
print(f"Badge: {badge} is already in the nickname")
current_nick = current_nick.replace(badge, "")
godlike_badge = "🔱"
new_nick = current_nick + godlike_badge
await member.edit(nick=new_nick)
except discord.Forbidden:
print(f"Failed to update nickname for {member.name} (insufficient permissions).")
except discord.HTTPException as e:
print(f"Error updating nickname for {member.name}: {e}")
#award XP to the user
xp_earned = random.randint(5, 10)
award_xp(str(member.id), xp_earned)
#send this message to the channel
await message.channel.send(f"🎉🎉🎉 **Role UP** \n{member.mention} has been awarded the **{role.name}** role and has been awarded **{xp_earned}**XPs!")
elif user_data["level"] in range(55, 61):
role = discord.utils.get(guild.roles, name="Wizard")
#only assign role if the user doesn't have it
if role not in member.roles:
await member.add_roles(role)
try:
for badge in badge_list:
if badge in current_nick:
print(f"Badge: {badge} is already in the nickname")
current_nick = current_nick.replace(badge, "")
wizard_badge = "🧙♂️"
new_nick = current_nick + wizard_badge
await member.edit(nick=new_nick)
except discord.Forbidden:
print(f"Failed to update nickname for {member.name} (insufficient permissions).")
except discord.HTTPException as e:
print(f"Error updating nickname for {member.name}: {e}")
#award XP to the user
xp_earned = random.randint(5, 10)
award_xp(str(member.id), xp_earned)
#send this message to the channel
await message.channel.send(f"🎉🎉🎉 **Role UP** \n{member.mention} has been awarded the **{role.name}** role and has been awarded **{xp_earned}**XPs!")
#rename the user's name to include the special badge
for word in offensive_words:
if word in [message for message in message.content.split(" ")]:
await message.delete()
await message.channel.send(
f"🛑 {message.author.mention}: ||{message.content}||"
)
# Increase the offense count
user_offenses[message.author.id] += 1
if user_offenses[message.author.id] >= PENALTY_THRESHOLD:
await apply_penalty(message.author)
await message.channel.send(f"🚨 {message.author.mention} ***has been penalized `{PENALTY_AMOUNT}` XPs for using offensive words too many times!!.***")
# Reset the offense count after penalty
user_offenses[message.author.id] = 0
user_id = str(message.author.id)
user_data = get_user_data(user_id)
xp_needed = get_xp_needed(user_data["level"])
# Award random XP between 5 and 10
xp_earned = random.randint(5, 100)
print(f"User {message.author.name} earned {xp_earned} XP!\n\n")
award_xp(user_id, xp_earned)
await bot.process_commands(message) # Ensure other commands can still run
# Leaderboard command
@bot.tree.command(name="leaderboard", description="Get the TACT leaderboard")
async def leaderboard(interaction: discord.Interaction):
# Acknowledge the interaction
await interaction.response.defer() # Keeps the interaction alive
# Fetch users sorted by level (descending) and XP (descending) for tiebreaker
sorted_users = list(user_collection.find().sort([("level", -1), ("xp", -1)]))
if not sorted_users:
await interaction.followup.send("No users found in the leaderboard.")
return
# Create an embed for the leaderboard
embed = discord.Embed(
title="🏆 TACT Leaderboard",
color=discord.Color.gold()
)
for i, user_data in enumerate(sorted_users[:10]): # Top 10 users
try:
# Fetch the user's Discord info
user = await bot.fetch_user(int(user_data["user_id"]))
user_display = user.name
except Exception:
# If the user is not found (e.g., left the server), use their ID
user_display = f"Unknown User ({user_data['user_id']})"
# Add the user to the leaderboard
embed.add_field(
#display user avatar next to their name
name=f"{i+1}. {user_display} ",
value=f"Level: {user_data['level']} | XP: {user_data['xp']} \n[Avatar]({user.display_avatar.url})",
inline=False
)
await interaction.followup.send(embed=embed)
@bot.tree.command(name="level", description="Get a user's TACT level")
async def level(interaction: discord.Interaction, user: discord.Member = None):
# Use the mentioned user if provided, otherwise default to the command invoker
user = user or interaction.user
user_id = str(user.id)
# Fetch the user's data from the database
user_data = get_user_data(user_id)
level = user_data.get("level", 1)
xp = user_data.get("xp", 0)
# Build an embed with the level information
embed = discord.Embed(
title=f"{user.display_name}'s Level",
description=f"**Level:** {level}\n**XP:** {xp} / {get_xp_needed(level + 1)}",
color=discord.Color.blue()
)
embed.set_thumbnail(url=user.display_avatar.url)
# Send the response
await interaction.response.send_message(embed=embed)
@bot.tree.command(name="give_xp", description="Give some XPs to your friends!")
async def give_xp(interaction: discord.Interaction, member: discord.Member, xp: int):
interaction.response.defer()
# Validate input
if xp <= 0:
await interaction.response.send_message("XP must be a positive number.")
return
# Retrieve user data
user_id = str(member.id)
user_data = get_user_data(user_id)
if not user_data:
await interaction.response.send_message("User not found!")
return
#check if user is trying to give themselves XP
if interaction.user == member:
embed = discord.Embed(
title="❌ XP Not Awarded!!",
description="You can't give yourself XP!",
color=discord.Color.red()
)
embed.set_thumbnail(url=member.display_avatar.url)
await interaction.response.send_message(embed=embed)
return
# Add XP and update user data
user_data["xp"] = user_data.get("xp", 0) + xp
save_user_data(user_id, user_data)
# Create the response embed
embed = discord.Embed(
title="✅ XP Awarded",
description=(
f"{interaction.user.mention} has awarded **{xp} XP** to {member.mention}!\n"
f"**{member.display_name}** now has **{user_data['xp']} XP**."
),
color=discord.Color.green()
)
embed.set_thumbnail(url=member.display_avatar.url)
# Respond with confirmation
await interaction.response.send_message(embed=embed)
@bot.tree.command(name="gift", description="Gift an item to another user.")
@app_commands.describe(item="The item you want to purchase")
@app_commands.autocomplete(item=item_autocomplete)
async def gift(interaction: discord.Interaction, recipient: discord.Member, *, item: str):
giver_id = str(interaction.user.id)
recipient_id = str(recipient.id)
# Prevent self-gifting
if giver_id == recipient_id:
embed = discord.Embed(
title=f"Gift {recipient.display_name}",
description=f"**❌ You can't gift items to yourself.**",
color=discord.Color.gold()
)
embed.set_thumbnail(url=recipient.display_avatar.url)
await interaction.response.send_message(embed=embed)
return
# Fetch giver and recipient data
giver_data = get_user_data(giver_id)
recipient_data = get_user_data(recipient_id)
# Validate giver's inventory
if not giver_data or "inventory" not in giver_data:
embed = discord.Embed(
title=f"Gift {recipient.display_name}",
description=f"**❌ You don't have an inventory to gift from.**",
color=discord.Color.gold()
)
embed.set_thumbnail(url=recipient.display_avatar.url)
await interaction.response.send_message(embed=embed)
return
# Ensure recipient data exists
if not recipient_data:
recipient_data = {"user_id": recipient_id, "balance": 0, "xp": 0, "level": 1, "inventory": []}
giver_inventory = giver_data.get("inventory", [])
# Check if the giver owns the item
if item not in giver_inventory:
embed = discord.Embed(
title=f"Gift {recipient.display_name}",
description=f"**❌ You don't own an item called {item}.**",
color=discord.Color.gold()
)
embed.set_thumbnail(url=recipient.display_avatar.url)
await interaction.response.send_message(embed=embed)
return
# Update giver's inventory
giver_inventory.remove(item)
giver_data["inventory"] = giver_inventory
# Update recipient's inventory
recipient_inventory = recipient_data.get("inventory", [])
recipient_inventory.append(item)
recipient_data["inventory"] = recipient_inventory
# Save data to database
save_user_data(giver_id, giver_data) # Update giver in the database
save_user_data(recipient_id, recipient_data) # Update recipient in the database
# Confirm the gift
embed = discord.Embed(
title="🎁 Gift Successful!",
description=(
f"{interaction.user.mention} has gifted **{item}** to {recipient.mention}!\n"
f"Check your inventory to see the updated items."
),
color=discord.Color.green()
)
embed.set_thumbnail(url=recipient.display_avatar.url)
await interaction.response.send_message(embed=embed)
@gift.error
async def gift_error(ctx, error):
member: discord.Member
if isinstance(error, commands.BadArgument, ):
embed = discord.Embed(
title=f"Gift error",
description=f"**❌ Invalid arguments. Usage: `/gift @User item_name`**",
color=discord.Color.gold()
)
embed.set_thumbnail(url=ctx.author.display_avatar.url)
await ctx.send(embed=embed)
else:
embed = discord.Embed(
title=f"Gift error",
description=f"**❌ An error occurred while processing the gift.**",
color=discord.Color.gold()
)
embed.set_thumbnail(url=ctx.author.display_avatar.url)
await ctx.send(embed=embed)
user_id = str(member.id)
user_data = get_user_data(user_id)
if user_id in user_data:
user_data[user_id] = {"xp": 0, "level": 1}
await ctx.send(f"✅ {member.mention}'s XP has been reset.")
else:
await ctx.send(f"{member.mention} has no XP data to reset.")
save_user_data(user_id, user_data) # Save the data
@bot.tree.command(name="balance", description="Check your or another user's balance.")
async def balance(interaction: discord.Interaction, user: discord.Member = None):
# Use the command invoker if no user is mentioned
user = user or interaction.user
# Get user data from the database
user_id = str(user.id)
user_data = get_user_data(user_id) # Replace with your database query function
# Ensure the user exists in the database
if not user_data:
user_data = {"xp": 0} # Default xp if user is not yet in the database
save_user_data(user_id, user_data) # Optionally initialize the user in the database
# Fetch xp
balance = user_data.get("xp", 0)
# Create response
embed = discord.Embed(
title=f"{user.display_name}'s Balance",
description=f"💰 **{balance} XPs**",
color=discord.Color.gold()
)
embed.set_thumbnail(url=user.display_avatar.url)
# Send the response
await interaction.response.send_message(embed=embed)
@bot.tree.command(name="inventory", description="Check the items in your inventory or someone else's.")
async def inventory(interaction: discord.Interaction, user: discord.Member = None):
# Use the command invoker if no user is mentioned
user = user or interaction.user
user_id = str(user.id) # Use the mentioned user's ID
user_data = get_user_data(user_id) # Fetch the correct user's data
if not user_data or "inventory" not in user_data or not user_data["inventory"]:
embed = discord.Embed(
title="🎒 Inventory",
description=(
f"{user.mention}, their inventory is empty." if user != interaction.user else
f"{user.mention}, your inventory is empty."
),
color=discord.Color.gold()
)
embed.set_thumbnail(url=user.display_avatar.url)
await interaction.response.send_message(embed=embed)
return
inventory_items = user_data["inventory"]
item_counts = Counter(inventory_items) # Count occurrences of each item
# Format the inventory to show "Item XCount"
formatted_inventory = "\n".join(
f"{item} x{count}" for item, count in item_counts.items()
)
embed = discord.Embed(
title=f"{user.display_name}'s Inventory:",
description=f"**{formatted_inventory}**",
color=discord.Color.gold()
)
embed.set_thumbnail(url=user.display_avatar.url)
await interaction.response.send_message(embed=embed)
@bot.tree.command(name="rob_bank", description="Attempt to rob a bank! High risk, high reward.")
async def rob_bank(interaction: discord.Interaction):
user_id = str(interaction.user.id)
user_data = get_user_data(user_id)
# Ensure the user exists in the database
if not user_data:
user_data = {"xp": 0, "last_rob": None}
save_user_data(user_id, user_data)
# Check cooldown
now = datetime.utcnow()
last_rob = user_data.get("last_rob")
cooldown_time = timedelta(hours=1) # Set cooldown to 1 hour
if last_rob and now - last_rob < cooldown_time:
remaining_time = cooldown_time - (now - last_rob)
await interaction.response.send_message(
f"⏳ You need to wait {remaining_time.seconds // 60} minutes before trying again!",
ephemeral=True
)
return
# Set success rate and rewards/penalties
success_chance = 0.5 # 50% chance of success
success_amount = random.randint(100, 500) # XPs gained on success
failure_penalty = random.randint(50, 300) # XPs lost on failure
# Check for "🚗 Escape Car" in inventory
has_escape_car = "🚗 Escape Car" in user_data["inventory"]
if has_escape_car:
success_chance = 0.75 # Tripled success chance
success_amount = random.randint(500, 1500) # Tripled reward
# Remove the Escape Car from the inventory
user_data["inventory"].remove("🚗 Escape Car")
# Attempt robbery
if random.random() < success_chance:
# Success: Add XPs
user_data["xp"] += success_amount
if has_escape_car:
result_message = (f"🚗 The **Escape Car** tripled your heist to **{success_amount} XPs**! The car is now used up.")
else:
result_message = f"🎉 Success! You managed to rob the bank and got **{success_amount} XPs**!"
else:
# Failure: Deduct XPs
if user_data["xp"] >= failure_penalty:
user_data["xp"] -= failure_penalty
else:
failure_penalty = user_data["xp"]
user_data["xp"] = 0
result_message = (
f"🚨 You got caught trying to rob the bank and lost **{failure_penalty} XPs**. Better luck next time!"
)
# Update last rob time and save data
user_data["last_rob"] = now
save_user_data(user_id, user_data)
# Send response
embed = discord.Embed(
title="💰 Rob Bank Results",
description=result_message,
color=discord.Color.red() if "caught" in result_message else discord.Color.green()
)
embed.set_thumbnail(url=interaction.user.display_avatar.url)
await interaction.response.send_message(embed=embed)
# Buy command with autocomplete and quantity
@bot.tree.command(name="buy", description="Buy items from the shop")
@app_commands.describe(item="The item you want to purchase", quantity="The number of items you want to buy (default: 1)")
@app_commands.autocomplete(item=item_autocomplete)
async def buy(interaction: discord.Interaction, item: str, quantity: int = 1):
user_id = str(interaction.user.id)
user_data = get_user_data(user_id)
# Fetch store items and prices
store_items = {item_data["item_name"]: item_data["item_price"] for item_data in store_collection.find()}
# Check if the item exists in the store
item_price = store_items.get(item)
if item_price is None:
embed = discord.Embed(
title="🛒 Purchase Unsuccessful !!",
description=f"❌ {item} is not available in the store.",
color=discord.Color.red()
)
embed.set_thumbnail(url=interaction.user.display_avatar.url)
await interaction.response.send_message(embed=embed)
return
# Validate quantity
if quantity <= 0:
embed = discord.Embed(
title="🛒 Purchase Unsuccessful !!",
description="❌ Quantity must be a positive number greater than zero.",
color=discord.Color.red()
)
embed.set_thumbnail(url=interaction.user.display_avatar.url)
await interaction.response.send_message(embed=embed)
return
# Calculate total cost
total_cost = int(item_price) * quantity
# Check if the user has enough XP
if user_data["xp"] < total_cost:
embed = discord.Embed(
title="🛒 Purchase Unsuccessful !!",
description=f"❌ You need {total_cost} XP to buy {quantity} x {item}.",
color=discord.Color.red()
)
embed.set_thumbnail(url=interaction.user.display_avatar.url)
await interaction.response.send_message(embed=embed)
return
# Deduct XP and add items to inventory
user_data["xp"] -= total_cost
user_data["inventory"].extend([item] * quantity)
# Send success message
embed = discord.Embed(
title="🛒 Purchase Successful",
description=(
f"✅ {interaction.user.mention} bought {quantity} x {item} for {total_cost} XP.\n"
f"💰 Remaining XP: {user_data['xp']}"
),
color=discord.Color.green()
)
embed.set_thumbnail(url=interaction.user.display_avatar.url)
await interaction.response.send_message(embed=embed)
# Save updated user data
save_user_data(user_id, user_data)
def steal_function(victim_id):
# Fetch victim data
victim = get_user_data(victim_id)
stolen_amount = random.randint(50, 2000) # Steal between 50 and 200 XPs
stolen_amount = min(stolen_amount, victim["xp"]) # Can't steal more than the victim's balance
return stolen_amount
@bot.tree.command(name="steal", description="Attempt to steal from another user.")
async def steal(interaction: discord.Interaction, target: discord.Member):
thief_id = str(interaction.user.id) #'673eb3f1491a384eb6545a19'
victim_id = str(target.id)
# Ensure thief isn't targeting themselves
if thief_id == victim_id:
embed = discord.Embed(
title="🔫 Steal Results",
description="🔫 You can't steal from yourself",
color=discord.Color.red()
)
embed.set_thumbnail(url=interaction.user.display_avatar.url)
await interaction.response.send_message(embed=embed, ephemeral=True)
return
# Fetch thief and victim data
thief = get_user_data(thief_id)
victim = get_user_data(victim_id)
# Cooldown logic
cooldown = 3600 # 1 hour cooldown in seconds
current_time = int(time.time())
time_since_last_steal = current_time - thief.get("last_steal", 0)
if time_since_last_steal < cooldown:
remaining_time = cooldown - time_since_last_steal
embed = discord.Embed(
title="🔫 Steal Results",
description=f"⏳ You need to wait {remaining_time // 60} minutes before stealing again!",
color=discord.Color.red()
)
embed.set_thumbnail(url=interaction.user.display_avatar.url)
await interaction.response.send_message(
f"⏳ You need to wait {remaining_time // 60} minutes before stealing again!",
ephemeral=True
)
return
# Chance of success
success_rate = 0.7 # 70% chance to succeed
success = random.random() < success_rate
if success:
stolen_amount = steal_function(victim_id)
if stolen_amount == 0:
embed = discord.Embed(
title="🔫 Steal Results",
description=f"❌ {target.mention} has no XPs to steal!",
color=discord.Color.red()
)
embed.set_thumbnail(url=interaction.user.display_avatar.url)
await interaction.response.send_message(embed=embed)
return
# Update balances
thief["xp"] += stolen_amount
victim["xp"] -= stolen_amount
# Update timestamps and save
thief["last_steal"] = current_time
save_user_data(thief_id, thief)
save_user_data(victim_id, victim)
embed = discord.Embed(
title="🔫 Steal Results",
description=f"🎉 You successfully stole `{stolen_amount}` XPs from {target.mention}!",
color=discord.Color.red()
)
embed.set_thumbnail(url=interaction.user.display_avatar.url)
await interaction.response.send_message(embed=embed)
else:
# Failed attempt penalty
penalty = random.randint(20, 100) # Lose between 20 and 100 XPs
thief["xp"] -= penalty
thief["xp"] = max(thief["xp"], 0) # Prevent negative xp
# Update timestamps and save
thief["last_steal"] = current_time
save_user_data(thief_id, thief)
await interaction.response.send_message(
f"❌ You got caught and lost `{penalty}` XPs as a penalty!"
)
@bot.tree.command(name="shoot", description="Shoot another user for a chance to win XPs!")
async def shoot(interaction: discord.Interaction, target: discord.Member):
attacker_id = str(interaction.user.id)
target_id = str(target.id)
# Prevent self-targeting
if interaction.user == target:
embed = discord.Embed(
title="🔫 Shoot Results",
description="🔫 You can't shoot yourself.",
color=discord.Color.red()
)
embed.set_thumbnail(url=interaction.user.display_avatar.url)
await interaction.response.send_message(embed=embed, ephemeral=True)
return
# Retrieve attacker and target data
attacker_data = get_user_data(attacker_id)
target_data = get_user_data(target_id)
if not attacker_data or not target_data:
embed = discord.Embed(
title="🔫 Shoot Results",
description="🔍 Both users must be registered to participate!",
color=discord.Color.red()
)
embed.set_thumbnail(url=interaction.user.display_avatar.url)
await interaction.response.send_message(embed=embed, ephemeral=True)
return
# Check if attacker has bullets in inventory (handling inventory as a list)
inventory = attacker_data.get("inventory", [])
bullet_count = sum(1 for item in inventory if item == "✏ Bullet")
if bullet_count < 1:
embed = discord.Embed(
title="🔫 Shoot Results",
description="❌ You don't have any bullets to shoot. Buy some from the store!",
color=discord.Color.red()
)
embed.set_thumbnail(url=interaction.user.display_avatar.url)
await interaction.response.send_message(embed=embed, ephemeral=True)
return
# Remove one bullet from inventory
inventory.remove("✏ Bullet")
attacker_data["inventory"] = inventory
# Check if target has the shield
target_inventory = target_data.get("inventory", [])
if "🛡 Shield of Protection" in target_inventory:
# Shield protects the target
target_inventory.remove("🛡 Shield of Protection")
target_data["inventory"] = target_inventory
save_user_data(target_id, target_data) # Save updated target data
embed = discord.Embed(
title="🛡 Shield Activated!",
description=(
f"{target.mention} was protected by the **🛡 Shield of Protection**! "
f"The shield blocked {interaction.user.mention}'s attack!"
),
color=discord.Color.blue()
)
embed.set_thumbnail(url=interaction.user.display_avatar.url)
await interaction.response.send_message(embed=embed)
return
# Check cooldown
now = datetime.utcnow()
last_shoot = shoot_cooldowns.get(attacker_id, None)
cooldown_time = timedelta(minutes=5) # Cooldown duration
if last_shoot and now - last_shoot < cooldown_time:
remaining_time = cooldown_time - (now - last_shoot)
embed = discord.Embed(
title="🔫 Shoot Results",
description=f"⏳ You need to wait {remaining_time.seconds} seconds before shooting again!",
color=discord.Color.red()
)
embed.set_thumbnail(url=interaction.user.display_avatar.url)
await interaction.response.send_message(embed=embed, ephemeral=True)
return
# Set success chance, rewards, and penalties
success_chance = 0.6 # 60% chance to hit
reward = random.randint(50, 2000) # XPs gained on success
penalty = random.randint(30, 1000) # XPs lost on failure
# Attempt to shoot
if random.random() < success_chance:
# Success: Attacker steals XPs from the target
if target_data["xp"] >= reward:
target_data["xp"] -= reward