Remove the items, admin commands and shop.
"import discord
from discord.ext import commands
import json
import os
import random
from discord.ext.commands import BucketType
import logging
Configurar logging
logging.basicConfig(level=logging.INFO)
Definir as intents
intents = discord.Intents.default()
intents.members = True # Necessário para acessar informações dos membros
intents.message_content = True # Necessário para ler o conteúdo das mensagens para comandos de prefixo
-------------------- Funções de Carregamento e Salvamento --------------------
def load_data(file_path, default):
try:
if not os.path.isfile(file_path):
with open(file_path, 'w') as f:
json.dump(default, f, indent=4)
with open(file_path, 'r') as f:
return json.load(f)
except json.JSONDecodeError:
logging.error(f"Erro ao decodificar {file_path}. Reiniciando o arquivo.")
return default
except Exception as e:
logging.error(f"Erro ao carregar {file_path}: {e}")
return default
def save_data(file_path, data):
try:
with open(file_path, 'w') as f:
json.dump(data, f, indent=4)
except Exception as e:
logging.error(f"Erro ao salvar em {file_path}: {e}")
-------------------- Eventos do Bot --------------------
@bot.event
async def on_ready():
logging.info(f'Logado como {bot.user.name} - {bot.user.id}')
Assistant
@bot.event
async def on_message(message):
if message.author == bot.user:
return
logging.info(f'Mensagem de {message.author}: {message.content}')
await bot.process_commands(message)
-------------------- Comandos de Economia --------------------
@bot.command(name='balance', help='Verifique seu saldo')
async def balance(ctx):
data = load_currency()
user_id = ctx.author.id
bal = get_balance(user_id, data)
await ctx.send(f'{ctx.author.mention}, você tem {bal} moedas.')
@balance.error
async def balance_error(ctx, error):
if isinstance(error, commands.CommandError):
await ctx.send('Ocorreu um erro ao buscar seu saldo.')
@bot.command(name='work', help='Ganhe uma pequena quantidade de moedas. Tempo de espera: 1 hora')
@commands.cooldown(rate=1, per=3600, type=BucketType.user) # 1 hora de espera por usuário
async def work(ctx):
data = load_currency()
user_id = ctx.author.id
# Definir a quantidade ganha com trabalho
earned = random.randint(10, 50)
add_currency(user_id, earned, data)
save_currency(data)
await ctx.send(f'{ctx.author.mention}, você trabalhou e ganhou {earned} moedas!')
@work.error
async def work_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
remaining = int(error.retry_after)
hours, remainder = divmod(remaining, 3600)
minutes, seconds = divmod(remainder, 60)
await ctx.send(f'{ctx.author.mention}, você pode usar o comando work novamente em {hours}h {minutes}m {seconds}s.')
else:
await ctx.send('Ocorreu um erro ao processar o comando.')
@bot.command(name='crime', help='Tente cometer um crime para uma grande recompensa ou enfrente uma perda. Tempo de espera: 1 hora')
@commands.cooldown(rate=1, per=3600, type=BucketType.user) # 1 hora de espera por usuário
async def crime(ctx):
data = load_currency()
user_id = ctx.author.id
# Definir taxa de sucesso
success_chance = 0.3 # 30% de chance de sucesso
if random.random() < success_chance:
# Sucesso: Ganhar uma grande quantidade
earned = random.randint(100, 500)
add_currency(user_id, earned, data)
save_currency(data)
await ctx.send(f'🎉 {ctx.author.mention}, você cometeu um crime com sucesso e ganhou {earned} moedas!')
else:
# Falha: Perder uma quantidade significativa
lost = random.randint(50, 300)
if subtract_currency(user_id, lost, data):
save_currency(data)
await ctx.send(f'⚠️ {ctx.author.mention}, sua tentativa de crime falhou! Você perdeu {lost} moedas.')
else:
# Usuário não tem saldo suficiente para perder
await ctx.send(f'⚠️ {ctx.author.mention}, sua tentativa de crime falhou! Mas você não tem moedas suficientes para perder.')
@crime.error
async def crime_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
remaining = int(error.retry_after)
hours, remainder = divmod(remaining, 3600)
minutes, seconds = divmod(remainder, 60)
await ctx.send(f'{ctx.author.mention}, você pode usar o comando crime novamente em {hours}h {minutes}m {seconds}s.')
else:
await ctx.send('Ocorreu um erro ao processar o comando.')
-------------------- Comandos de Jogos --------------------
Comando Blackjack com aposta variável
@bot.command(name='blackjack', help='Jogue uma partida de Blackjack contra o bot. Uso: !blackjack ')
async def blackjack(ctx, amount: int):
data = load_currency()
user_id = ctx.author.id
user_balance = get_balance(user_id, data)
if amount <= 0:
await ctx.send(f'{ctx.author.mention}, o valor da aposta deve ser maior que 0.')
return
if user_balance < amount:
await ctx.send(f'{ctx.author.mention}, você não tem moedas suficientes para apostar {amount} moedas.')
return
# Deduzir a aposta imediatamente
subtract_currency(user_id, amount, data)
save_currency(data)
# Inicializar estado do jogo
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11] * 4 # Baralho simplificado
random.shuffle(deck)
player_hand = [deck.pop(), deck.pop()]
bot_hand = [deck.pop(), deck.pop()]
game_state = {
'player_hand': player_hand,
'bot_hand': bot_hand,
'deck': deck,
'bet': amount,
'status': 'playing'
}
# Salvar estado do jogo
blackjack_data = load_blackjack()
blackjack_data[str(user_id)] = game_state
save_blackjack(blackjack_data)
# Calcular pontuações iniciais
def calculate_score(hand):
score = sum(hand)
# Ajustar para ases
while score > 21 and 11 in hand:
hand.remove(11)
hand.append(1)
score = sum(hand)
return score
player_score = calculate_score(player_hand)
bot_score = calculate_score(bot_hand)
# Mostrar mãos iniciais
await ctx.send(
f'**Blackjack**\n'
f'Sua Mão: {player_hand} (Total: {player_score})\n'
f'Mão do Bot: [{bot_hand[0]}, ?]'
f'\n\nDigite `!hit` para pegar mais uma carta ou `!stand` para segurar seu total.'
)
@blackjack.error
async def blackjack_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('Uso inválido. Por favor, use: !blackjack <quantia>.')
elif isinstance(error, commands.BadArgument):
await ctx.send('A quantia deve ser um número inteiro válido.')
else:
await ctx.send('Ocorreu um erro ao iniciar uma partida de Blackjack.')
@bot.command(name='hit', help='Pegar outra carta no Blackjack.')
async def hit(ctx):
data = load_currency()
user_id = ctx.author.id
blackjack_data = load_blackjack()
if str(user_id) not in blackjack_data:
await ctx.send(f'{ctx.author.mention}, você não está atualmente em uma partida de Blackjack. Inicie uma com `!blackjack <quantia>`.')
return
game = blackjack_data[str(user_id)]
if game['status'] != 'playing':
await ctx.send(f'{ctx.author.mention}, a partida já terminou. Inicie uma nova com `!blackjack <quantia>`.')
return
deck = game['deck']
player_hand = game['player_hand']
if not deck:
await ctx.send('O baralho está sem cartas! Finalizando a partida.')
game['status'] = 'ended'
blackjack_data[str(user_id)] = game
save_blackjack(blackjack_data)
return
# Adicionar uma carta na mão do jogador
new_card = deck.pop()
player_hand.append(new_card)
player_score = sum(player_hand)
# Ajustar para ases
while player_score > 21 and 11 in player_hand:
player_hand.remove(11)
player_hand.append(1)
player_score = sum(player_hand)
# Atualizar estado do jogo
game['deck'] = deck
game['player_hand'] = player_hand
blackjack_data[str(user_id)] = game
save_blackjack(blackjack_data)
if player_score > 21:
# Jogador estoura
game['status'] = 'ended'
blackjack_data[str(user_id)] = game
save_blackjack(blackjack_data)
await ctx.send(
f'Você puxou um {new_card}. Seu total é {player_score}. Você estourou! Você perde {game["bet"]} moedas.'
)
else:
await ctx.send(
f'Você puxou um {new_card}. Seu total é {player_score}. Digite `!hit` para puxar novamente ou `!stand` para segurar.'
)
@hit.error
async def hit_error(ctx, error):
await ctx.send('Ocorreu um erro ao tentar puxar uma carta.')
@bot.command(name='stand', help='Segurar seu total no Blackjack.')
async def stand(ctx):
data = load_currency()
user_id = ctx.author.id
blackjack_data = load_blackjack()
if str(user_id) not in blackjack_data:
await ctx.send(f'{ctx.author.mention}, você não está atualmente em uma partida de Blackjack. Inicie uma com `!blackjack <quantia>`.')
return
game = blackjack_data[str(user_id)]
if game['status'] != 'playing':
await ctx.send(f'{ctx.author.mention}, a partida já terminou. Inicie uma nova com `!blackjack <quantia>`.')
return
deck = game['deck']
player_hand = game['player_hand']
bot_hand = game['bot_hand']
# Calcular pontuação do jogador
player_score = sum(player_hand)
while player_score > 21 and 11 in player_hand:
player_hand.remove(11)
player_hand.append(1)
player_score = sum(player_hand)
# Turno do bot
bot_score = sum(bot_hand)
while bot_score < 17:
if not deck:
await ctx.send('O baralho está sem cartas! Finalizando a partida.')
game['status'] = 'ended'
blackjack_data[str(user_id)] = game
save_blackjack(blackjack_data)
return
new_card = deck.pop()
bot_hand.append(new_card)
bot_score = sum(bot_hand)
while bot_score > 21 and 11 in bot_hand:
bot_hand.remove(11)
bot_hand.append(1)
bot_score = sum(bot_hand)
# Determinar o resultado
if bot_score > 21:
outcome = 'bot_estourou'
elif bot_score > player_score:
outcome = 'bot_ganha'
elif bot_score < player_score:
outcome = 'jogador_ganha'
else:
outcome = 'empate'
# Atualizar estado do jogo
game['deck'] = deck
game['player_hand'] = player_hand
game['bot_hand'] = bot_hand
game['status'] = 'ended'
blackjack_data[str(user_id)] = game
save_blackjack(blackjack_data)
# Preparar resposta
response = (
f'**Resultado do Blackjack**\n'
f'Sua Mão: {player_hand} (Total: {player_score})\n'
f'Mão do Bot: {bot_hand} (Total: {bot_score})\n'
)
if outcome == 'bot_estourou':
response += f'O Bot estourou! Você ganha {game["bet"]} moedas.'
add_currency(user_id, game["bet"], data)
elif outcome == 'bot_ganha':
response += f'O Bot ganhou! Você perde {game["bet"]} moedas.'
# A aposta já foi deduzida no início
elif outcome == 'jogador_ganha':
response += f'Você ganhou! Você recebe {game["bet"]} moedas.'
add_currency(user_id, game["bet"], data)
else:
response += 'Empate! Nenhuma moeda perdida ou ganha.'
save_currency(data)
await ctx.send(response)
@stand.error
async def stand_error(ctx, error):
await ctx.send('Ocorreu um erro ao tentar segurar seu total.')
Comando Roleta (já com aposta variável)
@bot.command(name='roulette', help='Jogue Roleta! Aposte em um número (0-36) ou cor (vermelho/preto). Uso: !roulette <tipo_aposta> ')
async def roulette(ctx, bet_type: str, amount: int):
data = load_currency()
user_id = ctx.author.id
user_balance = get_balance(user_id, data)
if amount <= 0:
await ctx.send(f'{ctx.author.mention}, o valor da aposta deve ser maior que 0.')
return
if user_balance < amount:
await ctx.send(f'{ctx.author.mention}, você não tem moedas suficientes para fazer essa aposta.')
return
bet_type_lower = bet_type.lower()
valid_colors = ['vermelho', 'preto', 'verde']
number = None
color = None
# Definir a roda da roleta
roulette_numbers = {
0: 'verde',
1: 'vermelho', 2: 'preto', 3: 'vermelho', 4: 'preto', 5: 'vermelho', 6: 'preto',
7: 'vermelho', 8: 'preto', 9: 'vermelho', 10: 'preto', 11: 'preto', 12: 'vermelho',
13: 'preto', 14: 'vermelho', 15: 'preto', 16: 'vermelho', 17: 'preto',
18: 'vermelho', 19: 'vermelho', 20: 'preto', 21: 'vermelho', 22: 'preto',
23: 'vermelho', 24: 'preto', 25: 'vermelho', 26: 'preto', 27: 'vermelho',
28: 'preto', 29: 'preto', 30: 'vermelho', 31: 'preto', 32: 'vermelho',
33: 'preto', 34: 'vermelho', 35: 'preto', 36: 'vermelho'
}
# Determinar o tipo de aposta
if bet_type_lower in valid_colors:
bet_category = 'cor'
bet_choice = bet_type_lower
else:
try:
number = int(bet_type)
if 0 <= number <= 36:
bet_category = 'número'
bet_choice = number
else:
await ctx.send(f'{ctx.author.mention}, por favor, escolha um número entre 0 e 36 ou uma cor (vermelho/preto).')
return
except ValueError:
await ctx.send(f'{ctx.author.mention}, tipo de aposta inválido. Escolha um número entre 0 e 36 ou uma cor (vermelho/preto).')
return
# Girar a roleta
winning_number = random.randint(0, 36)
winning_color = roulette_numbers[winning_number]
# Determinar o resultado
if bet_category == 'número':
if bet_choice == winning_number:
payout = amount * 35
outcome = 'ganhou'
else:
payout = -amount
outcome = 'perdeu'
elif bet_category == 'cor':
if bet_choice == winning_color:
payout = amount
outcome = 'ganhou'
else:
payout = -amount
outcome = 'perdeu'
# Atualizar saldo do usuário
if payout > 0:
add_currency(user_id, payout, data)
result = f'🎉 Você ganhou! O número foi {winning_number} ({winning_color}). Você ganha {payout} moedas.'
else:
subtract_currency(user_id, amount, data)
result = f'⚠️ Você perdeu! O número foi {winning_number} ({winning_color}). Você perde {amount} moedas.'
save_currency(data)
await ctx.send(f'{ctx.author.mention}, {result}')
@roulette.error
async def roulette_error(ctx, error):
if isinstance(error, commands.BadArgument):
await ctx.send('Argumentos inválidos. Uso: !roulette <tipo_aposta> <quantia>. Exemplo: !roulette vermelho 50 ou !roulette 17 100')
else:
await ctx.send('Ocorreu um erro ao processar a aposta na roleta.')
-------------------- Comandos da Loja --------------------
@bot.command(name='shop', help='Veja os itens disponíveis na loja.')
async def shop(ctx):
shop = load_shop()
if not shop['items']:
await ctx.send('A loja ainda está vazia. Volte mais tarde!')
return
embed = discord.Embed(title="🏬 Loja do Servidor", color=discord.Color.blue())
for item in shop['items']:
embed.add_field(name=item['name'], value=f"Preço: {item['price']} moedas\nTipo: {item['type'].capitalize()}", inline=False)
await ctx.send(embed=embed)
@bot.command(name='buy', help='Compre um item da loja. Uso: !buy <nome_do_item>')
async def buy(ctx, *, item_name: str):
shop = load_shop()
purchases = load_purchases()
data = load_currency()
user_id = str(ctx.author.id)
# Find the item
item = next((item for item in shop['items'] if item['name'].lower() == item_name.lower()), None)
if not item:
await ctx.send(f'{ctx.author.mention}, o item "{item_name}" não foi encontrado na loja.')
return
# Check if the user has enough balance
user_balance = get_balance(user_id, data)
if user_balance < item['price']:
await ctx.send(f'{ctx.author.mention}, você não tem moedas suficientes para comprar "{item["name"]}".')
return
# Deduct the price
subtract_currency(user_id, item['price'], data)
save_currency(data)
# Record the purchase
if user_id not in purchases:
purchases[user_id] = []
purchases[user_id].append(item)
save_purchases(purchases)
# Deliver the reward
if item['type'] == 'role':
role = discord.utils.get(ctx.guild.roles, name=item['value'])
if role:
await ctx.author.add_roles(role)
await ctx.send(f'🎉 {ctx.author.mention}, você comprou "{item["name"]}" e recebeu o cargo "{role.name}".')
else:
await ctx.send(f'❗ Cargo "{item["value"]}" não encontrado. Por favor, contate um administrador.')
elif item['type'] == 'badge':
# Implement badge logic here
# This could be a custom field, a role, or a nickname change
# For simplicity, we'll send a confirmation message
await ctx.send(f'🎉 {ctx.author.mention}, você comprou "{item["name"]}". Parabéns pelo seu badge!')
elif item['type'] == 'emoji_access':
# Implement emoji access logic
# This typically requires managing channel permissions or creating private emoji roles
await ctx.send(f'🎉 {ctx.author.mention}, você comprou "{item["name"]}". Agora você tem acesso a emojis especiais!')
else:
await ctx.send(f'🎉 {ctx.author.mention}, você comprou "{item["name"]}".')
@buy.error
async def buy_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('Uso inválido. Por favor, use: !buy <nome_do_item>.')
elif isinstance(error, commands.BadArgument):
await ctx.send('Argumento inválido. Por favor, verifique o nome do item e tente novamente.')
else:
await ctx.send('Ocorreu um erro ao tentar comprar o item. Por favor, tente novamente mais tarde.')
logging.error(f"Erro no comando buy: {error}")
@bot.command(name='mypurchases', help='Veja seus itens comprados na loja.')
async def my_purchases(ctx):
purchases = load_purchases()
user_id = str(ctx.author.id)
if user_id not in purchases or not purchases[user_id]:
await ctx.send(f'{ctx.author.mention}, você ainda não comprou nenhum item da loja.')
return
embed = discord.Embed(title=f"🛒 Compras de {ctx.author.name}", color=discord.Color.green())
for idx, item in enumerate(purchases[user_id], start=1):
embed.add_field(name=f"Compra {idx}", value=f"**{item['name']}** - {item['type'].capitalize()}", inline=False)
await ctx.send(embed=embed)
Comando Admin para adicionar itens à loja
@bot.command(name='additem', help='Adicione um novo item à loja. Uso: !additem <preço> ')
@commands.has_permissions(administrator=True)
async def additem(ctx, name: str, price: int, type: str, value: str):
shop = load_shop()
if any(item['name'].lower() == name.lower() for item in shop['items']):
await ctx.send(f'Um item com o nome "{name}" já existe na loja.')
return
if type not in ['role', 'badge', 'emoji_access']:
await ctx.send('Tipo inválido. Tipos permitidos: role, badge, emoji_access.')
return
new_item = {
"name": name,
"price": price,
"type": type,
"value": value
}
shop['items'].append(new_item)
save_shop(shop)
await ctx.send(f'🆕 O item "{name}" foi adicionado à loja com o preço de {price} moedas.')
@additem.error
async def additem_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send('Você não tem permissão para usar este comando.')
elif isinstance(error, commands.BadArgument):
await ctx.send('Argumentos inválidos. Certifique-se de fornecer: <preço> .')
else:
await ctx.send('Ocorreu um erro ao tentar adicionar o item.')
logging.error(f"Erro no comando additem: {error}")
Comando Admin para remover itens da loja (Opcional)
@bot.command(name='removeitem', help='Remova um item da loja. Uso: !removeitem <nome_do_item>')
@commands.has_permissions(administrator=True)
async def removeitem(ctx, *, item_name: str):
shop = load_shop()
item = next((item for item in shop['items'] if item['name'].lower() == item_name.lower()), None)
if not item:
await ctx.send(f'Item "{item_name}" não encontrado na loja.')
return
shop['items'].remove(item)
save_shop(shop)
await ctx.send(f'🗑️ O item "{item_name}" foi removido da loja.')
@removeitem.error
async def removeitem_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send('Você não tem permissão para usar este comando.')
else:
await ctx.send('Ocorreu um erro ao tentar remover o item.')
logging.error(f"Erro no comando removeitem: {error}")
-------------------- Rodando o Bot --------------------
Rodar o bot com um token seguro (substitua 'SEU_TOKEN_AQUI' pelo seu token real, armazenado de maneira segura)
Certainly! Below is the revised Discord bot code with all shop-related items, admin commands, and shop functionalities removed. This streamlined version focuses solely on the economy and game features, such as balance, work, crime, blackjack, and roulette.
Changes Made:
Removed Variables and File Paths Related to the Shop:
SHOP_FILE
PURCHASE_FILE
Deleted Shop-Related Functions:
load_shop and save_shop
load_purchases and save_purchases
Eliminated Shop and Admin Commands:
shop, buy, mypurchases
additem, removeitem
Cleaned Up Any References to Shop Data:
Removed any references or usages of shop data within other parts of the code.
import discord
from discord.ext import commands
import json
import os
import random
from discord.ext.commands import BucketType
import logging
# Configurar logging
logging.basicConfig(level=logging.INFO)
# Definir as intents
intents = discord.Intents.default()
intents.members = True # Necessário para acessar informações dos membros
intents.message_content = True # Necessário para ler o conteúdo das mensagens para comandos de prefixo
# Inicializar o bot com as intents atualizadas
bot = commands.Bot(command_prefix='!', intents=intents)
# Definir o caminho para os arquivos JSON
CURRENCY_FILE = 'currency_data.json'
BLACKJACK_FILE = 'blackjack_data.json'
ROULETTE_FILE = 'roulette_data.json'
# -------------------- Funções de Carregamento e Salvamento --------------------
def load_data(file_path, default):
try:
if not os.path.isfile(file_path):
with open(file_path, 'w') as f:
json.dump(default, f, indent=4)
with open(file_path, 'r') as f:
return json.load(f)
except json.JSONDecodeError:
logging.error(f"Erro ao decodificar {file_path}. Reiniciando o arquivo.")
return default
except Exception as e:
logging.error(f"Erro ao carregar {file_path}: {e}")
return default
def save_data(file_path, data):
try:
with open(file_path, 'w') as f:
json.dump(data, f, indent=4)
except Exception as e:
logging.error(f"Erro ao salvar em {file_path}: {e}")
# Especificando funções para diferentes arquivos
def load_currency():
return load_data(CURRENCY_FILE, {})
def save_currency(data):
save_data(CURRENCY_FILE, data)
def load_blackjack():
return load_data(BLACKJACK_FILE, {})
def save_blackjack(data):
save_data(BLACKJACK_FILE, data)
def load_roulette():
return load_data(ROULETTE_FILE, {})
def save_roulette(data):
save_data(ROULETTE_FILE, data)
# -------------------- Funções de Moeda --------------------
def get_balance(user_id, data):
return data.get(str(user_id), 0)
def add_currency(user_id, amount, data):
data[str(user_id)] = data.get(str(user_id), 0) + amount
def subtract_currency(user_id, amount, data):
if data.get(str(user_id), 0) >= amount:
data[str(user_id)] -= amount
return True
return False
# -------------------- Eventos do Bot --------------------
@bot.event
async def on_ready():
logging.info(f'Logado como {bot.user.name} - {bot.user.id}')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
logging.info(f'Mensagem de {message.author}: {message.content}')
await bot.process_commands(message)
# -------------------- Comandos de Economia --------------------
@bot.command(name='balance', help='Verifique seu saldo')
async def balance(ctx):
data = load_currency()
user_id = ctx.author.id
bal = get_balance(user_id, data)
await ctx.send(f'{ctx.author.mention}, você tem {bal} moedas.')
@balance.error
async def balance_error(ctx, error):
if isinstance(error, commands.CommandError):
await ctx.send('Ocorreu um erro ao buscar seu saldo.')
@bot.command(name='work', help='Ganhe uma pequena quantidade de moedas. Tempo de espera: 1 hora')
@commands.cooldown(rate=1, per=3600, type=BucketType.user) # 1 hora de espera por usuário
async def work(ctx):
data = load_currency()
user_id = ctx.author.id
# Definir a quantidade ganha com trabalho
earned = random.randint(10, 50)
add_currency(user_id, earned, data)
save_currency(data)
await ctx.send(f'{ctx.author.mention}, você trabalhou e ganhou {earned} moedas!')
@work.error
async def work_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
remaining = int(error.retry_after)
hours, remainder = divmod(remaining, 3600)
minutes, seconds = divmod(remainder, 60)
await ctx.send(f'{ctx.author.mention}, você pode usar o comando `work` novamente em {hours}h {minutes}m {seconds}s.')
else:
await ctx.send('Ocorreu um erro ao processar o comando.')
@bot.command(name='crime', help='Tente cometer um crime para uma grande recompensa ou enfrente uma perda. Tempo de espera: 1 hora')
@commands.cooldown(rate=1, per=3600, type=BucketType.user) # 1 hora de espera por usuário
async def crime(ctx):
data = load_currency()
user_id = ctx.author.id
# Definir taxa de sucesso
success_chance = 0.3 # 30% de chance de sucesso
if random.random() < success_chance:
# Sucesso: Ganhar uma grande quantidade
earned = random.randint(100, 500)
add_currency(user_id, earned, data)
save_currency(data)
await ctx.send(f'🎉 {ctx.author.mention}, você cometeu um crime com sucesso e ganhou {earned} moedas!')
else:
# Falha: Perder uma quantidade significativa
lost = random.randint(50, 300)
if subtract_currency(user_id, lost, data):
save_currency(data)
await ctx.send(f'⚠️ {ctx.author.mention}, sua tentativa de crime falhou! Você perdeu {lost} moedas.')
else:
# Usuário não tem saldo suficiente para perder
await ctx.send(f'⚠️ {ctx.author.mention}, sua tentativa de crime falhou! Mas você não tem moedas suficientes para perder.')
@crime.error
async def crime_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
remaining = int(error.retry_after)
hours, remainder = divmod(remaining, 3600)
minutes, seconds = divmod(remainder, 60)
await ctx.send(f'{ctx.author.mention}, você pode usar o comando `crime` novamente em {hours}h {minutes}m {seconds}s.')
else:
await ctx.send('Ocorreu um erro ao processar o comando.')
# -------------------- Comandos de Jogos --------------------
# Comando Blackjack com aposta variável
@bot.command(name='blackjack', help='Jogue uma partida de Blackjack contra o bot. Uso: !blackjack <quantia>')
async def blackjack(ctx, amount: int):
data = load_currency()
user_id = ctx.author.id
user_balance = get_balance(user_id, data)
if amount <= 0:
await ctx.send(f'{ctx.author.mention}, o valor da aposta deve ser maior que 0.')
return
if user_balance < amount:
await ctx.send(f'{ctx.author.mention}, você não tem moedas suficientes para apostar {amount} moedas.')
return
# Deduzir a aposta imediatamente
subtract_currency(user_id, amount, data)
save_currency(data)
# Inicializar estado do jogo
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11] * 4 # Baralho simplificado
random.shuffle(deck)
player_hand = [deck.pop(), deck.pop()]
bot_hand = [deck.pop(), deck.pop()]
game_state = {
'player_hand': player_hand,
'bot_hand': bot_hand,
'deck': deck,
'bet': amount,
'status': 'playing'
}
# Salvar estado do jogo
blackjack_data = load_blackjack()
blackjack_data[str(user_id)] = game_state
save_blackjack(blackjack_data)
# Calcular pontuações iniciais
def calculate_score(hand):
score = sum(hand)
# Ajustar para ases
while score > 21 and 11 in hand:
hand.remove(11)
hand.append(1)
score = sum(hand)
return score
player_score = calculate_score(player_hand)
bot_score = calculate_score(bot_hand)
# Mostrar mãos iniciais
await ctx.send(
f'**Blackjack**\n'
f'Sua Mão: {player_hand} (Total: {player_score})\n'
f'Mão do Bot: [{bot_hand[0]}, ?]'
f'\n\nDigite `!hit` para pegar mais uma carta ou `!stand` para segurar seu total.'
)
@blackjack.error
async def blackjack_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('Uso inválido. Por favor, use: `!blackjack <quantia>`.')
elif isinstance(error, commands.BadArgument):
await ctx.send('A quantia deve ser um número inteiro válido.')
else:
await ctx.send('Ocorreu um erro ao iniciar uma partida de Blackjack.')
@bot.command(name='hit', help='Pegar outra carta no Blackjack.')
async def hit(ctx):
data = load_currency()
user_id = ctx.author.id
blackjack_data = load_blackjack()
if str(user_id) not in blackjack_data:
await ctx.send(f'{ctx.author.mention}, você não está atualmente em uma partida de Blackjack. Inicie uma com `!blackjack <quantia>`.')
return
game = blackjack_data[str(user_id)]
if game['status'] != 'playing':
await ctx.send(f'{ctx.author.mention}, a partida já terminou. Inicie uma nova com `!blackjack <quantia>`.')
return
deck = game['deck']
player_hand = game['player_hand']
if not deck:
await ctx.send('O baralho está sem cartas! Finalizando a partida.')
game['status'] = 'ended'
blackjack_data[str(user_id)] = game
save_blackjack(blackjack_data)
return
# Adicionar uma carta na mão do jogador
new_card = deck.pop()
player_hand.append(new_card)
player_score = sum(player_hand)
# Ajustar para ases
while player_score > 21 and 11 in player_hand:
player_hand.remove(11)
player_hand.append(1)
player_score = sum(player_hand)
# Atualizar estado do jogo
game['deck'] = deck
game['player_hand'] = player_hand
blackjack_data[str(user_id)] = game
save_blackjack(blackjack_data)
if player_score > 21:
# Jogador estoura
game['status'] = 'ended'
blackjack_data[str(user_id)] = game
save_blackjack(blackjack_data)
await ctx.send(
f'Você puxou um {new_card}. Seu total é {player_score}. Você estourou! Você perde {game["bet"]} moedas.'
)
else:
await ctx.send(
f'Você puxou um {new_card}. Seu total é {player_score}. Digite `!hit` para puxar novamente ou `!stand` para segurar.'
)
@hit.error
async def hit_error(ctx, error):
await ctx.send('Ocorreu um erro ao tentar puxar uma carta.')
@bot.command(name='stand', help='Segurar seu total no Blackjack.')
async def stand(ctx):
data = load_currency()
user_id = ctx.author.id
blackjack_data = load_blackjack()
if str(user_id) not in blackjack_data:
await ctx.send(f'{ctx.author.mention}, você não está atualmente em uma partida de Blackjack. Inicie uma com `!blackjack <quantia>`.')
return
game = blackjack_data[str(user_id)]
if game['status'] != 'playing':
await ctx.send(f'{ctx.author.mention}, a partida já terminou. Inicie uma nova com `!blackjack <quantia>`.')
return
deck = game['deck']
player_hand = game['player_hand']
bot_hand = game['bot_hand']
# Calcular pontuação do jogador
player_score = sum(player_hand)
while player_score > 21 and 11 in player_hand:
player_hand.remove(11)
player_hand.append(1)
player_score = sum(player_hand)
# Turno do bot
bot_score = sum(bot_hand)
while bot_score < 17:
if not deck:
await ctx.send('O baralho está sem cartas! Finalizando a partida.')
game['status'] = 'ended'
blackjack_data[str(user_id)] = game
save_blackjack(blackjack_data)
return
new_card = deck.pop()
bot_hand.append(new_card)
bot_score = sum(bot_hand)
while bot_score > 21 and 11 in bot_hand:
bot_hand.remove(11)
bot_hand.append(1)
bot_score = sum(bot_hand)
# Determinar o resultado
if bot_score > 21:
outcome = 'bot_estourou'
elif bot_score > player_score:
outcome = 'bot_ganha'
elif bot_score < player_score:
outcome = 'jogador_ganha'
else:
outcome = 'empate'
# Atualizar estado do jogo
game['deck'] = deck
game['player_hand'] = player_hand
game['bot_hand'] = bot_hand
game['status'] = 'ended'
blackjack_data[str(user_id)] = game
save_blackjack(blackjack_data)
# Preparar resposta
response = (
f'**Resultado do Blackjack**\n'
f'Sua Mão: {player_hand} (Total: {player_score})\n'
f'Mão do Bot: {bot_hand} (Total: {bot_score})\n'
)
if outcome == 'bot_estourou':
response += f'O Bot estourou! Você ganha {game["bet"]} moedas.'
add_currency(user_id, game["bet"], data)
elif outcome == 'bot_ganha':
response += f'O Bot ganhou! Você perde {game["bet"]} moedas.'
# A aposta já foi deduzida no início
elif outcome == 'jogador_ganha':
response += f'Você ganhou! Você recebe {game["bet"]} moedas.'
add_currency(user_id, game["bet"], data)
else:
response += 'Empate! Nenhuma moeda perdida ou ganha.'
save_currency(data)
await ctx.send(response)
@stand.error
async def stand_error(ctx, error):
await ctx.send('Ocorreu um erro ao tentar segurar seu total.')
# Comando Roleta (já com aposta variável)
@bot.command(name='roulette', help='Jogue Roleta! Aposte em um número (0-36) ou cor (vermelho/preto). Uso: !roulette <tipo_aposta> <quantia>')
async def roulette(ctx, bet_type: str, amount: int):
data = load_currency()
user_id = ctx.author.id
user_balance = get_balance(user_id, data)
if amount <= 0:
await ctx.send(f'{ctx.author.mention}, o valor da aposta deve ser maior que 0.')
return
if user_balance < amount:
await ctx.send(f'{ctx.author.mention}, você não tem moedas suficientes para fazer essa aposta.')
return
bet_type_lower = bet_type.lower()
valid_colors = ['vermelho', 'preto', 'verde']
number = None
color = None
# Definir a roda da roleta
roulette_numbers = {
0: 'verde',
1: 'vermelho', 2: 'preto', 3: 'vermelho', 4: 'preto', 5: 'vermelho', 6: 'preto',
7: 'vermelho', 8: 'preto', 9: 'vermelho', 10: 'preto', 11: 'preto', 12: 'vermelho',
13: 'preto', 14: 'vermelho', 15: 'preto', 16: 'vermelho', 17: 'preto',
18: 'vermelho', 19: 'vermelho', 20: 'preto', 21: 'vermelho', 22: 'preto',
23: 'vermelho', 24: 'preto', 25: 'vermelho', 26: 'preto', 27: 'vermelho',
28: 'preto', 29: 'preto', 30: 'vermelho', 31: 'preto', 32: 'vermelho',
33: 'preto', 34: 'vermelho', 35: 'preto', 36: 'vermelho'
}
# Determinar o tipo de aposta
if bet_type_lower in valid_colors:
bet_category = 'cor'
bet_choice = bet_type_lower
else:
try:
number = int(bet_type)
if 0 <= number <= 36:
bet_category = 'número'
bet_choice = number
else:
await ctx.send(f'{ctx.author.mention}, por favor, escolha um número entre 0 e 36 ou uma cor (vermelho/preto).')
return
except ValueError:
await ctx.send(f'{ctx.author.mention}, tipo de aposta inválido. Escolha um número entre 0 e 36 ou uma cor (vermelho/preto).')
return
# Girar a roleta
winning_number = random.randint(0, 36)
winning_color = roulette_numbers[winning_number]
# Determinar o resultado
if bet_category == 'número':
if bet_choice == winning_number:
payout = amount * 35
outcome = 'ganhou'
else:
payout = -amount
outcome = 'perdeu'
elif bet_category == 'cor':
if bet_choice == winning_color:
payout = amount
outcome = 'ganhou'
else:
payout = -amount
outcome = 'perdeu'
# Atualizar saldo do usuário
if payout > 0:
add_currency(user_id, payout, data)
result = f'🎉 Você ganhou! O número foi {winning_number} ({winning_color}). Você ganha {payout} moedas.'
else:
subtract_currency(user_id, amount, data)
result = f'⚠️ Você perdeu! O número foi {winning_number} ({winning_color}). Você perde {amount} moedas.'
save_currency(data)
await ctx.send(f'{ctx.author.mention}, {result}')
@roulette.error
async def roulette_error(ctx, error):
if isinstance(error, commands.BadArgument):
await ctx.send('Argumentos inválidos. Uso: `!roulette <tipo_aposta> <quantia>`. Exemplo: `!roulette vermelho 50` ou `!roulette 17 100`')
else:
await ctx.send('Ocorreu um erro ao processar a aposta na roleta.')
# -------------------- Rodando o Bot --------------------
# Rodar o bot com um token seguro (substitua 'SEU_TOKEN_AQUI' pelo seu token real, armazenado de maneira segura)
bot.run('SEU_TOKEN_AQUI')
Considerações Finais:
Token de Segurança: Certifique-se de substituir 'SEU_TOKEN_AQUI' pelo seu token real do Discord e não compartilhe este token publicamente. É altamente recomendável utilizar variáveis de ambiente ou arquivos de configuração seguros para armazenar tokens e outras credenciais sensíveis.
Gerenciamento de Arquivos: Com a remoção do sistema de loja, os arquivos shop_items.json e shop_purchases.json não são mais necessários. Você pode optar por removê-los do seu projeto para evitar confusões futuras.
Testes: Após realizar as modificações, teste todos os comandos para garantir que o bot está funcionando corretamente sem as funcionalidades removidas.
Se precisar de mais assistência ou de funcionalidades adicionais, sinta-se à vontade para perguntar!