Discord Bot: Economy & Game Features
Discord Bot: Economy & Game Features
DATA_FILENAME = "fractal_data_v13_en.json"
ALLOWED_CHANNEL_NAME = "cmds"
GUILD_ID = 1401167718111117342
WORK_COOLDOWN_HOURS = 1
DAILY_COOLDOWN_HOURS = 22
CRIME_COOLDOWN_MINUTES = 45
MESSAGE_XP_COOLDOWN_SECONDS = 60
SHOP_ITEMS = {
"Roles": {
"VIP": {"price": 40000, "description": "Show off your status!"},
"Pro Gamer": {"price": 15000, "description": "For the true gaming
enthusiasts."},
"Legend": {"price": 150000, "description": "You have become a part of
server history."},
},
"Boosters": {
"XP Elixir": {"price": 3000, "duration_hours": 1, "effect": "xp_boost",
"multiplier": 2, "description": "Doubles all XP gains for 1 hour."},
"Lucky Clover": {"price": 4300, "duration_hours": 1, "effect":
"luck_boost", "multiplier": 1.15, "description": "Slightly increases win chances &
payouts for 1 hour."},
},
"Consumables": {
"Safety Net": {"price": 25000, "description": "A one-time use item that
prevents coin loss from a single casino game defeat."},
"Case Key": {"price": 3000, "description": "Unlocks a case with a random
reward."}
}
}
SLOT_EMOJIS = { "🍒": {"multiplier": 3, "weight": 25}, "🍋": {"multiplier": 4,
"weight": 20}, "🔔": {"multiplier": 6, "weight": 15}, "💎": {"multiplier": 12,
7️⃣
"weight": 8}, "": {"multiplier": 25, "weight": 4}, " ": {"multiplier": 77,
"weight": 1} }
SLOT_POOL = [emoji for emoji, data in SLOT_EMOJIS.items() for _ in
range(data['weight'])]
intents = [Link]()
intents.message_content = True
[Link] = True
bot = [Link](command_prefix="!", intents=intents, help_command=None)
user_data = {}
message_cooldowns = {}
def load_data():
global user_data
if [Link](DATA_FILENAME):
try:
with open(DATA_FILENAME, 'r', encoding='utf-8') as f: user_data =
[Link](f)
except [Link]: user_data = {}
else: user_data = {}
def save_data():
with open(DATA_FILENAME, 'w', encoding='utf-8') as f: [Link](user_data, f,
indent=4, ensure_ascii=False)
def get_user_account(user_id):
user_id_str = str(user_id)
if user_id_str not in user_data:
user_data[user_id_str] = DEFAULT_ACCOUNT.copy()
save_data()
else:
for key, value in DEFAULT_ACCOUNT.items():
user_data[user_id_str].setdefault(key, value)
return user_data[user_id_str]
def calculate_xp_for_next_level(level):
return 5 * (level ** 2) + (50 * level) + 100
def get_luck_multiplier(account):
luck_boost = [Link]("active_boosts", {}).get("luck_boost")
if luck_boost and [Link]() <
[Link](luck_boost["end_time"]):
return luck_boost["multiplier"]
return 1.0
@[Link]
async def on_ready():
load_data()
auto_save.start()
[Link].interaction_check = interaction_check
try:
guild_obj = [Link](id=GUILD_ID)
await [Link](guild=guild_obj)
synced = await [Link](guild=guild_obj)
print(f'Synced {len(synced)} commands for server {GUILD_ID}.')
except Exception as e: print(f'Error syncing commands: {e}')
print(f'Bot {[Link]} ([Link]) is online!')
await bot.change_presence(activity=[Link](name="/help or !help |
[Link]"))
@[Link](minutes=5)
async def auto_save(): save_data()
@[Link]
async def on_message(message):
if [Link] or not [Link]: return
if [Link] == ALLOWED_CHANNEL_NAME:
user_id = [Link]
current_time = [Link]()
last_message_time = message_cooldowns.get(user_id)
if not last_message_time or (current_time -
last_message_time).total_seconds() >= MESSAGE_XP_COOLDOWN_SECONDS:
message_cooldowns[user_id] = current_time
account = get_user_account(user_id)
xp_gain = [Link](*BASE_XP_PER_MESSAGE)
xp_boost = [Link]("active_boosts", {}).get("xp_boost")
if xp_boost and [Link]() <
[Link](xp_boost["end_time"]):
xp_gain = int(xp_gain * xp_boost["multiplier"])
account["xp"] += xp_gain
xp_needed = calculate_xp_for_next_level(account["level"])
if account["xp"] >= xp_needed:
account["level"] += 1
account["xp"] -= xp_needed
reward = account["level"] * LEVEL_UP_REWARD_MULTIPLIER
account["balance"] += reward
account["total_earned"] += reward
embed = [Link](title="🎉 LEVEL UP!",
description=f"{[Link]}, you have reached level
**{account['level']}**!\nReward: **{reward}** 🪙", color=[Link]())
try:
await [Link](embed=embed)
except [Link]:
pass
await bot.process_commands(message)
@[Link]
async def on_command_error(ctx, error):
if isinstance(error, [Link]): return
if isinstance(error, [Link]):
await [Link](f"❌ You're missing an argument! Correct usage: `!
{[Link]} {[Link]}`")
elif isinstance(error, ([Link], [Link])):
await [Link]("❌ Invalid argument provided. Please check your spelling and
try again.")
elif isinstance(error, [Link]):
await [Link]("❌ You don't have permission to use this command.")
elif isinstance(error, [Link]) and
isinstance([Link], [Link]):
await [Link]("❌ I don't have the required permissions to perform this
action. Please check my role and channel permissions (e.g., Send Messages, Manage
Roles, Mute Members).")
else:
print(f"An error occurred with a prefix command: {error}")
await [Link]("❌ An unexpected error occurred.")
class DuelView([Link]):
def __init__(self, challenger, opponent, bet):
super().__init__(timeout=60.0)
[Link] = challenger
[Link] = opponent
[Link] = bet
[Link] = None
[Link]()
for item in [Link]: [Link] = True
challenger_acc = get_user_account([Link])
opponent_acc = get_user_account([Link])
winner_acc["balance"] += [Link]
winner_acc["games_won"] += 1
loser_acc["games_lost"] += 1
save_data()
@[Link](label="Decline", style=[Link])
async def decline(self, interaction: [Link], button:
[Link]):
if [Link] != [Link]:
return await [Link].send_message("❌ This duel is not for
you!", ephemeral=True)
[Link]()
for item in [Link]: [Link] = True
await [Link].edit_message(content=f"🏃
**{[Link].display_name}** has declined the duel.", view=self)
class RussianRouletteView([Link]):
def __init__(self, author):
super().__init__(timeout=30.0)
[Link] = author
[Link] = {author}
[Link] = None
if len([Link]) < 2:
return await [Link](content="❌ Not enough players for
Russian Roulette.", view=self)
loser = [Link](list([Link]))
for p in [Link]:
account = get_user_account([Link])
if p == loser: account["games_lost"] += 1
else: account["games_won"] += 1
save_data()
embed = [Link](title="🔫 Russian Roulette 🔫",
color=[Link].dark_red(), description=f"The cylinder spins... 🔄\n...\n**💥
BANG!**\n\nThe loser is **{[Link]}**!")
try:
await [Link](timedelta(minutes=5), reason="Lost Russian
Roulette")
embed.set_footer(text=f"{loser.display_name} has been muted for 5
minutes.")
except [Link]:
embed.set_footer(text="I don't have permissions to mute the loser.")
class CoinflipView([Link]):
def __init__(self, author, opponent, amount):
super().__init__(timeout=60)
[Link] = author
[Link] = opponent
[Link] = amount
[Link] = None
@[Link](label="Accept", style=[Link],
emoji="✅")
async def accept(self, interaction: [Link], button:
[Link]):
if [Link] != [Link]:
return await [Link].send_message("❌ This challenge is not
for you!", ephemeral=True)
for item in [Link]: [Link] = True
winner, loser = [Link]([[Link], [Link]], 2)
winner_acc, loser_acc = get_user_account([Link]),
get_user_account([Link])
winner_acc["balance"] += [Link]
winner_acc["games_won"] += 1
loser_acc["games_lost"] += 1
save_data()
embed = [Link](title="🪙 Coinflip 🪙", description=result_text,
color=[Link]())
await [Link].edit_message(content=None, embed=embed,
view=self)
@[Link](label="Decline", style=[Link],
emoji="❌")
async def decline(self, interaction: [Link], button:
[Link]):
if [Link] != [Link]:
return await [Link].send_message("❌ This challenge is not
for you!", ephemeral=True)
for item in [Link]: [Link] = True
await [Link].edit_message(content="❌ Challenge declined.",
view=self)
if item_type == 'Boosters':
effect_type = item_to_use['effect']
if effect_type in [Link]("active_boosts", {}) and [Link]() <
[Link](account["active_boosts"][effect_type]["end_time"]):
return f"❌ A booster of this type is already active!"
end_time = [Link]() +
timedelta(hours=item_to_use['duration_hours'])
account["active_boosts"][effect_type] = {"end_time": end_time.isoformat(),
"multiplier": item_to_use['multiplier']}
account["inventory"].remove(item_in_inventory)
save_data()
return f"🚀 You have activated **{item_to_use['name']}** for
{item_to_use['duration_hours']} hour(s)!"
elif item_type == 'Consumables':
if item_to_use['name'] == "Case Key":
account["inventory"].remove(item_in_inventory)
reward_type = [Link](["coins", "item", "xp"], weights=[70, 10,
20], k=1)[0]
if reward_type == "coins":
amount = [Link](1000, 5000)
account['balance'] += amount
save_data()
return f"🔑 You opened the case and found **{amount:,}** 🪙!"
elif reward_type == "xp":
amount = [Link](500, 2000)
account['xp'] += amount
save_data()
return f"🔑 You opened the case and received **{amount:,}** ✨ XP!"
else:
item = "Safety Net"
account['inventory'].append(item)
save_data()
return f"🔑 You opened the case and found a **{item}**!"
return f"✅ **{item_to_use['name']}** is a passive item. It will be used
automatically when needed."
else:
return "❌ This item cannot be 'used' this way."
if result == target:
luck_mult = get_luck_multiplier(account)
winnings = int(bet * multipliers[target] * luck_mult)
account["balance"] += winnings
account["games_won"] += 1
win_desc = f"🎉 **You won!** Your bet on **{target}** paid out
**{winnings:,}** 🪙!"
if luck_mult > 1.0: win_desc += f"\n*Lucky Clover bonus: +{int(winnings -
(bet * multipliers[target])):,} 🪙!*"
[Link] = win_desc
[Link] = [Link]()
else:
if "Safety Net" in account["inventory"]:
account["inventory"].remove("Safety Net")
[Link] = f"💔 **You lost!** You bet on **{target}**, but the
roll was **{result}**.\n Your **Safety Net** was used and you lost no coins!"
[Link] = [Link]()
else:
account["balance"] -= bet
[Link] = f"💔 **You lost!** You bet on **{target}**, but the
roll was **{result}**. You lost **{bet:,}** 🪙."
account["games_lost"] += 1
account["balance"] -= item_to_buy["price"]
account["total_spent"] += item_to_buy["price"]
if item_type == "Roles":
role = [Link]([Link], name=item_to_buy["name"])
if not role: return f"❌ Role `{item_to_buy['name']}` not found on the
server!"
if role in [Link]: return "❌ You already have this role!"
if [Link].top_role.position <= [Link]:
return f"❌ I can't assign the **{[Link]}** role because it's higher
than my own role in the server's hierarchy."
await user.add_roles(role)
response = f"🎉 You purchased the **{item_to_buy['name']}** role!"
elif item_type in ["Boosters", "Consumables"]:
account["inventory"].append(item_to_buy["name"])
response = f"🎉 You bought a **{item_to_buy['name']}**! Check your
`/inventory`."
save_data()
return response
account['last_crime'] = [Link]().isoformat()
embed.add_field(name="New Balance", value=f"{account['balance']:,} 🪙")
save_data()
return embed
# SLASH COMMANDS
@[Link](name="help", description="Shows the list of all commands.")
async def help_slash(interaction: [Link]):
embed = await run_help(interaction)
await [Link].send_message(embed=embed, ephemeral=True)
await [Link]()
await [Link](1)
await [Link](embed=[Link](title="🎰 Slots are spinning...",
description=f"[ {reels[0]} | ❓ | ❓ ]", color=[Link]()))
await [Link](1)
await [Link](embed=[Link](title="🎰 Slots are spinning...",
description=f"[ {reels[0]} | {reels[1]} | ❓ ]", color=[Link]()))
await [Link](1)
winnings = 0
win_description = ""
final_embed = [Link]()
result_str = f"[ {reels[0]} | {reels[1]} | {reels[2]} ]"
if winnings > 0:
account["balance"] += winnings
if winnings > bet:
account["balance"] -= bet
account["games_won"] += 1
final_embed.title = "🎉 WINNER! 🎉"
final_embed.description = f"{result_str}\n{win_description}"
final_embed.color = [Link]()
else:
if "Safety Net" in account["inventory"]:
account["inventory"].remove("Safety Net")
final_embed.title = " SAVED! "
final_embed.description = f"{result_str}\n💔 You lost, but your **Safety
Net** was used and you lost no coins!"
final_embed.color = [Link]()
else:
account["balance"] -= bet
final_embed.title = "💔 DEFEAT 💔"
final_embed.description = f"{result_str}\nYou lost **{bet:,}** 🪙."
final_embed.color = [Link]()
account["games_lost"] += 1
# PREFIX COMMANDS
@[Link](name="help")
async def help_prefix(ctx: [Link]):
embed = await run_help(ctx)
await [Link](embed=embed)
@[Link](name="balance", aliases=["bal"])
async def balance_prefix(ctx: [Link], member: [Link] = None):
embed = await run_balance(ctx, member)
await [Link](embed=embed)
@[Link](name="profile")
async def profile_prefix(ctx: [Link], member: [Link] = None):
embed = await run_profile(ctx, member)
await [Link](embed=embed)
@[Link](name="work")
async def work_prefix(ctx: [Link]):
result = await run_work([Link])
if isinstance(result, str): await [Link](result)
else: await [Link](embed=result)
@[Link](name="daily")
async def daily_prefix(ctx: [Link]):
result = await run_daily([Link])
if isinstance(result, str): await [Link](result)
else: await [Link](embed=result)
@[Link](name="inventory")
async def inventory_prefix(ctx: [Link]):
embed = await run_inventory([Link])
await [Link](embed=embed)
@[Link](name="use")
async def use_prefix(ctx: [Link], *, item_name: str):
response_message = await run_use([Link], item_name)
await [Link](response_message)
@[Link](name="givemoney")
@commands.has_permissions(administrator=True)
async def give_money_prefix(ctx: [Link], member: [Link], amount:
int):
if amount <= 0: return await [Link]("❌ Amount must be positive.")
account = get_user_account([Link])
account["balance"] += amount
save_data()
embed = [Link](title="💸 Funds Added", description=f"Admin
{[Link]} has given **{amount:,}** 🪙 to {[Link]}.",
color=[Link]())
await [Link](embed=embed)
@[Link](name="duel")
async def duel_prefix(ctx: [Link], member: [Link], bet: int):
error_message = await run_duel(ctx, member, bet)
if error_message: await [Link](error_message)
@[Link](name="russian_roulette")
async def russian_roulette_prefix(ctx: [Link]):
await run_russian_roulette(ctx)
@[Link](name="pay")
async def pay_prefix(ctx: [Link], member: [Link], amount: int):
if [Link] == [Link] or amount <= 0 or [Link]:
return await [Link]("❌ Invalid transfer parameters.")
sender_account = get_user_account([Link])
if sender_account["balance"] < amount:
return await [Link]("❌ You don't have enough funds!")
receiver_account = get_user_account([Link])
sender_account["balance"] -= amount
receiver_account["balance"] += amount
save_data()
await [Link](f"💸 {[Link]} transferred **{amount:,}** 🪙 to
{[Link]}!")
@[Link](name="shop")
async def shop_prefix(ctx: [Link]):
embed = [Link](title="🛒 Shop", description="Use `!buy <item_name>` to
purchase.", color=[Link]())
for category, items in SHOP_ITEMS.items():
text = "\n".join([f"**{name}** - {data['price']:,} 🪙\n*└
{data['description']}*" for name, data in [Link]()])
embed.add_field(name=f"--- {category} ---", value=text, inline=False)
await [Link](embed=embed)
@[Link](name="buy")
async def buy_prefix(ctx: [Link], *, item_name: str):
response = await run_buy([Link], [Link], item_name)
await [Link](response)
@[Link](name="stats")
async def stats_prefix(ctx: [Link]):
total_balance = sum([Link]('balance', 0) for data in user_data.values())
total_users = len(user_data)
avg_level = sum([Link]('level', 1) for data in user_data.values()) / max(1,
total_users)
embed = [Link](title="📊 Server Statistics",
color=[Link].dark_blue())
embed.add_field(name="👥 Total Players", value=f"{total_users}")
embed.add_field(name="💰 Total Coins in Circulation",
value=f"{total_balance:,} 🪙")
embed.add_field(name="📈 Average Level", value=f"{avg_level:.1f}")
await [Link](embed=embed)
@[Link](name="rank")
async def rank_prefix(ctx: [Link], member: [Link] = None):
embed = await run_rank(ctx, member)
await [Link](embed=embed)
@[Link](name="top")
async def top_prefix(ctx: [Link]):
embed = await run_top([Link])
await [Link](embed=embed)
@[Link](name="leaderboard")
async def leaderboard_prefix(ctx: [Link]):
embed = await run_leaderboard([Link])
await [Link](embed=embed)
@[Link](name="dice")
async def dice_prefix(ctx: [Link], bet: int, target: int):
result = await run_dice([Link], bet, target)
if isinstance(result, str): await [Link](result)
else: await [Link](embed=result)
@[Link](name="slots")
async def slots_prefix(ctx: [Link], bet: int):
if bet <= 0: return await [Link]("❌ Bet must be positive.")
account = get_user_account([Link])
if account["balance"] < bet: return await [Link]("❌ You don't have enough
coins.")
await [Link](1)
await [Link](embed=[Link](title="🎰 Slots are spinning...",
description=f"[ {reels[0]} | ❓ | ❓ ]", color=[Link]()))
await [Link](1)
await [Link](embed=[Link](title="🎰 Slots are spinning...",
description=f"[ {reels[0]} | {reels[1]} | ❓ ]", color=[Link]()))
await [Link](1)
winnings = 0
win_description = ""
final_embed = [Link]()
result_str = f"[ {reels[0]} | {reels[1]} | {reels[2]} ]"
if winnings > 0:
account["balance"] += winnings
if winnings > bet:
account["balance"] -= bet
account["games_won"] += 1
final_embed.title = "🎉 WINNER! 🎉"
final_embed.description = f"{result_str}\n{win_description}"
final_embed.color = [Link]()
else:
if "Safety Net" in account["inventory"]:
account["inventory"].remove("Safety Net")
final_embed.title = " SAVED! "
final_embed.description = f"{result_str}\n💔 You lost, but your **Safety
Net** was used and you lost no coins!"
final_embed.color = [Link]()
else:
account["balance"] -= bet
final_embed.title = "💔 DEFEAT 💔"
final_embed.description = f"{result_str}\nYou lost **{bet:,}** 🪙."
final_embed.color = [Link]()
account["games_lost"] += 1
@[Link](name="rofl")
async def rofl_prefix(ctx: [Link]):
members = [m for m in [Link] if not [Link]]
target = [Link](members)
await [Link](f"😂 {[Link]} {[Link](ROFL_PHRASES)}
{[Link]}!")
@[Link](name="meme")
async def meme_prefix(ctx: [Link]):
memes = ["Why don't scientists trust atoms? Because they make up everything!",
"I told my wife she was drawing her eyebrows too high. She looked surprised."]
await [Link]([Link](memes))
@[Link](name="8ball")
async def eightball_prefix(ctx: [Link], *, question: str):
embed = [Link](title="🔮 Magic 8-Ball", color=[Link]())
embed.add_field(name="Your Question", value=question, inline=False)
embed.add_field(name="The Ball's Answer",
value=[Link](EIGHT_BALL_RESPONSES), inline=False)
await [Link](embed=embed)
@[Link](name="ship")
async def ship_prefix(ctx: [Link], member1: [Link], member2:
[Link]):
compatibility = [Link](0, 100)
emoji = "❤️"
if compatibility < 20: emoji = "💔"
elif compatibility < 50: emoji = "😐"
elif compatibility < 80: emoji = "😊"
else: emoji = "💞"
await [Link](f"Compatibility for {[Link]} and {[Link]}:
**{compatibility}%** {emoji}")
@[Link](name="cat")
async def cat_prefix(ctx: [Link]):
async with [Link]() as session:
async with [Link]('[Link] as
resp:
if [Link] == 200:
data = await [Link]()
embed = [Link](title="🐱 Meow!", color=[Link]())
embed.set_image(url=data[0]['url'])
await [Link](embed=embed)
else:
await [Link]("❌ Could not fetch a cat picture.")
@[Link](name="dog")
async def dog_prefix(ctx: [Link]):
async with [Link]() as session:
async with [Link]('[Link] as resp:
if [Link] == 200:
data = await [Link]()
embed = [Link](title="🐶 Woof!",
color=[Link]())
embed.set_image(url=data['url'])
await [Link](embed=embed)
else:
await [Link]("❌ Could not fetch a dog picture.")
@[Link](name="avatar")
async def avatar_prefix(ctx: [Link], member: [Link] = None):
target_user = member or [Link]
embed = [Link](title=f" Avatar of {target_user.display_name}",
color=target_user.color)
embed.set_image(url=target_user.display_avatar.url)
await [Link](embed=embed)
@[Link](name="hug")
async def hug_prefix(ctx: [Link], member: [Link]):
if member == [Link]: return await [Link]("You can't hug yourself, but
here's one from me 🤗")
embed = [Link](description=f"**{[Link].display_name}** gives
**{member.display_name}** a big hug!", color=0xFFC0CB)
embed.set_image(url=[Link](HUG_GIFS))
await [Link](embed=embed)
@[Link](name="crime")
async def crime_prefix(ctx: [Link]):
result = await run_crime([Link])
if isinstance(result, str): await [Link](result)
else: await [Link](embed=result)
[Link]("MTQxMDczNzU2MDE0NTEwMDk5Mg.GagLf5.mPF_Mkp4BYlXKpKwZTLaqOXL2Noe4KehBCRi8Q")
# Замени на свой токен