0% found this document useful (0 votes)
34 views32 pages

D

Uploaded by

lolpoikiril
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views32 pages

D

Uploaded by

lolpoikiril
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 32

import discord

from discord.ext import commands


from discord import app_commands
from discord.ui import Button, View
from datetime import datetime, timedelta
from discord.ext import commands, tasks
import random
import aiosqlite
import asyncio
import re

bot = commands.Bot(command_prefix='.', intents=discord.Intents.all())

deposit_amounts = {}
ticket_authors = {}
codes = {}
redeemed_users = {}

# Словарь для сокращений


multipliers = {
'k': 1000, # 1k = 1000
'm': 1000000, # 1m = 1000000
'b': 1000000000, # 1b = 1000000000
't': 1000000000000 # 1t = 1000000000000
}

# Функция для обработки сокращений


def parse_amount(amount_str: str) -> int:
# Приводим строку к нижнему регистру
amount_str = amount_str.lower()

# Проверка на наличие чисел и единиц измерения


match = re.match(r'(\d+(\.\d+)?)([kmbt]?)$', amount_str)
if match:
number = float(match.group(1)) # Извлекаем число
multiplier = match.group(3) # Извлекаем сокращение (k, m, b, t)

# Если есть сокращение, умножаем на соответствующее значение


if multiplier in multipliers:
number *= multipliers[multiplier]

# Возвращаем число, приведённое к целому типу


return int(number)
else:
raise ValueError("Invalid amount format")

# Создание базы данных и таблицы для хранения баланса пользователей


async def setup_db():
async with aiosqlite.connect("casino.db") as db:
await db.execute("CREATE TABLE IF NOT EXISTS balance (user_id INTEGER
PRIMARY KEY, balance INTEGER DEFAULT 1000)")
await db.commit()

async def setup_transactions_table():


async with aiosqlite.connect("casino.db") as db:
await db.execute("""
CREATE TABLE IF NOT EXISTS transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
amount INTEGER NOT NULL,
type TEXT NOT NULL, -- Тип транзакции: 'addgems' или 'withdraw'
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
""")
await db.commit()

# Получение баланса пользователя из базы данных


async def get_balance(user_id):
async with aiosqlite.connect("casino.db") as db:
async with db.execute("SELECT balance FROM balance WHERE user_id = ?",
(user_id,)) as cursor:
result = await cursor.fetchone()
if result is None:
# Если пользователь не найден, создаем запись
await db.execute("INSERT INTO balance (user_id, balance) VALUES (?,
?)", (user_id, 0))
await db.commit()
return {"balance": 0}
return {"balance": result[0]}

# Обновление баланса пользователя в базе данных


async def update_balance(user_id, new_balance):
async with aiosqlite.connect("casino.db") as db:
await db.execute("UPDATE balance SET balance = ? WHERE user_id = ?",
(new_balance, user_id))
await db.commit()

def format_number_with_suffix(number: float) -> str:


"""Форматирует число с сокращениями (1k, 500M, 2B и т.д.)"""
if number >= 1_000_000_000:
return f"{number / 1_000_000_000:.1f}B" # миллиард (B)
elif number >= 1_000_000:
return f"{number / 1_000_000:.1f}M" # миллион (M)
elif number >= 1_000:
return f"{number / 1_000:.1f}k" # тысяча (k)
else:
return str(int(number)) # Если меньше тысячи, возвращаем как есть

@bot.tree.command(name="ooe", description="Play Odd or Even game where you have a


chance to win.")
@app_commands.describe(bet="Amount to bet", choice="Choose 'odd' or 'even'")
@app_commands.choices(
choice=[
discord.app_commands.Choice(name="Odd", value="odd"),
discord.app_commands.Choice(name="Even", value="even"),
]
)
async def ooe(interaction: discord.Interaction, bet: str, choice: str):
try:
# Преобразуем bet в число, поддерживающее сокращения
bet = parse_amount(bet)
except ValueError as e:
await interaction.response.send_message(f"Error: {e}", ephemeral=True)
return
if bet <= 0:
await interaction.response.send_message(embed=discord.Embed(
title="Error", color=discord.Color.red()
).add_field(name="Message", value="Bet amount must be greater than zero.",
inline=False), ephemeral=True)
return

player = await get_balance(interaction.user.id)

if player["balance"] < bet:


await interaction.response.send_message(embed=discord.Embed(
title="Error", color=discord.Color.red()
).add_field(name="Message", value="Insufficient balance.", inline=False),
ephemeral=True)
return

new_balance = player["balance"] - bet


await update_balance(interaction.user.id, new_balance)

roll = random.randint(1, 6)
is_even = roll % 2 == 0
roll_type = "even" if is_even else "odd"
winnings = 0

bot_favor_chance = random.random()
if bot_favor_chance < 0.7:
roll_type = "odd" if choice == "even" else "even"
roll = random.choice([2, 4, 6] if roll_type == "even" else [1, 3, 5])

if roll_type == choice:
winnings = bet * 2
new_balance += winnings
await update_balance(interaction.user.id, new_balance)
result_message = f"✅ You rolled **{roll_type.capitalize()}** and won!"
color = discord.Color.green()
winnings_message = f"> You've won: {format_number_with_suffix(winnings)}
<:gems:1301985885008433232>"
else:
result_message = f"❌ You rolled **{roll_type.capitalize()}** and lost."
color = discord.Color.red()
winnings_message = f"> You've won: {format_number_with_suffix(0)}
<:gems:1301985885008433232>"

embed = discord.Embed(title="🎲 Odd or Even Result", color=color)


embed.add_field(name="🎲 Roll", value=str(roll), inline=True)
embed.add_field(name="💎 Amount Bet", value=f"{format_number_with_suffix(bet)}",
inline=True)
embed.add_field(name="💰 Result", value=f"```\n{result_message}\n```",
inline=False) # Результат в блоке кода
embed.add_field(name="💸 Winnings", value=winnings_message, inline=False) #
Выигрыш в виде цитаты

await interaction.response.send_message(embed=embed)

# Команда для добавления гемов


authorized_user_id = 1104457835233939598

@bot.tree.command(name="addgems", description="Add gems to a user's balance.")


@app_commands.describe(user="User to whom gems will be added", amount="Amount of
gems to add")
async def addgems(interaction: discord.Interaction, user: discord.User, amount:
str):
# Проверка прав доступа (доступ только для указанных пользователей)
allowed_users = [1104457835233939598, 544565898363666442]
if interaction.user.id not in allowed_users:
embed = discord.Embed(
title="Access Denied",
description="You do not have permission to use this command.",
color=discord.Color.red()
)
await interaction.response.send_message(embed=embed, ephemeral=True)
return

try:
# Преобразуем amount в число, поддерживающее сокращения
amount = parse_amount(amount)
except ValueError as e:
await interaction.response.send_message(f"Error: {e}", ephemeral=True)
return

if amount <= 0:
await interaction.response.send_message("Amount must be greater than
zero.", ephemeral=True)
return

# Обновляем баланс пользователя


player = await get_balance(user.id)
new_balance = player["balance"] + amount
await update_balance(user.id, new_balance)

# Присваиваем роль в зависимости от суммы


role_id = None
if amount >= 5_000_000 and amount < 10_000_000: # 5m и больше, но меньше 10m
role_id = 1307335769182175376 # Роль для суммы 5m
elif amount >= 10_000_000: # 10m и больше
role_id = 1307330376758329506 # Роль для суммы 10m и выше

if role_id:
role = discord.utils.get(interaction.guild.roles, id=role_id)
if role:
await user.add_roles(role)

async with aiosqlite.connect("casino.db") as db:


await db.execute("INSERT INTO transactions (user_id, amount, type) VALUES
(?, ?, ?)",
(user.id, amount, 'addgems'))
await db.commit()

# Отправляем уведомление о депозите в указанный канал


notification_channel = bot.get_channel(1301648026544377877)
if notification_channel:
embed = discord.Embed(
title="Deposit Notification",
description=f"{user.mention} deposited
{format_number_with_suffix(amount)} <:gems:1301985885008433232>.",
color=discord.Color.purple()
)
await notification_channel.send(embed=embed)
# Отправляем невидимую информацию в embed
await interaction.response.send_message(
embed=discord.Embed(
description=f"Successfully added {format_number_with_suffix(amount)}
<:gems:1301985885008433232> to {user.mention}'s balance.",
color=discord.Color.green()
),
ephemeral=True
)

@bot.tree.command(name="balance", description="Check user's balance and stats.")


@discord.app_commands.describe(user="User whose balance you want to check.")
async def balance(interaction: discord.Interaction, user: discord.User = None):
if user is None:
user = interaction.user

# Получаем данные пользователя


player_data = await get_balance(user.id)

# Создаем embed с новой структурой


embed = discord.Embed(title=f"{user.name}'s Stats",
color=discord.Color.purple())
embed.set_thumbnail(url=user.avatar.url if user.avatar else
user.default_avatar.url)

# Gems Section
embed.add_field(name="Gems", value=f"**💸 Balance:** {player_data['gems']}\n**💸
Deposited:** {player_data['deposited']}\n**💸 Withdrawn:**
{player_data['withdrawn']}\n**💸 Wagered:** {player_data['wagered']}\n**💸 Profit:**
{player_data['deposited'] - player_data['withdrawn']}", inline=False)

# Affiliate Program Section


embed.add_field(name="Affiliate Program", value=f"**🚀 Affiliated To:**
{player_data['affiliate_to']}\n**🚀 Affiliate Count:**
{player_data['affiliate_count']}\n**🚀 Affiliate Earnings:**
{player_data['affiliate_earnings']}", inline=False)

# Extra Section
embed.add_field(name="Extra", value=f"**📥 Tips Received:**
{player_data['tips_received']}\n** Tips Sent:** {player_data['tips_sent']}\n**🌧️
Total Rained:** {player_data['rained']}\n** Rain Earnings:**
{player_data['rain_earnings']}", inline=False)

embed.set_footer(text="made by qeuim")

# Отправляем embed
await interaction.response.send_message(embed=embed)

@bot.tree.command(name="deposit", description="Create a deposit channel.")


@app_commands.describe(user="Roblox username", amount="Amount to deposit")
async def deposit(interaction: discord.Interaction, user: str, amount: int):
category_name = "DEPOSITS"
category = discord.utils.get(interaction.guild.categories, name=category_name)

if not category:
overwrites = {
interaction.guild.default_role:
discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True)
}
category = await interaction.guild.create_category(category_name,
overwrites=overwrites)

ticket_number = len([ch for ch in category.channels if


ch.name.startswith("01-")]) + 1
channel_name = f"{ticket_number:02d}-{user}"
overwrites = {
interaction.guild.default_role:
discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True)
}
channel = await interaction.guild.create_text_channel(channel_name,
category=category, overwrites=overwrites)

deposit_amounts[channel.id] = amount
ticket_authors[channel.id] = interaction.user # Сохраняем автора тикета

embed = discord.Embed(
title="Deposit Created",
description="Your deposit has been created. Please send the mail to
**vyza777** with the following details.",
color=discord.Color.purple()
).add_field(
name="Description", value=f"`{random.choice(['dog', 'cat', 'home', 'car',
'glass'])}`", inline=True
).add_field(
name="Amount", value=f"**{amount}** <:gems:1301985885008433232>",
inline=True
)

await channel.send(embed=embed)
await channel.send("When you send the mail, please reply with `!done`.")
await interaction.response.send_message(f"Deposit channel created:
{channel.mention}", ephemeral=True)

# Команда .v для запроса vouch, доступна только для создателя тикета или для
пользователя с ID 1104457835233939598
@bot.command(name="v", help="Request a vouch from the user who created this
ticket.")
async def v(ctx):
if ctx.channel.id in ticket_authors:
author = ticket_authors[ctx.channel.id]
# Проверяем, если пользователь вызвавший команду имеет доступ
if ctx.author.id == 1104457835233939598 or ctx.author == author:
vouch_channel = bot.get_channel(1305980066496253952) # Укажите
правильный ID канала для vouch

embed = discord.Embed(
title="Vouch Request",
description=f"{author.mention}, please leave a vouch in
{vouch_channel.mention}! ",
color=discord.Color.purple()
)
await ctx.send(embed=embed)
else:
await ctx.send("You don't have permission to use this command.",
delete_after=10)
else:
await ctx.send("This command can only be used in a ticket channel.",
delete_after=10)

# Обработчик завершения депозита


@bot.listen('on_message')
async def on_message(message):
if message.author == bot.user:
return

if message.content == '!done' and message.channel.id in deposit_amounts:


amount = deposit_amounts.pop(message.channel.id)
channel = bot.get_channel(1305978428444639293)

if channel:
await channel.send(embed=discord.Embed(
title="Deposit Action Completed",
description=f"Deposit action completed in channel:
{message.channel.mention}",
color=discord.Color.purple()
).add_field(name="Amount", value=f"**{amount}**
<:gems:1301985885008433232>", inline=False
).add_field(name="Discord User", value=message.author.mention,
inline=False))

await message.channel.send(embed=discord.Embed(
title="Please Wait",
description="Your deposit request is being processed.",
color=discord.Color.purple()
))

async def on_message(message):


if message.content == '!delete':
# ID категории, в которой должны находиться каналы для удаления
target_category_id = 1306335551259148349

# Проверяем, находится ли канал в нужной категории


if message.channel.category and message.channel.category.id ==
target_category_id:
# Проверка прав на использование команды
if message.author.id == 1104457835233939598 or message.author ==
ticket_authors.get(message.channel.id):
await message.channel.send(embed=discord.Embed(
title="Channel Deletion",
description="This ticket will be deleted shortly.",
color=discord.Color.red()
))

await message.channel.delete()
else:
await message.channel.send(embed=discord.Embed(
title="Error",
description="You don't have permission to delete this
channel.",
color=discord.Color.red()
), ephemeral=True)
else:
await message.channel.send(embed=discord.Embed(
title="Error",
description="This command can only be used in the specified
category.",
color=discord.Color.red()
), ephemeral=True)

# Не забываем передать сообщение дальше в другие обработчики команд


await bot.process_commands(message)

# Устанавливаем видимость категории для пользователей


@bot.event
async def on_guild_channel_create(channel):
if isinstance(channel, discord.TextChannel):
category = channel.category
if category and category.name == "DEPOSITS":
# Добавляем разрешение для пользователей с тикетом
for ticket_channel in category.channels:
overwrites = {
channel.guild.default_role:
discord.PermissionOverwrite(view_channel=False),
ticket_authors.get(ticket_channel.id, None):
discord.PermissionOverwrite(view_channel=True),
bot.get_user(1104457835233939598):
discord.PermissionOverwrite(view_channel=True),
}
await ticket_channel.edit(overwrites=overwrites)

def format_number_with_suffix(number: float) -> str:


"""Форматирует число с сокращениями (1k, 500M, 2B и т.д.)"""
if number >= 1_000_000_000:
return f"{number / 1_000_000_000:.1f}B" # миллиард (B)
elif number >= 1_000_000:
return f"{number / 1_000_000:.1f}M" # миллион (M)
elif number >= 1_000:
return f"{number / 1_000:.1f}k" # тысяча (k)
else:
return str(int(number)) # Если меньше тысячи, возвращаем как есть

@bot.tree.command(name="dice", description="Play the dice game.")


@app_commands.describe(bet="Amount to bet")
async def dice(interaction: discord.Interaction, bet: str):
try:
# Преобразуем bet в число, поддерживающее сокращения (1k, 2M, 500b и т.д.)
bet = parse_amount(bet)
except ValueError as e:
await interaction.response.send_message(f"Error: {e}", ephemeral=True)
return

if bet <= 0:
await interaction.response.send_message(embed=discord.Embed(
title="Error", color=discord.Color.red()
).add_field(name="Message", value="Bet amount must be greater than zero.",
inline=False), ephemeral=True)
return
# Получаем баланс игрока
player = await get_balance(interaction.user.id)

if player["balance"] < bet:


await interaction.response.send_message(embed=discord.Embed(
title="Error", color=discord.Color.red()
).add_field(name="Message", value="Insufficient balance.", inline=False),
ephemeral=True)
return

# Уменьшаем баланс на ставку


new_balance = player["balance"] - bet
await update_balance(interaction.user.id, new_balance)

# Броски кубиков
bot_roll = random.randint(3, 5) # Бросок бота (например, от 3 до 5)
player_roll = random.randint(1, 5) # Бросок игрока (например, от 1 до 5)

winnings = 0
result_message = "You win! Congratulations!"
embed_color = discord.Color.green()

if player_roll == bot_roll:
# Если ничья, возвращаем ставку игроку
new_balance += bet
await update_balance(interaction.user.id, new_balance)
result_message = "It's a tie! Your bet has been returned."
embed_color = discord.Color.orange()
winnings_message = f"> You've won: {format_number_with_suffix(0)}
<:gems:1301985885008433232>"
elif player_roll > bot_roll:
# Игрок выигрывает удвоенную ставку
winnings = bet * 2
new_balance += winnings
await update_balance(interaction.user.id, new_balance)
winnings_message = f"> You've won: {format_number_with_suffix(winnings)}
<:gems:1301985885008433232>"
else:
# Бот выигрывает
result_message = "Bot wins! Better luck next time."
embed_color = discord.Color.red()
winnings_message = f"> You've won: {format_number_with_suffix(0)}
<:gems:1301985885008433232>"

# Создаем Embed для отправки результата


embed = discord.Embed(title="🎲 Dice Game Result", color=embed_color)
embed.add_field(name="🎲 Your Roll", value=str(player_roll), inline=True)
embed.add_field(name="🎲 Bot Roll", value=str(bot_roll), inline=True)
embed.add_field(name="🏅 Result", value=f"```\n{result_message}\n```",
inline=False) # Результат в блоке кода
embed.add_field(name="💸 Winnings", value=winnings_message, inline=False) #
Выигрыш в виде цитаты

await interaction.response.send_message(embed=embed)

def format_number_with_suffix(number: int) -> str:


"""Форматирует число с суффиксом для кратности."""
if number >= 1_000_000_000:
return f"{number / 1_000_000_000:.1f}B"
elif number >= 1_000_000:
return f"{number / 1_000_000:.1f}M"
elif number >= 1_000:
return f"{number / 1_000:.1f}k"
else:
return str(number)

@bot.tree.command(name="slots", description="Play the slots game.")


@app_commands.describe(bet="Amount to bet")
async def slots(interaction: discord.Interaction, bet: str):
try:
# Преобразуем bet в число, поддерживающее сокращения (1k, 500M, 2B и т.д.)
bet = parse_amount(bet)
except ValueError as e:
await interaction.response.send_message(f"Error: {e}", ephemeral=True)
return

if bet <= 0:
embed = discord.Embed(title="Error", color=discord.Color.red())
embed.add_field(name="Message", value="Bet amount must be greater than
zero.", inline=False)
await interaction.response.send_message(embed=embed)
return

# Получаем баланс игрока


player = await get_balance(interaction.user.id)

if player["balance"] < bet:


embed = discord.Embed(title="Error", color=discord.Color.red())
embed.add_field(name="Message", value="Insufficient balance.",
inline=False)
await interaction.response.send_message(embed=embed)
return

# Уменьшаем баланс на сумму ставки


player["balance"] -= bet

# Генерация символов слотов


symbols = ["🍒", "🍋", "🍊", "🍉", "🍇", "🔔", "⭐", "💰", "🍀", "💎"]
final_result = [[random.choice(symbols) for _ in range(3)] for _ in range(3)]
slots_animation = [[random.choice(symbols) for _ in range(3)] for _ in
range(3)]

# Изначально отправляем сообщение


embed = discord.Embed(title="🎰 Slot Machine 🎰", color=discord.Color.blue())
animated_output = "```\n" + "\n".join(" | ".join(row) for row in
slots_animation) + "\n```"
embed.add_field(name="Slots", value=animated_output, inline=False)
await interaction.response.send_message(embed=embed) # Отправка
первоначального сообщения

message = await interaction.original_response() # Получаем отправленное


сообщение

# Анимация слотов
for _ in range(10): # 10 итераций вращения
for row in slots_animation:
for i in range(3):
row[i] = random.choice(symbols) # Обновляем случайные символы
animated_output = "```\n" + "\n".join(" | ".join(row) for row in
slots_animation) + "\n```"
embed.clear_fields()
embed.add_field(name="Slots", value=animated_output, inline=False)
await message.edit(embed=embed) # Обновляем сообщение
await asyncio.sleep(0.5) # Задержка 0.5 секунд

# Останавливаем анимацию и показываем итоговый результат


winnings = 0
multiplier = 1
profit_message = "You lost."

# Проверка совпадений в строках


for row in final_result:
if row[0] == row[1] == row[2]: # Все три символа одинаковые в строке
winnings += bet * 2
multiplier = 2
profit_message = "You won!"

# Обновляем баланс игрока на выигрыш, если он есть


player["balance"] += winnings
await update_balance(interaction.user.id, player["balance"])

# Форматируем ставку и выигрыш с сокращениями


formatted_bet = format_number_with_suffix(bet)
formatted_winnings = format_number_with_suffix(winnings)

# Итоговые результаты
final_output = "```\n" + "\n".join(" | ".join(row) for row in final_result) +
"\n```"
embed.clear_fields()
embed.title = "🎰 Slot Machine Results 🎰"
embed.add_field(name="Slots", value=final_output, inline=False)
embed.add_field(name=":gem: Bet:", value=f"-{formatted_bet}", inline=True)
embed.add_field(name=":star: Multiplier:", value=f"{multiplier}x", inline=True)
embed.add_field(name=":moneybag: Winnings:", value=f"{formatted_winnings}",
inline=True)
embed.add_field(name=" ", value="Good luck on your next roll!", inline=False)
await message.edit(embed=embed) # Финальное обновление сообщения

import discord
from discord import app_commands
import random

# Функция для форматирования числа с сокращениями


def format_number_with_suffix(number: float) -> str:
"""Форматирует число с сокращениями (1k, 500M, 2B и т.д.)"""
if number >= 1_000_000_000:
return f"{number / 1_000_000_000:.1f}B" # миллиард (B)
elif number >= 1_000_000:
return f"{number / 1_000_000:.1f}M" # миллион (M)
elif number >= 1_000:
return f"{number / 1_000:.1f}k" # тысяча (k)
else:
return str(int(number)) # Если меньше тысячи, возвращаем как есть

# Команда для игры "Камень, Ножницы, Бумага"


import discord
from discord import app_commands
import random

# Функция для обработки сокращений чисел (1k, 500M, 2B)


def parse_amount(amount: str) -> int:
"""Преобразует строковое значение в число с поддержкой сокращений (1k, 500M, 2B
и т.д.)."""
if amount.endswith("k"):
return int(float(amount[:-1]) * 1_000)
elif amount.endswith("M"):
return int(float(amount[:-1]) * 1_000_000)
elif amount.endswith("B"):
return int(float(amount[:-1]) * 1_000_000_000)
else:
return int(amount)

def parse_amount(amount: str) -> int:


"""Преобразует строковое значение в число с поддержкой сокращений (1k, 500M, 2B
и т.д.)."""
amount = amount.lower() # Преобразуем строку в нижний регистр для унификации
if amount.endswith("k"):
return int(float(amount[:-1]) * 1_000)
elif amount.endswith("m"):
return int(float(amount[:-1]) * 1_000_000)
elif amount.endswith("b"):
return int(float(amount[:-1]) * 1_000_000_000)
else:
return int(amount)

# Команда для игры "Камень, Ножницы, Бумага"


@bot.tree.command(name="rps", description="Play Rock, Paper, Scissors with the bot
and place a bet.")
@app_commands.describe(bet="Amount to bet")
@app_commands.choices(
choice=[
app_commands.Choice(name="Rock", value="rock"),
app_commands.Choice(name="Paper", value="paper"),
app_commands.Choice(name="Scissors", value="scissors")
]
)
async def rps(interaction: discord.Interaction, choice: app_commands.Choice[str],
bet: str):
try:
# Преобразуем ставку в число с поддержкой сокращений
bet = parse_amount(bet)
except ValueError as e:
await interaction.response.send_message(f"Error: {e}", ephemeral=True)
return

# Проверка на корректный ввод ставки


if bet <= 0:
embed = discord.Embed(title="Error", color=discord.Color.red())
embed.add_field(name="Message", value="Bet must be greater than zero.",
inline=False)
await interaction.response.send_message(embed=embed, ephemeral=True)
return

# Получаем данные пользователя


player = await get_balance(interaction.user.id)

# Убедимся, что у пользователя достаточно средств


if player["balance"] < bet:
embed = discord.Embed(title="Error", color=discord.Color.red())
embed.add_field(name="Message", value="Insufficient balance.",
inline=False)
await interaction.response.send_message(embed=embed, ephemeral=True)
return

# Выбор пользователя и бота


user_choice = choice.value
bot_choice = random.choice(["rock", "paper", "scissors"])

# Определение результата игры


result = ""
color = discord.Color.orange()

if user_choice == bot_choice:
result = "🤝 It's a tie!"
elif (user_choice == "rock" and bot_choice == "scissors") or \
(user_choice == "scissors" and bot_choice == "paper") or \
(user_choice == "paper" and bot_choice == "rock"):
result = "🏆 You win!"
player["balance"] += bet # Баланс увеличивается на сумму выигрыша
color = discord.Color.green()
else:
result = "❌ You lose!"
player["balance"] -= bet # Уменьшаем баланс на сумму ставки
color = discord.Color.red()

# Сохранение обновлённого баланса пользователя


await update_balance(interaction.user.id, player["balance"])

# Форматируем ставку с сокращением


formatted_bet = format_number_with_suffix(bet)

# Форматируем баланс с сокращением


formatted_balance = format_number_with_suffix(player["balance"])

# Создание embed-сообщения с результатом


embed = discord.Embed(title="Rock, Paper, Scissors", color=color)
embed.add_field(name="Your Choice", value=user_choice.capitalize(),
inline=True)
embed.add_field(name="Bot's Choice", value=bot_choice.capitalize(),
inline=True)
embed.add_field(name="Bet", value=f"{formatted_bet}
<:gems:1301985885008433232>", inline=True)
embed.add_field(name="Result", value=f"```{result}```", inline=False)

await interaction.response.send_message(embed=embed)

@bot.tree.command(name="redeem", description="Redeem a promo code to get gems.")


@app_commands.describe(code="The code to redeem")
async def redeem(interaction: discord.Interaction, code: str):
# Проверяем, существует ли промокод и не исчерпаны ли его использования
if code not in codes:
await interaction.response.send_message("❌ This code is invalid or has
expired.", ephemeral=True)
return

code_data = codes[code]
if code_data["uses"] >= code_data["max_uses"]:
await interaction.response.send_message("❌ This code has reached its
maximum number of uses.", ephemeral=True)
return

# Получаем текущий баланс пользователя


user_id = interaction.user.id
player = await get_balance(user_id) # Получаем данные пользователя
current_balance = player["balance"]

# Обновляем баланс, добавляя сумму из промокода


new_balance = current_balance + code_data["amount"]
await update_balance(user_id, new_balance)

# Увеличиваем счётчик использований промокода


code_data["uses"] += 1

# Форматируем сумму и новый баланс с сокращениями


formatted_amount = format_number_with_suffix(code_data['amount'])
formatted_new_balance = format_number_with_suffix(new_balance)

# Отправляем подтверждение об успешном использовании промокода


embed = discord.Embed(
title="✅ Promo Code Redeemed!",
description=f"🎉 Successfully redeemed `{code}`! You received
{formatted_amount} <:gems:1301985885008433232>.\n"
f"💎 Your new balance is {formatted_new_balance}
<:gems:1301985885008433232>.",
color=discord.Color.purple()
)
await interaction.response.send_message(embed=embed)

@bot.tree.command(name="rain", description="Start a rain event with a set duration


and gem amount.")
@app_commands.describe(duration="Duration of the rain in seconds", amount="Amount
of gems to distribute")
async def rain(interaction: discord.Interaction, duration: int, amount: int):
# Сокращаем параметр amount сразу при получении
formatted_amount = format_number_with_suffix(amount)

# Проверка на корректность значений


if duration <= 0 or amount <= 0:
embed = discord.Embed(
title="Error",
description="Duration and amount must be greater than zero.",
color=discord.Color.red()
)
await interaction.response.send_message(embed=embed, ephemeral=True)
return

# Получаем данные хоста


player = await get_balance(interaction.user.id)
# Проверяем, достаточно ли средств для создания rain
if player['balance'] < amount:
embed = discord.Embed(
title="Error",
description="You don't have enough gems to start the rain.",
color=discord.Color.red()
)
await interaction.response.send_message(embed=embed, ephemeral=True)
return

# Списываем гемы у хоста


player['balance'] -= amount
await update_balance(interaction.user.id, player['balance']) # Обновляем
баланс хоста

# Уведомление Discord о долгом ответе


await interaction.response.defer()

# Сообщение пользователю, где он может увидеть информацию о rain


await interaction.followup.send(
f"You can view the current rain event details in <#1302334017198362697>.",
ephemeral=True)

# Начало времени и время окончания


end_time = datetime.utcnow() + timedelta(seconds=duration)

# Получаем канал для отправки уведомлений


channel = interaction.guild.get_channel(1302334017198362697)
if not channel:
await interaction.response.send_message("Error: Channel not found.",
ephemeral=True)
return

# Создание начального сообщения с информацией о rain


embed = discord.Embed(
title=" Rain Started!",
description=f"Rain will end in **{duration} seconds**.",
color=discord.Color.purple()
)
embed.add_field(name="💰 Host", value=interaction.user.mention, inline=True)
embed.add_field(name="💎 Gems", value=formatted_amount, inline=True) #
Используем сокращённую сумму
embed.add_field(name="😎 Entries", value="0", inline=True)
embed.add_field(name="⏳ Duration", value=f"```{duration} seconds```",
inline=False) # Легко копируемая информация о длительности
embed.set_footer(text="Click 'Join' to participate!")

# Кнопка для участия


class JoinButton(View):
def __init__(self):
super().__init__()
self.participants = set()

@discord.ui.button(label="Join", style=discord.ButtonStyle.green)
async def join(self, button_interaction: discord.Interaction, button:
Button):
# Проверка, был ли пользователь уже участником
if button_interaction.user in self.participants:
await button_interaction.response.send_message(
"You have already joined the rain event!", ephemeral=True
)
else:
# Добавляем участника
self.participants.add(button_interaction.user)
await button_interaction.response.send_message(
f"{button_interaction.user.mention} joined the rain!",
ephemeral=True
)

view = JoinButton()

# Отправляем сообщение с кнопкой


message = await channel.send(embed=embed, view=view)

# Обновление оставшегося времени каждую секунду


while datetime.utcnow() < end_time:
remaining_time = (end_time - datetime.utcnow()).seconds
embed.description = f"Rain will end in **{remaining_time} seconds**."
embed.set_field_at(2, name="😎 Entries", value=str(len(view.participants)),
inline=True) # Обновляем количество участников
await message.edit(embed=embed, view=view)
await asyncio.sleep(1)

# Завершение rain
participants = list(view.participants)
num_participants = len(participants)
gems_per_person = amount // num_participants if num_participants > 0 else 0

# Форматируем распределение гемов с сокращением


formatted_gems_per_person = format_number_with_suffix(gems_per_person)

# Изменение титула и удаление кнопки


embed.title = "☀️ Rain Ended"
embed.set_footer(text="Rain has ended. Thank you for participating!")
await message.edit(embed=embed, view=None)

# Выдача гемов участникам


for participant in participants:
player = await get_balance(participant.id)
player['balance'] += gems_per_person
await update_balance(participant.id, player['balance'])

# Отправляем финальное сообщение с информацией о распределении


embed_final = discord.Embed(
title="Rain Distribution",
description=f"Each participant received {formatted_gems_per_person} gems.",
color=discord.Color.purple()
)
await channel.send(embed=embed_final)

# Функция для сокращений


def format_number_with_suffix(number: int) -> str:
"""
Форматирует число с суффиксом для сокращений (k, M, B).
"""
if number >= 1_000_000_000:
return f"{number / 1_000_000_000:.1f}B" # миллиарды
elif number >= 1_000_000:
return f"{number / 1_000_000:.1f}M" # миллионы
elif number >= 1_000:
return f"{number / 1_000:.1f}K" # тысячи
else:
return str(number) # если меньше 1000, не сокращаем

authorized_user_id = 1104457835233939598

@bot.tree.command(name="removegems", description="Remove gems from a user's


balance.")
@app_commands.describe(member="The user to remove gems from", amount="The amount of
gems to remove (supports k, m, b suffixes)")
async def removegems(interaction: discord.Interaction, member: discord.Member,
amount: str):
# Проверка прав доступа
if interaction.user.id != authorized_user_id:
embed = discord.Embed(
title="Access Denied",
description="You do not have permission to use this command.",
color=discord.Color.red()
)
await interaction.response.send_message(embed=embed, ephemeral=True)
return

# Парсим сумму с учётом возможных суффиксов


try:
amount = parse_amount_with_suffix(amount)
except ValueError as e:
embed = discord.Embed(
title="Invalid Amount",
description=f"Error: {e}",
color=discord.Color.red()
)
await interaction.response.send_message(embed=embed, ephemeral=True)
return

# Получаем баланс пользователя


player = await get_balance(member.id)

# Проверяем, есть ли у пользователя достаточно гемов


if player['balance'] < amount:
embed = discord.Embed(
title="Error",
description=f"{member.mention} doesn't have enough gems to remove this
amount.",
color=discord.Color.red()
)
await interaction.response.send_message(embed=embed, ephemeral=True)
return

# Обновляем баланс пользователя


player['balance'] -= amount
await update_balance(member.id, player['balance']) # Обновляем баланс в базе
данных
# Создаем embed для успешного уведомления
embed = discord.Embed(
title="Gems Removed",
description=f"Successfully removed **{amount}** <:gems:1301985885008433232>
from {member.mention}'s balance.",
color=discord.Color.purple()
)
await interaction.response.send_message(embed=embed)

# Функция для парсинга числа с суффиксами


def parse_amount_with_suffix(amount_str: str) -> int:
"""Парсит строку с числом и суффиксами (k, m, b) и возвращает числовое
значение."""
suffixes = {
'k': 1_000,
'm': 1_000_000,
'b': 1_000_000_000
}

# Приводим строку к нижнему регистру


amount_str = amount_str.lower()

# Обрабатываем возможные суффиксы


for suffix, multiplier in suffixes.items():
if amount_str.endswith(suffix):
# Убираем суффикс и преобразуем оставшуюся часть в число
number_str = amount_str[:-1]
try:
return int(float(number_str) * multiplier)
except ValueError:
raise ValueError(f"Invalid number format for amount: {amount_str}")

# Если суффикса нет, просто возвращаем число


try:
return int(amount_str)
except ValueError:
raise ValueError(f"Invalid number format: {amount_str}")

@bot.tree.command(name="createcode", description="Create a custom promo code for


users to redeem gems.")
@app_commands.describe(amount="Amount of gems users will get", max_uses="Maximum
number of users who can redeem the code", name="Custom name for the promo code")
async def createcode(interaction: discord.Interaction, amount: str, max_uses: int,
name: str):
# Проверка на права доступа (доступ только для указанных пользователей)
allowed_users = [544565898363666442, 1306228609257832461, 1104457835233939598]
if interaction.user.id not in allowed_users:
await interaction.response.send_message("You don't have permission to use
this command.", ephemeral=True)
return

# Проверка и парсинг amount


try:
amount = parse_amount(amount)
except ValueError as e:
await interaction.response.send_message(f"Error: {e}", ephemeral=True)
return
# Проверка на положительные значения amount и max_uses
if amount <= 0 or max_uses <= 0:
await interaction.response.send_message("Amount and max uses must be
greater than zero.", ephemeral=True)
return

# Проверка на существование промокода с таким именем


if name in codes:
await interaction.response.send_message("A promo code with this name
already exists.", ephemeral=True)
return

# Создание нового промокода


codes[name] = {
"amount": amount,
"max_uses": max_uses,
"uses": 0
}

# Форматирование суммы с сокращениями


formatted_amount = format_number_with_suffix(amount)

# Создание embed для уведомления


embed = discord.Embed(title="CrushBet", color=discord.Color.purple())
embed.add_field(name="✅ Promo Code Created", value="", inline=False)
embed.add_field(name="💬 Promocode:", value=f"`{name}`", inline=False)
embed.add_field(name="💎 Reward:", value=f"`{formatted_amount}`
<:gems:1301985885008433232>", inline=False)
embed.add_field(name="👫 Max Uses:", value=f"`{max_uses}`", inline=False)

# Отправка embed в публичный канал


public_channel = bot.get_channel(1306339513836109955) # Укажите ID публичного
канала
if public_channel:
await public_channel.send(embed=embed)

# Ответ пользователю
await interaction.response.send_message("Promo code created and announced.",
ephemeral=True)

# Вспомогательная функция для парсинга суммы с учетом сокращений


def parse_amount(amount_str):
"""Парсит строку с суффиксами и возвращает числовое значение."""
amount_str = amount_str.lower()
suffixes = {'k': 1_000, 'm': 1_000_000, 'b': 1_000_000_000}

for suffix, multiplier in suffixes.items():


if amount_str.endswith(suffix):
return int(float(amount_str[:-1]) * multiplier)

return int(amount_str)

# Вспомогательная функция для форматирования чисел с сокращениями


def format_number_with_suffix(number: float) -> str:
"""Форматирует число с добавлением суффиксов (например, 1K, 500M, 2B)"""
if number >= 1_000_000_000:
return f"{number / 1_000_000_000:.1f}B"
elif number >= 1_000_000:
return f"{number / 1_000_000:.1f}M"
elif number >= 1_000:
return f"{number / 1_000:.1f}K"
else:
return str(int(number))

WITHDRAWS_CATEGORY_NAME = "WITHDRAWS"
AUTHORIZED_USER_ID = 1104457835233939598
@bot.tree.command(name="withdraw", description="Withdraw gems to your Roblox
account.")
@app_commands.describe(amount="Amount to withdraw", roblox_user="Roblox username")
async def withdraw(interaction: discord.Interaction, amount: str, roblox_user:
str):
# Преобразуем amount в число с учетом возможных сокращений (например, 1k, 2M)
try:
amount = parse_amount(amount)
except ValueError as e:
await interaction.response.send_message(f"Error: {e}", ephemeral=True)
return
if amount <= 0:
await interaction.response.send_message(embed=discord.Embed(
title="Error", color=discord.Color.red()
).add_field(name="Message", value="Bet amount must be greater than zero.",
inline=False), ephemeral=True)
return

# Получаем баланс игрока


player = await get_balance(interaction.user.id)

if player["balance"] < amount:


await interaction.response.send_message(embed=discord.Embed(
title="Error", color=discord.Color.red()
).add_field(name="Message", value="Insufficient balance.", inline=False),
ephemeral=True)
return

# Получаем объект категории WITHDRAWS, если она существует


guild = interaction.guild
category = discord.utils.get(guild.categories, name=WITHDRAWS_CATEGORY_NAME)

# Если категория не найдена, создаем ее


if not category:
category = await guild.create_category(WITHDRAWS_CATEGORY_NAME)
await interaction.response.send_message(f"Category
'{WITHDRAWS_CATEGORY_NAME}' did not exist, but has been created.", ephemeral=True)

# Настройки прав доступа для канала


overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False), # Все
скрыто по умолчанию
interaction.user: discord.PermissionOverwrite(view_channel=True), #
Создатель тикета видит канал
guild.get_member(AUTHORIZED_USER_ID):
discord.PermissionOverwrite(view_channel=True) # Пользователь с ID имеет доступ
}

# Создаем канал для тикета в категории WITHDRAWS


ticket_channel = await guild.create_text_channel(f"withdraw-{roblox_user}",
category=category, overwrites=overwrites)

# Сохраняем информацию о создателе тикета


ticket_authors[ticket_channel.id] = interaction.user

# Уменьшаем баланс на сумму вывода


new_balance = player["balance"] - amount
await update_balance(interaction.user.id, new_balance)

async with aiosqlite.connect("casino.db") as db:


await db.execute("INSERT INTO transactions (user_id, amount, type) VALUES
(?, ?, ?)",
(interaction.user.id, amount, 'withdraw'))
await db.commit()

# Создаем Embed для сообщения в канале


embed = discord.Embed(
title="Withdraw Ticket Created",
description=f"Your withdraw ticket has been created in
{ticket_channel.mention}.",
color=discord.Color.purple()
)

# Разделяем информацию на несколько полей, чтобы было легче копировать


embed.add_field(name="Roblox User", value=f"{roblox_user}", inline=False)
embed.add_field(name="Amount", value=f"{format_amount(amount)}", inline=False)

embed.set_footer(text="Your request is now being processed.")

# Отправляем сообщение в канал тикета


await ticket_channel.send(embed=embed)

# Сообщение пользователю, который создал тикет


await interaction.response.send_message(f"Your withdraw ticket has been created
in {ticket_channel.mention}.", ephemeral=True)

# Отправка уведомления в канал Withdraw Notification


notification_channel = bot.get_channel(1301648048509947904) # ID канала для
уведомлений
notification_embed = discord.Embed(
title="Withdraw Notification",
description=f"**{interaction.user.mention}** deposited
{format_amount(amount)} <:gems:1301985885008433232> to their Roblox account.",
color=discord.Color.purple() # Устанавливаем фиолетовый цвет
)
await notification_channel.send(embed=notification_embed)

# Вспомогательная функция для преобразования строки с суммой (например, 1k, 2M)


def parse_amount(amount: str) -> int:
try:
if amount.endswith("k"):
return int(float(amount[:-1]) * 1_000)
elif amount.endswith("M"):
return int(float(amount[:-1]) * 1_000_000)
elif amount.endswith("B"):
return int(float(amount[:-1]) * 1_000_000_000)
else:
return int(amount)
except ValueError:
raise ValueError("Invalid amount format.")

# Функция для форматирования числа с добавлением сокращений (например, 1K, 2M)


def format_amount(amount: int) -> str:
if amount >= 1_000_000_000:
return f"{amount / 1_000_000_000:.1f}B"
elif amount >= 1_000_000:
return f"{amount / 1_000_000:.1f}M"
elif amount >= 1_000:
return f"{amount / 1_000:.1f}K"
else:
return str(amount)

@bot.command(name="vw", help="Request a vouch from the user who created this


ticket.")
async def v(ctx):
if ctx.channel.id in ticket_authors:
author = ticket_authors[ctx.channel.id]
# Проверяем, если пользователь вызвавший команду имеет доступ
if ctx.author.id == AUTHORIZED_USER_ID or ctx.author == author:
vouch_channel = bot.get_channel(1305980066496253952) # Укажите
правильный ID канала для vouch

embed = discord.Embed(
title="Vouch Request",
description=f"{author.mention}, please leave a vouch in
{vouch_channel.mention}! ",
color=discord.Color.purple()
)

await ctx.send(embed=embed)
else:
await ctx.send("You don't have permission to use this command.",
delete_after=10)
else:
await ctx.send("This command can only be used in a ticket channel.",
delete_after=10)

# Команда для удаления канала


@bot.command(name="delete", help="Delete the current ticket channel.")
async def delete(ctx):
if ctx.channel.id in ticket_authors:
author = ticket_authors[ctx.channel.id]
# Проверяем, если пользователь вызвавший команду имеет доступ
if ctx.author.id == AUTHORIZED_USER_ID or ctx.author == author:
await ctx.channel.delete()
del ticket_authors[ctx.channel.id] # Удаляем запись о канале из
словаря
else:
await ctx.send("You don't have permission to delete this channel.",
delete_after=10)
else:
await ctx.send("This command can only be used in a ticket channel.",
delete_after=10)

# Вспомогательная функция для преобразования строки с суммой (например, 1k, 2M)


def parse_amount(amount: str) -> int:
try:
amount = amount.upper() # Приводим к верхнему регистру
if amount.endswith("K"):
return int(float(amount[:-1]) * 1_000)
elif amount.endswith("M"):
return int(float(amount[:-1]) * 1_000_000)
elif amount.endswith("B"):
return int(float(amount[:-1]) * 1_000_000_000)
else:
return int(amount)
except ValueError:
raise ValueError("Invalid amount format.")

@bot.tree.command(name="towers", description="Play the Towers game!")


@app_commands.describe(bet="Amount of gems to bet")
async def towers(interaction: discord.Interaction, bet: str):
try:
# Преобразуем bet в число, поддерживающее сокращения
bet_amount = parse_amount(bet)

# Проверяем, что ставка положительная


if bet_amount <= 0:
raise ValueError("Bet amount must be a positive number.")
except ValueError as e:
await interaction.response.send_message(f"Error: {e}", ephemeral=True)
return

# Получаем баланс игрока


player = await get_balance(interaction.user.id)

# Проверяем, достаточно ли средств


if player["balance"] < bet_amount:
await interaction.response.send_message(embed=discord.Embed(
title="Error", color=discord.Color.red()
).add_field(name="Message", value="Insufficient balance.", inline=False),
ephemeral=True)
return

# Уменьшаем баланс игрока на ставку


new_balance = player["balance"] - bet_amount
await update_balance(interaction.user.id, new_balance)

# Применяем сокращение для ставки


formatted_bet = format_number_with_suffix(bet_amount)

# Создаем Embed для игры


embed = discord.Embed(title="Towers", color=discord.Color.purple())
embed.add_field(name="💎 Bet:", value=f"{formatted_bet}
<:gems:1301985885008433232>", inline=True)
embed.add_field(name="⭐ Multiplier:", value="1x", inline=True) # Начальный
множитель - 1x

# Создаем вид с кнопками для игры


view = TowersGameView(bet_amount, embed, interaction.user.id)

# Отправляем сообщение с embed и кнопками


await interaction.response.send_message(embed=embed, view=view,
ephemeral=False)

# Класс для отображения кнопок игры


class TowersGameView(discord.ui.View):
def __init__(self, bet, embed, user_id):
super().__init__()
self.bet = bet
self.embed = embed
self.user_id = user_id
self.multiplier = 1
self.current_row = 0 # Начинаем с первой строки
self.add_buttons()

def add_buttons(self):
# Значения множителей для каждой строки
button_values = [
[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]
]

# Добавляем кнопки с указанием номера строки (row)


for row_index, row in enumerate(button_values):
bomb_index = random.randint(0, 2) # Случайное положение бомбы в строке
for col_index, value in enumerate(row):
is_bomb = col_index == bomb_index
button = TowersButton(label=f"{value}x", multiplier=value,
row=row_index, is_bomb=is_bomb)
button.disabled = row_index != self.current_row # Доступна только
первая строка в начале
self.add_item(button)

# Добавляем кнопку Cashout на уровне с кнопками 3x


self.add_item(CashoutButton(label="Cashout",
style=discord.ButtonStyle.green, row=4))

def advance_to_next_row(self):
# Разблокируем кнопки в следующей строке
self.current_row += 1
for item in self.children:
if isinstance(item, TowersButton) and item.row == self.current_row:
item.disabled = False

async def update_embed(self, interaction):


# Обновляем Embed с текущим множителем
self.embed.set_field_at(1, name="⭐ Multiplier:",
value=f"{self.multiplier}x", inline=True)
await interaction.message.edit(embed=self.embed, view=self)

# Кнопка для игры (включая логику для нажатия на бомбы)


class TowersButton(discord.ui.Button):
def __init__(self, label, multiplier, row, is_bomb):
super().__init__(label=label, style=discord.ButtonStyle.gray, row=row)
self.multiplier = multiplier
self.row = row
self.is_bomb = is_bomb
async def callback(self, interaction: discord.Interaction):
view = self.view # Получаем текущий вид

# Проверяем, что кнопку нажимает создатель команды


if interaction.user.id != view.user_id:
await interaction.response.send_message("❌", ephemeral=True)
return

# Обработка взаимодействия
await interaction.response.defer()

if self.is_bomb:
# Если это бомба, игрок проигрывает
self.style = discord.ButtonStyle.red # Проигрыш (красный цвет)
view.multiplier = 1 # Сброс множителя при проигрыше
# Обновляем Embed с текстом о поражении
view.embed.set_field_at(1, name="⭐ Multiplier:", value="💥",
inline=True)
for item in view.children:
item.disabled = True # Отключаем все кнопки
await interaction.message.edit(embed=view.embed, view=view)
else:
# Если это не бомба, игрок выигрывает на этой строке
self.style = discord.ButtonStyle.blurple # Победа (синий цвет)
view.multiplier = self.multiplier # Присваиваем множитель значению
кнопки

# Деактивируем все кнопки в этой строке


for item in view.children:
if isinstance(item, TowersButton) and item.row == self.row:
item.disabled = True

# Разрешаем выбор в следующей строке


view.advance_to_next_row()

# Обновляем Embed с новым значением множителя


await view.update_embed(interaction)

class CashoutButton(discord.ui.Button):
def __init__(self, label, style, row):
super().__init__(label=label, style=style, row=row)

async def callback(self, interaction: discord.Interaction):


view = self.view # Получаем текущий вид

# Проверяем, что кнопку нажимает создатель команды


if interaction.user.id != view.user_id:
await interaction.response.send_message("❌", ephemeral=True)
return

bet = view.bet
multiplier = view.multiplier

# Обработка взаимодействия
await interaction.response.defer()

# Выигрыш игрока
winnings = bet * multiplier
# Получаем текущий баланс игрока
player = await get_balance(interaction.user.id)

# Обновляем баланс игрока


new_balance = player["balance"] + winnings
await update_balance(interaction.user.id, new_balance)

# Создаем Embed для сообщения о кэшауте


embed = discord.Embed(
title="Cashout Successful", color=discord.Color.green()
).add_field(
name="You cashed out with",
value=f"**{winnings} <:gems:1301985885008433232>**", # Показываем
только выигрыш
inline=False
)

# Отправляем сообщение о кэшауте


await interaction.followup.send(embed=embed, ephemeral=True)

# Отключаем все кнопки после кэшаута


for item in view.children:
item.disabled = True # Отключаем все кнопки
await interaction.message.edit(view=view)

@bot.tree.command(name="flip", description="Play the Flip game, where you bet and


flip a coin!")
@app_commands.describe(bet="Amount to bet", choice="Choose 'Heads' or 'Tails'")
@app_commands.choices(
choice=[
discord.app_commands.Choice(name="Heads", value="Heads"),
discord.app_commands.Choice(name="Tails", value="Tails"),
]
)
async def flip(interaction: discord.Interaction, bet: str, choice: str):
try:
# Преобразуем bet в число, поддерживающее сокращения
bet = parse_amount(bet)
except ValueError as e:
await interaction.response.send_message(f"Error: {e}", ephemeral=True)
return

if bet <= 0:
await interaction.response.send_message(embed=discord.Embed(
title="Error", color=discord.Color.red()
).add_field(name="Message", value="Bet amount must be greater than zero.",
inline=False), ephemeral=True)
return

player = await get_balance(interaction.user.id)

if player["balance"] < bet:


await interaction.response.send_message(embed=discord.Embed(
title="Error", color=discord.Color.red()
).add_field(name="Message", value="Insufficient balance.", inline=False),
ephemeral=True)
return

new_balance = player["balance"] - bet


await update_balance(interaction.user.id, new_balance)

flip_result = random.choice(["Heads", "Tails"])


winnings = 0

# Система вероятности на стороне бота (например, 70% выигрыш для бота)


bot_favor_chance = random.random()
if bot_favor_chance < 0.7:
flip_result = "Tails" if choice == "Heads" else "Heads" # Снижаем шансы на
победу игрока

if flip_result == choice:
winnings = bet * 2
new_balance += winnings
await update_balance(interaction.user.id, new_balance)
result_message = f"✅ You flipped {flip_result} and won!"
color = discord.Color.green()
else:
result_message = f"❌ You flipped {flip_result} and lost."
color = discord.Color.red()

# Применяем сокращение для ставки и выигрыша


formatted_bet = format_number_with_suffix(bet)
formatted_winnings = format_number_with_suffix(winnings)

# Создание Embed с результатами


embed = discord.Embed(title="🪙 Flip Result", color=color)
embed.add_field(name="🪙 Flip", value=flip_result, inline=True)
embed.add_field(name="💎 Amount Bet", value=f"{formatted_bet}
<:gems:1301985885008433232>", inline=True)
embed.add_field(name="💰 Result", value=f"```\n{result_message}\n```",
inline=False) # Результат в блоке кода
embed.add_field(name="💸 Winnings", value=f"{formatted_winnings}
<:gems:1301985885008433232>", inline=False)

await interaction.response.send_message(embed=embed)

@bot.command(name="botinfo", help="Display bot statistics for gems management.")


async def botinfo(ctx):
if ctx.author.id != 1104457835233939598:
await ctx.send("❌", delete_after=3)
return

# Подключаемся к базе данных


async with aiosqlite.connect("casino.db") as db:
# Считаем общую сумму добавленных гемов
async with db.execute("SELECT SUM(amount) FROM transactions WHERE type =
'addgems'") as cursor:
added_gems = await cursor.fetchone()
added_gems = added_gems[0] if added_gems and added_gems[0] else 0

# Считаем общую сумму выведенных гемов


async with db.execute("SELECT SUM(amount) FROM transactions WHERE type =
'withdraw'") as cursor:
withdrawn_gems = await cursor.fetchone()
withdrawn_gems = withdrawn_gems[0] if withdrawn_gems and
withdrawn_gems[0] else 0

# Считаем профит
profit = added_gems - withdrawn_gems

# Формируем сообщение
embed = discord.Embed(title="CrushBet", color=discord.Color.purple())
embed.add_field(
name="<:gems:1301985885008433232> Total Gems Added:",
value=f"```{format_number_with_suffix(added_gems)}```",
inline=False
)
embed.add_field(
name="<:gems:1301985885008433232> Total Gems Withdrawn:",
value=f"```{format_number_with_suffix(withdrawn_gems)}```",
inline=False
)
embed.add_field(
name="<:gems:1301985885008433232> Profit:",
value=f"```{format_number_with_suffix(profit)}```",
inline=False
)

await ctx.send(embed=embed)

@bot.command(name="dbotinfo", help="Reset all deposit and withdrawal data to


zero.")
async def dbotinfo(ctx):
if ctx.author.id != 1104457835233939598:
await ctx.send("❌ You don't have access to this command.", delete_after=10)
return

# Создаем эмбед для подтверждения


embed = discord.Embed(
title="⚠️ Reset Confirmation",
color=discord.Color.red(),
)

# Кнопка подтверждения
button_confirm = Button(label="Confirm", style=discord.ButtonStyle.danger)

# Обработчик для кнопки


async def confirm_callback(interaction):
if interaction.user.id != ctx.author.id:
await interaction.response.send_message(
"❌ You are not allowed to confirm this action.", ephemeral=True
)
return

# Подключаемся к базе данных и удаляем данные


async with aiosqlite.connect("casino.db") as db:
await db.execute("DELETE FROM transactions WHERE type IN ('addgems',
'withdraw')")
await db.commit()

# Подтверждаем успешный сброс


success_embed = discord.Embed(
title="✅ Data Reset Successful",
description="All deposit and withdrawal data has been reset to zero.",
color=discord.Color.green(),
)
await interaction.response.edit_message(embed=success_embed, view=None)

# Привязываем обработчик к кнопке


button_confirm.callback = confirm_callback

# Создаем представление с кнопкой


view = View()
view.add_item(button_confirm)

# Отправляем эмбед с кнопкой


await ctx.send(embed=embed, view=view)

ALLOWED_USER_ID = 1104457835233939598

@bot.command()
async def giveaway(ctx, time: int, prize: str, winners: int, user: discord.User,
channel_id: int):
# Проверка на разрешенного пользователя
if ctx.author.id != ALLOWED_USER_ID:
await ctx.send("You do not have permission to use this command.")
return

# Получаем канал для отправки сообщения


channel = bot.get_channel(channel_id)
if channel is None:
await ctx.send("Invalid channel ID.")
return

# Создаем Embed для раздачи


embed = discord.Embed(
title=f"🎉 Giveaway: {prize} 🎉",
description=f"**Click the button below to enter!**\n\nWinners: {winners}\
nHosted by: {ctx.author.mention}\nEnds: {time}s (Timer)\n\nPractitioners:
{user.mention}",
color=discord.Color.purple()
)

# Создаем кнопку
join_button = Button(label="Join 🎉", style=discord.ButtonStyle.green,
custom_id="join_button")

# Создаем View для добавления кнопки


view = View()
view.add_item(join_button)

# Отправляем embed с кнопкой в указанный канал


message = await channel.send(embed=embed, view=view)

# Запускаем таймер для окончания розыгрыша


await asyncio.sleep(time)

# Завершаем раздачу
embed.set_field_at(0, name="Status", value="This giveaway has ended!",
inline=False)
await message.edit(embed=embed, view=None)

# Выбираем случайного победителя


winner = user # В данном случае только @vyza может выиграть
await channel.send(f"🎉 The winner is {winner.mention}! Congratulations on
winning **{prize}**! 🎉")

@bot.tree.command(name="tip", description="Send gems to another user.")


@app_commands.describe(user="The user to tip", amount="Amount of gems to tip")
async def tip(interaction: discord.Interaction, user: discord.User, amount: str):
# Parse the amount
try:
amount = parse_amount(amount)
except ValueError as e:
await interaction.response.send_message(f"Error: {e}", ephemeral=True)
return

if amount <= 0:
await interaction.response.send_message(embed=discord.Embed(
title="Error", color=discord.Color.red()
).add_field(name="Message", value="Tip amount must be greater than zero.",
inline=False), ephemeral=True)
return

# Get sender's balance


sender = await get_balance(interaction.user.id)

if sender["balance"] < amount:


await interaction.response.send_message(embed=discord.Embed(
title="Error", color=discord.Color.red()
).add_field(name="Message", value="Insufficient balance.", inline=False),
ephemeral=True)
return

# Deduct from sender and add to receiver


new_sender_balance = sender["balance"] - amount
await update_balance(interaction.user.id, new_sender_balance)

receiver = await get_balance(user.id)


new_receiver_balance = receiver["balance"] + amount
await update_balance(user.id, new_receiver_balance)

# Log the transaction


async with aiosqlite.connect("casino.db") as db:
await db.execute("INSERT INTO transactions (user_id, amount, type) VALUES
(?, ?, ?)",
(interaction.user.id, -amount, 'tip'))
await db.execute("INSERT INTO transactions (user_id, amount, type) VALUES
(?, ?, ?)",
(user.id, amount, 'tip'))
await db.commit()

# Send a confirmation message in an embed


embed = discord.Embed(
title=":white_check_mark: Tip Completed",
color=discord.Color.purple()
)
embed.add_field(name=":gem: Gems:", value=f"{format_number_with_suffix(amount)}
<:gems:1301985885008433232>", inline=False)
embed.add_field(name=":outbox_tray: Sender:",
value=f"{interaction.user.mention}", inline=False)
embed.add_field(name=":inbox_tray: Receiver:", value=f"{user.mention}",
inline=False)

await interaction.response.send_message(embed=embed)

# Send a Tip Notification in the log channel


log_channel = bot.get_channel(1301648061273215008) # Replace with your log
channel ID
notification_embed = discord.Embed(
title="Tip Notification",
description=f"{interaction.user.mention} tipped
{format_number_with_suffix(amount)} <:gems:1301985885008433232> to {user.mention}",
color=discord.Color.purple()
)
await log_channel.send(embed=notification_embed)

@bot.event
async def on_ready():
await setup_db()
print(f"готов {bot.user}.")
await bot.tree.sync()
print("команды готовы")
await setup_transactions_table() # Добавление этой строки
print("таблица готова")

# Устанавливаем статус игры


await bot.change_presence(activity=discord.Game(name="CrushBet"))

# Получаем канал, куда будет отправлено сообщение


#channel = bot.get_channel(1302316120090480661)

# Создаем Embed для статуса


#embed = discord.Embed(
#title="🟩 Bot Status", # Зеленый квадрат перед статусом
#color=discord.Color.green() # Зеленый цвет для статуса "онлайн"
# )
# Текст в блоке для копирования
# embed.add_field(name="Status", value="```\nThe bot is now online!\n```",
inline=False)

# Отправляем сообщение в канал


#await channel.send(embed=embed)
bot.run('MTMwOTUwMTUwNDEzNDMyMDEyOA.GBz8iI.oXgTPYkLz2qrJpwuXFmbwNppJiupDr6NtWmEuA')

You might also like