To enhance your Discord bot by allowing players to place variable bets and introducing a shop system with in-server rewards, you can follow the steps below. This guide will help you modify existing commands to accept dynamic bet amounts and implement a comprehensive shop system where users can purchase rewards using their in-game currency.
1. Enabling Variable Bets
A. Updating the Blackjack Command
Currently, your blackjack command uses a fixed bet amount of 100 coins. To allow players to specify their bet amounts, you'll need to modify the command to accept an additional argument for the bet.
Here's how you can do it:
-
Modify the Command Signature:
Update the blackjack command to accept an amount parameter:
@bot.command(name='blackjack', help='Jogue uma partida de Blackjack contra o bot. Uso: !blackjack <quantia>')
async def blackjack(ctx, amount: int):
# Rest of the code...
-
Validate the Bet Amount:
Ensure the user specifies a valid bet amount and has sufficient balance:
@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)
# Rest of the game logic...
# Use `amount` instead of a fixed bet
-
Adjust the Game Logic:
Replace the fixed bet with the user-specified amount throughout the game logic:
# Define the bet as the amount specified by the user
bet = amount
-
Update Responses:
Ensure all responses reflect the dynamic bet amount:
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.'
)
-
Handle Win/Loss Logic:
Adjust the payout and loss calculations based on the dynamic bet:
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.'
# No need to subtract again since it's already deducted
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.'
B. Updating Other Betting Commands (Optional)
If you have other commands where the bet is fixed, consider updating them similarly. For example, the roulette command already accepts an amount parameter, so it's ready for variable bets.
2. Implementing a Shop System with In-Server Rewards
Introducing a shop system allows users to spend their in-game currency on various rewards such as roles, badges, or other perks. Here's how to add this feature:
A. Define the Shop Items
First, decide what items you want to offer in your shop. For this example, let's assume you have the following items:
- Premium Role - Grants the user a special role.
- Gamer Badge - Adds a badge to the user's profile.
- Special Emoji Access - Unlocks access to exclusive emojis.
Creating a Shop Configuration File
Create a JSON file named shop_items.json to store your shop items:
{
"items": [
{
"name": "Premium Role",
"price": 500,
"type": "role",
"value": "Premium"
},
{
"name": "Gamer Badge",
"price": 300,
"type": "badge",
"value": "Gamer"
},
{
"name": "Special Emoji Access",
"price": 200,
"type": "emoji_access",
"value": "SpecialEmojis"
}
]
}
- name: The display name of the item.
- price: Cost in coins.
- type: The type of reward (
role, badge, emoji_access, etc.).
- value: The specific value associated with the type (e.g., role name, badge name, emoji category).
B. Loading and Saving Shop Data
Add functions to load shop items from the JSON file:
SHOP_FILE = 'shop_items.json'
def load_shop():
try:
if not os.path.isfile(SHOP_FILE):
with open(SHOP_FILE, 'w') as f:
json.dump({"items": []}, f, indent=4)
with open(SHOP_FILE, 'r') as f:
return json.load(f)
except json.JSONDecodeError:
logging.error(f"Erro ao decodificar {SHOP_FILE}. Reiniciando o arquivo.")
return {"items": []}
except Exception as e:
logging.error(f"Erro ao carregar {SHOP_FILE}: {e}")
return {"items": []}
def save_shop(data):
try:
with open(SHOP_FILE, 'w') as f:
json.dump(data, f, indent=4)
except Exception as e:
logging.error(f"Erro ao salvar em {SHOP_FILE}: {e}")
C. Viewing the Shop
Create a command for users to view available shop items:
@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']}", inline=False)
await ctx.send(embed=embed)
D. Buying Items from the Shop
Implement a command that allows users to purchase items:
-
Create a Data Structure to Track Purchases
Create a JSON file named shop_purchases.json to keep track of user purchases:
{}
-
Loading and Saving Purchase Data
Add functions to handle purchase data:
PURCHASE_FILE = 'shop_purchases.json'
def load_purchases():
try:
if not os.path.isfile(PURCHASE_FILE):
with open(PURCHASE_FILE, 'w') as f:
json.dump({}, f, indent=4)
with open(PURCHASE_FILE, 'r') as f:
return json.load(f)
except json.JSONDecodeError:
logging.error(f"Erro ao decodificar {PURCHASE_FILE}. Reiniciando o arquivo.")
return {}
except Exception as e:
logging.error(f"Erro ao carregar {PURCHASE_FILE}: {e}")
return {}
def save_purchases(data):
try:
with open(PURCHASE_FILE, 'w') as f:
json.dump(data, f, indent=4)
except Exception as e:
logging.error(f"Erro ao salvar em {PURCHASE_FILE}: {e}")
-
Implement the Buy Command
@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"]}".')
E. Viewing Purchase History (Optional)
You can add a command for users to view their purchase history:
@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)
3. Ensuring Seamless Integration
A. Organizing the Code
For better code organization and maintainability, consider separating different functionalities into distinct files or using cogs. However, for simplicity, the following additions can be integrated directly into your existing bot.py.
B. Handling Permissions
Ensure that your bot has the necessary permissions to manage roles and assign them to users:
-
Bot Permissions:
- Go to the Discord Developer Portal.
- Select your application.
- Navigate to the "Bot" section.
- Under "Privileged Gateway Intents," enable the required intents (e.g., Server Members Intent).
- Ensure the bot has permissions like
Manage Roles in your Discord server.
-
Role Hierarchy:
- In your Discord server's role settings, ensure that the bot's role is above the roles it needs to assign. Discord's role hierarchy prevents bots from assigning roles that are equal or higher in position than their highest role.
C. Enhancing User Experience
-
Error Handling:
Improve error handling to provide users with clear feedback:
@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}")
-
Dynamic Shop Management (Advanced):
To allow server administrators to add or remove items from the shop without modifying the JSON file manually, consider implementing admin commands to manage the shop:
@bot.command(name='additem', help='Adicione um novo item à loja. Uso: !additem <nome> <preço> <tipo> <valor>')
@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.')
else:
await ctx.send('Ocorreu um erro ao tentar adicionar o item.')
logging.error(f"Erro no comando additem: {error}")
Similarly, you can create commands like removeitem to delete items from the shop.
D. Security Considerations
-
Protecting the Bot Token:
Ensure your bot token is kept secure. Never share your bot token publicly. If you've accidentally shared it, revoke it immediately in the Discord Developer Portal and regenerate a new one.
-
Validating User Inputs:
Always validate and sanitize user inputs to prevent misuse or unintended behavior.
4. Complete Updated Bot Code
Below is the complete updated bot code integrating both variable betting and the shop system. Note that comments have been added for clarity.
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'
)
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. 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 <nome> <preço> <tipo> <valor>')
@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: <nome> <preço> <tipo> <valor>.')
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)
bot.run('SEU_TOKEN_AQUI')
Notas Importantes:
-
Segurança do Token:
- Nunca compartilhe seu token do Discord publicamente. Se você o fez, revogue-o imediatamente no Discord Developer Portal.
- Considere usar variáveis de ambiente ou arquivos de configuração para armazenar seu token de forma segura, evitando incluí-lo diretamente no código.
-
Configuração Inicial da Loja:
- Certifique-se de que o arquivo
shop_items.json está presente no mesmo diretório que o seu bot ou ajuste o caminho conforme necessário.
- Inicialize o
shop_purchases.json com um objeto vazio {}.
-
Permissões do Bot:
- O bot precisa ter permissões adequadas para gerenciar cargos (
Manage Roles) se você estiver atribuindo roles como recompensas.
- Assegure-se de que o bot está posicionado acima dos cargos que ele tentará atribuir na hierarquia de cargos do Discord.
-
Expansão do Sistema de Recompensas:
- O exemplo acima inclui apenas um exemplo básico de como entregar recompensas baseado no tipo. Você pode expandir isso para incluir funcionalidades mais complexas, como gerenciamento de badges personalizados ou acesso a canais exclusivos.
-
Adicionando Itens à Loja:
-
Use o comando !additem para adicionar novos itens à loja. Por exemplo:
!additem "VIP Medal" 1000 badge VIP
-
Use o comando !removeitem para remover itens da loja.
!removeitem "VIP Medal"
-
Visualizando Compras:
- Os usuários podem ver suas compras com o comando
!mypurchases.
5. Testando as Novas Funcionalidades
Após implementar as mudanças, é essencial testar todas as funcionalidades para garantir que tudo está funcionando como esperado.
-
Reinicie o Bot:
Certifique-se de que o bot foi reiniciado para carregar as novas alterações.
-
Teste os Comandos de Aposta Variável:
- Inicie uma partida de Blackjack com uma aposta específica:
!blackjack 200
- Complete a partida usando
!hit e !stand.
-
Teste o Sistema da Loja:
- Verifique os itens disponíveis na loja:
!shop
- Compre um item:
!buy "Premium Role"
- Verifique suas compras:
!mypurchases
- Verifique se o rolamento do cargo foi atribuído corretamente no Discord.
-
Testar Comandos Admin:
-
Verificar Mensagens de Erro:
- Tente usar comandos com argumentos incorretos para garantir que as mensagens de erro estão sendo exibidas adequadamente.
6. Considerações Finais
Implementando essas alterações, seu Discord bot agora suporta apostas variáveis e um sistema de loja robusto, proporcionando uma experiência de jogo mais interativa e recompensadora para os usuários. Lembre-se de sempre testar as novas funcionalidades em um ambiente controlado antes de disponibilizá-las para todos os membros do servidor.
Se desejar expandir ainda mais as capacidades do seu bot, considere adicionar:
- Comandos de Administração mais abrangentes para gerenciar a loja.
- Sistema de Inventário para que os usuários possam gerenciar suas compras.
- Integração com Banco de Dados para melhor escalabilidade e segurança em vez de usar arquivos JSON para armazenar dados.
Boa sorte com o desenvolvimento do seu bot!