Remove the admin commands, add predefined shop items, make them balanced with the insane amount of money players can easily get, but also add some meme ones (such as an anti-ban card, which makes the user automatically be unbanned, but it costs infinite money and doesn't even work) atleast 20 functional, useful items. (in-server)
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}')
@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)
code
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()
code
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()
code
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)
code
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
code
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)
code
# 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)
code
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
code
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
code
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)
Sure! I'll help you modify your Discord bot by removing the admin commands, adding a set of predefined shop items (including meme items), and ensuring they're balanced with the in-game economy.
Overview of Changes
Remove Admin Commands: The additem and removeitem commands will be removed to prevent users from adding or removing shop items dynamically.
Predefine Shop Items: We'll add a predefined list of 20 shop items directly into the shop_items.json file. These items will range from useful roles and badges to meme items like an "Anti-Ban Card."
Balance Shop Prices: Considering that players can earn money relatively easily through commands like work and crime, we'll set shop item prices appropriately to maintain balance.
Add Meme Items: Include items that serve no practical purpose or have humorous effects to add some fun to the shop.
Step 1: Remove Admin Commands
First, we'll remove the admin commands additem and removeitem from your bot code.
Modified Bot Code (Without Admin Commands)
python
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'
SHOP_FILE = 'shop_items.json'
PURCHASE_FILE = 'shop_purchases.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)
def load_shop():
return load_data(SHOP_FILE, {"items": []})
def save_shop(data):
save_data(SHOP_FILE, data)
def load_purchases():
return load_data(PURCHASE_FILE, {})
def save_purchases(data):
save_data(PURCHASE_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'
)
data = load_currency() # Reload currency data to reflect any changes
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.')
# -------------------- 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. Entre em contato com um administrador para adicionar itens!')
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)
# Encontrar o 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
# Verificar se o usuário tem saldo suficiente
user_balance = get_balance(ctx.author.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
# Deduzir o preço
subtract_currency(ctx.author.id, item['price'], data)
save_currency(data)
# Registrar a compra
if user_id not in purchases:
purchases[user_id] = []
purchases[user_id].append(item)
save_purchases(purchases)
# Entregar a recompensa
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':
# Implementar lógica de badge aqui
# Por simplicidade, enviaremos uma mensagem de confirmação
await ctx.send(f'🎉 {ctx.author.mention}, você comprou "{item["name"]}". Parabéns pelo seu badge!')
elif item['type'] == 'emoji_access':
# Implementar lógica de acesso a emojis
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)
# -------------------- 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')
Step 2: Predefine Shop Items
We'll create a shop_items.json file with 20 predefined items, ensuring a mix of functional and meme items. Here's an example of how the shop_items.json file should look:
Functional Items: These include roles, badges, and emoji access that provide tangible benefits within the server.
Meme Items: Such as the "Anti-Ban Card" and "Invisible Cloak," these items are priced exorbitantly or have no real effect, adding humor to the shop.
Step 3: Handle Meme Items in the Code
Since some items like the "Anti-Ban Card" have unique behaviors (e.g., not functioning despite their price), we'll need to handle them appropriately in the buy command.
Update the buy Command to Handle Meme Items
Modify the buy command to add special behavior for meme items. Here's how you can adjust the buy command:
python
Explanation:
Meme Items Handling: For items with type meme, we check the item name and send a humorous response indicating that the item doesn't have its intended effect.
Step 4: Initialize shop_items.json with Predefined Items
Ensure that the shop_items.json file exists and contains the predefined items. You can initialize it when the bot starts if it doesn't exist.
Initialize Shop Items in Code
Add the following function to initialize the shop with predefined items if shop_items.json is empty:
python
Explanation:
Initialization Function: The initialize_shop function checks if the shop is empty. If it is, it populates it with the predefined items.
Call Initialization on Startup: The on_ready event is updated to call initialize_shop when the bot starts.
Step 5: Ensure Proper Handling of Meme Items
Since meme items like the "Anti-Ban Card" are not standard item types, we added a new type called meme in the shop_items.json and handled it explicitly in the buy command to provide humorous responses.
Final Bot Code
Here's the complete modified bot code incorporating all the changes:
python
Step 6: Final Touches
Assign Roles on Server: Ensure that the roles specified in the shop items (e.g., "VIP", "Streamer") exist on your Discord server. If not, create them to prevent errors.
Handle Emoji Access: The emoji_access type in this example simply sends a confirmation message. To implement actual emoji access, you may need to set specific channel permissions or create special roles that grant access to certain emojis.
Secure Your Bot Token: Replace 'SEU_TOKEN_AQUI' with your actual bot token. Never share your bot token publicly. Consider using environment variables or a separate configuration file to store your token securely.
Error Handling and Logging: The bot includes basic error handling and logging. Monitor the logs to identify and fix any potential issues.
Conclusion
With these modifications:
Admin Commands Removed: Users can no longer dynamically add or remove shop items.
Predefined Shop Items: The shop is populated with 20 predefined items, balancing functional benefits with humorous, meme-based items.
Balanced Economy: Prices are set considering the rate at which players can earn money, maintaining a balanced in-game economy.
Feel free to adjust the prices, item types, and effects to better suit your server's dynamics and preferences!
Not yet included in a published release.
@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)
# Encontrar o 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
# Verificar se o usuário tem saldo suficiente
user_balance = get_balance(ctx.author.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
# Deduzir o preço
subtract_currency(ctx.author.id, item['price'], data)
save_currency(data)
# Registrar a compra
if user_id not in purchases:
purchases[user_id] = []
purchases[user_id].append(item)
save_purchases(purchases)
# Entregar a recompensa ou realizar ação especial para meme items
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':
# Implementar lógica de badge aqui
# Por simplicidade, enviaremos uma mensagem de confirmação
await ctx.send(f'🎉 {ctx.author.mention}, você comprou "{item["name"]}". Parabéns pelo seu badge!')
elif item['type'] == 'emoji_access':
# Implementar lógica de acesso a emojis
await ctx.send(f'🎉 {ctx.author.mention}, você comprou "{item["name"]}". Agora você tem acesso a emojis especiais!')
elif item['type'] == 'meme':
# Handle meme items
if item['name'].lower() == 'anti-ban card':
await ctx.send(f'😅 {ctx.author.mention}, você comprou o "{item["name"]}", mas infelizmente ele não funciona! Boa tentativa!')
elif item['name'].lower() == 'invisible cloak':
await ctx.send(f'🧥 {ctx.author.mention}, você está usando a "{item["name"]}"... Agora você ainda é visível! Haha!')
elif item['name'].lower() == 'flying bus ticket':
await ctx.send(f'🚌 {ctx.author.mention}, você comprou o "{item["name"]}" e tentou voar, mas tudo que você conseguiu foi uma dor nas costas!')
else:
await ctx.send(f'🎉 {ctx.author.mention}, você comprou "{item["name"]}". Divirta-se!')
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}")