"import discord
from discord.ext import commands
import json
import os
import random
from discord.ext.commands import BucketType
import logging
Configure logging
logging.basicConfig(level=logging.INFO)
Define the intents
intents = discord.Intents.default()
intents.members = True # Needed to access member information
intents.message_content = True # Needed to read message content for prefix commands
def load_data():
if not os.path.isfile(DATA_FILE):
with open(DATA_FILE, 'w') as f:
json.dump({}, f)
with open(DATA_FILE, 'r') as f:
return json.load(f)
Save currency data to the JSON file
def save_data(data):
with open(DATA_FILE, 'w') as f:
json.dump(data, f, indent=4)
@bot.event
async def on_ready():
logging.info(f'Logged in as {bot.user.name} - {bot.user.id}')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
logging.info(f'Message from {message.author}: {message.content}')
await bot.process_commands(message)
@bot.command(name='balance', help='Check your balance')
async def balance(ctx):
data = load_data()
user_id = ctx.author.id
bal = get_balance(user_id, data)
await ctx.send(f'{ctx.author.mention}, you have {bal} coins.')
@balance.error
async def balance_error(ctx, error):
if isinstance(error, commands.CommandError):
await ctx.send('An error occurred while fetching your balance.')
@bot.command(name='work', help='Earn a small amount of coins. Cooldown: 1 hour')
@commands.cooldown(rate=1, per=3600, type=BucketType.user) # 1 hour cooldown per user
async def work(ctx):
data = load_data()
user_id = ctx.author.id
# Define the amount earned from work
earned = random.randint(10, 50)
add_currency(user_id, earned, data)
save_data(data)
await ctx.send(f'{ctx.author.mention}, you worked and earned {earned} coins!')
@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}, you can use the work command again in {hours}h {minutes}m {seconds}s.')
else:
await ctx.send('An error occurred while processing the command.')
Assistant
@bot.command(name='crime', help='Attempt to commit a crime for a large reward or face a loss. Cooldown: 1 hour')
@commands.cooldown(rate=1, per=3600, type=BucketType.user) # 1 hour cooldown per user
async def crime(ctx):
data = load_data()
user_id = ctx.author.id
# Define success rate
success_chance = 0.3 # 30% chance to succeed
if random.random() < success_chance:
# Success: Earn a large amount
earned = random.randint(100, 500)
add_currency(user_id, earned, data)
save_data(data)
await ctx.send(f'🎉 {ctx.author.mention}, you successfully committed a crime and earned {earned} coins!')
else:
# Failure: Lose a significant amount
lost = random.randint(50, 300)
if subtract_currency(user_id, lost, data):
save_data(data)
await ctx.send(f'⚠️ {ctx.author.mention}, your crime attempt failed! You lost {lost} coins.')
else:
# User does not have enough balance to lose
await ctx.send(f'⚠️ {ctx.author.mention}, your crime attempt failed! But you do not have enough coins to lose.')
@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}, you can use the crime command again in {hours}h {minutes}m {seconds}s.')
else:
await ctx.send('An error occurred while processing the command.')
Add blackjack (which is agaisn't a bot in turns) and roullete (which multiple players can play at once)
Sure! I'll help you extend your Discord bot by adding two new commands: blackjack and roulette.
Blackjack: This command allows a single user to play a simplified version of Blackjack against the bot. The game manages the player's and the bot's hands, calculates scores, and determines the outcome based on standard Blackjack rules.
Roulette: This command allows multiple users to participate simultaneously. Users can place bets on numbers, colors, or other roulette options, and the bot will handle the spinning and payout based on the outcome.
Below is the updated bot code with the new blackjack and roulette commands integrated:
python
import discord
from discord.ext import commands
import json
import os
import random
from discord.ext.commands import BucketType
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
# Define the intents
intents = discord.Intents.default()
intents.members = True # Needed to access member information
intents.message_content = True # Needed to read message content for prefix commands
# Initialize the bot with the updated intents
bot = commands.Bot(command_prefix='!', intents=intents)
# Define the path to the JSON files
CURRENCY_FILE = 'currency_data.json'
BLACKJACK_FILE = 'blackjack_data.json'
ROULETTE_FILE = 'roulette_data.json'
# Load currency data from the JSON file
def load_currency():
if not os.path.isfile(CURRENCY_FILE):
with open(CURRENCY_FILE, 'w') as f:
json.dump({}, f)
with open(CURRENCY_FILE, 'r') as f:
return json.load(f)
# Save currency data to the JSON file
def save_currency(data):
with open(CURRENCY_FILE, 'w') as f:
json.dump(data, f, indent=4)
# Load blackjack data
def load_blackjack():
if not os.path.isfile(BLACKJACK_FILE):
with open(BLACKJACK_FILE, 'w') as f:
json.dump({}, f)
with open(BLACKJACK_FILE, 'r') as f:
return json.load(f)
# Save blackjack data
def save_blackjack(data):
with open(BLACKJACK_FILE, 'w') as f:
json.dump(data, f, indent=4)
# Load roulette data
def load_roulette():
if not os.path.isfile(ROULETTE_FILE):
with open(ROULETTE_FILE, 'w') as f:
json.dump({}, f)
with open(ROULETTE_FILE, 'r') as f:
return json.load(f)
# Save roulette data
def save_roulette(data):
with open(ROULETTE_FILE, 'w') as f:
json.dump(data, f, indent=4)
# Get user's balance
def get_balance(user_id, data):
return data.get(str(user_id), 0)
# Add currency to a user
def add_currency(user_id, amount, data):
data[str(user_id)] = data.get(str(user_id), 0) + amount
# Subtract currency from a user
def subtract_currency(user_id, amount, data):
if data.get(str(user_id), 0) >= amount:
data[str(user_id)] -= amount
return True
return False
@bot.event
async def on_ready():
logging.info(f'Logged in as {bot.user.name} - {bot.user.id}')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
logging.info(f'Message from {message.author}: {message.content}')
await bot.process_commands(message)
@bot.command(name='balance', help='Check your balance')
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}, you have {bal} coins.')
@balance.error
async def balance_error(ctx, error):
if isinstance(error, commands.CommandError):
await ctx.send('An error occurred while fetching your balance.')
@bot.command(name='work', help='Earn a small amount of coins. Cooldown: 1 hour')
@commands.cooldown(rate=1, per=3600, type=BucketType.user) # 1 hour cooldown per user
async def work(ctx):
data = load_currency()
user_id = ctx.author.id
# Define the amount earned from work
earned = random.randint(10, 50)
add_currency(user_id, earned, data)
save_currency(data)
await ctx.send(f'{ctx.author.mention}, you worked and earned {earned} coins!')
@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}, you can use the `work` command again in {hours}h {minutes}m {seconds}s.')
else:
await ctx.send('An error occurred while processing the command.')
@bot.command(name='crime', help='Attempt to commit a crime for a large reward or face a loss. Cooldown: 1 hour')
@commands.cooldown(rate=1, per=3600, type=BucketType.user) # 1 hour cooldown per user
async def crime(ctx):
data = load_currency()
user_id = ctx.author.id
# Define success rate
success_chance = 0.3 # 30% chance to succeed
if random.random() < success_chance:
# Success: Earn a large amount
earned = random.randint(100, 500)
add_currency(user_id, earned, data)
save_currency(data)
await ctx.send(f'🎉 {ctx.author.mention}, you successfully committed a crime and earned {earned} coins!')
else:
# Failure: Lose a significant amount
lost = random.randint(50, 300)
if subtract_currency(user_id, lost, data):
save_currency(data)
await ctx.send(f'⚠️ {ctx.author.mention}, your crime attempt failed! You lost {lost} coins.')
else:
# User does not have enough balance to lose
await ctx.send(f'⚠️ {ctx.author.mention}, your crime attempt failed! But you do not have enough coins to lose.')
@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}, you can use the `crime` command again in {hours}h {minutes}m {seconds}s.')
else:
await ctx.send('An error occurred while processing the command.')
# -------------------- Blackjack Command --------------------
@bot.command(name='blackjack', help='Play a game of Blackjack against the bot.')
async def blackjack(ctx):
data = load_currency()
user_id = ctx.author.id
user_balance = get_balance(user_id, data)
if user_id in load_blackjack():
await ctx.send(f'{ctx.author.mention}, you are already in a game of Blackjack.')
return
# Set bet amount
bet = 100 # Fixed bet for simplicity; you can modify to accept user input
if user_balance < bet:
await ctx.send(f'{ctx.author.mention}, you do not have enough coins to play Blackjack. You need at least {bet} coins.')
return
# Initialize game state
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11] * 4 # Simplified deck
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': bet,
'status': 'playing'
}
# Save game state
blackjack_data = load_blackjack()
blackjack_data[str(user_id)] = game_state
save_blackjack(blackjack_data)
# Calculate initial scores
def calculate_score(hand):
score = sum(hand)
# Adjust for aces
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)
# Show initial hands
await ctx.send(
f'**Blackjack**\n'
f'Your Hand: {player_hand} (Total: {player_score})\n'
f'Bot\'s Hand: [{bot_hand[0]}, ?]'
f'\n\nType `!hit` to get another card or `!stand` to hold your total.'
)
@blackjack.error
async def blackjack_error(ctx, error):
await ctx.send('An error occurred while starting a game of Blackjack.')
@bot.command(name='hit', help='Hit to get another card in 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}, you are not currently in a game of Blackjack. Start one with `!blackjack`.')
return
game = blackjack_data[str(user_id)]
if game['status'] != 'playing':
await ctx.send(f'{ctx.author.mention}, the game is already over. Start a new one with `!blackjack`.')
return
deck = game['deck']
player_hand = game['player_hand']
if not deck:
await ctx.send('The deck is out of cards! Ending the game.')
game['status'] = 'ended'
blackjack_data[str(user_id)] = game
save_blackjack(blackjack_data)
return
# Add a card to player's hand
new_card = deck.pop()
player_hand.append(new_card)
player_score = sum(player_hand)
# Adjust for aces
while player_score > 21 and 11 in player_hand:
player_hand.remove(11)
player_hand.append(1)
player_score = sum(player_hand)
# Update game state
game['deck'] = deck
game['player_hand'] = player_hand
blackjack_data[str(user_id)] = game
save_blackjack(blackjack_data)
if player_score > 21:
# Player busts
game['status'] = 'ended'
blackjack_data[str(user_id)] = game
save_blackjack(blackjack_data)
await ctx.send(
f'You drew a {new_card}. Your total is {player_score}. You busted! You lose {game["bet"]} coins.'
)
# Deduct bet
if subtract_currency(user_id, game['bet'], data):
save_currency(data)
else:
await ctx.send(
f'You drew a {new_card}. Your total is {player_score}. Type `!hit` to draw again or `!stand` to hold.'
)
@hit.error
async def hit_error(ctx, error):
await ctx.send('An error occurred while trying to hit.')
@bot.command(name='stand', help='Stand to hold your total in 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}, you are not currently in a game of Blackjack. Start one with `!blackjack`.')
return
game = blackjack_data[str(user_id)]
if game['status'] != 'playing':
await ctx.send(f'{ctx.author.mention}, the game is already over. Start a new one with `!blackjack`.')
return
deck = game['deck']
player_hand = game['player_hand']
bot_hand = game['bot_hand']
player_score = sum(player_hand)
# Adjust for aces
while player_score > 21 and 11 in player_hand:
player_hand.remove(11)
player_hand.append(1)
player_score = sum(player_hand)
# Bot's turn
bot_score = sum(bot_hand)
while bot_score < 17:
if not deck:
await ctx.send('The deck is out of cards! Ending the game.')
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)
# Adjust for aces
while bot_score > 21 and 11 in bot_hand:
bot_hand.remove(11)
bot_hand.append(1)
bot_score = sum(bot_hand)
# Determine outcome
if bot_score > 21:
outcome = 'bot_bust'
elif bot_score > player_score:
outcome = 'bot_wins'
elif bot_score < player_score:
outcome = 'player_wins'
else:
outcome = 'tie'
# Update game state
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)
# Prepare response
response = (
f'**Blackjack Result**\n'
f'Your Hand: {player_hand} (Total: {player_score})\n'
f'Bot\'s Hand: {bot_hand} (Total: {bot_score})\n'
)
if outcome == 'bot_bust':
response += f'Bot busted! You win {game["bet"]} coins.'
add_currency(user_id, game['bet'], data)
elif outcome == 'bot_wins':
response += f'Bot wins! You lose {game["bet"]} coins.'
if subtract_currency(user_id, game['bet'], data):
pass
elif outcome == 'player_wins':
response += f'You win! You earn {game["bet"]} coins.'
add_currency(user_id, game['bet'], data)
else:
response += 'It\'s a tie! No coins lost or gained.'
save_currency(data)
await ctx.send(response)
@stand.error
async def stand_error(ctx, error):
await ctx.send('An error occurred while trying to stand.')
# -------------------- Roulette Command --------------------
@bot.command(name='roulette', help='Play Roulette! Place a bet on a number (0-36) or color (red/black). Usage: !roulette <bet_type> <amount>')
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}, bet amount must be greater than 0.')
return
if user_balance < amount:
await ctx.send(f'{ctx.author.mention}, you do not have enough coins to place that bet.')
return
bet_type_lower = bet_type.lower()
valid_colors = ['red', 'black', 'green']
number = None
color = None
# Define roulette wheel
roulette_numbers = {
0: 'green',
1: 'red', 2: 'black', 3: 'red', 4: 'black', 5: 'red', 6: 'black',
7: 'red', 8: 'black', 9: 'red', 10: 'black', 11: 'black', 12: 'red',
13: 'black', 14: 'red', 15: 'black', 16: 'red', 17: 'black',
18: 'red', 19: 'red', 20: 'black', 21: 'red', 22: 'black',
23: 'red', 24: 'black', 25: 'red', 26: 'black', 27: 'red',
28: 'black', 29: 'black', 30: 'red', 31: 'black', 32: 'red',
33: 'black', 34: 'red', 35: 'black', 36: 'red'
}
# Determine bet type
if bet_type_lower in valid_colors:
bet_category = 'color'
bet_choice = bet_type_lower
else:
try:
number = int(bet_type)
if 0 <= number <= 36:
bet_category = 'number'
bet_choice = number
else:
await ctx.send(f'{ctx.author.mention}, please choose a number between 0 and 36 or a color (red/black).')
return
except ValueError:
await ctx.send(f'{ctx.author.mention}, invalid bet type. Choose a number between 0 and 36 or a color (red/black).')
return
# Spin the roulette
winning_number = random.randint(0, 36)
winning_color = roulette_numbers[winning_number]
# Determine outcome
if bet_category == 'number':
if bet_choice == winning_number:
payout = amount * 35
outcome = 'win'
else:
payout = -amount
outcome = 'lose'
elif bet_category == 'color':
if bet_choice == winning_color:
payout = amount
outcome = 'win'
else:
payout = -amount
outcome = 'lose'
# Update user balance
if payout > 0:
add_currency(user_id, payout, data)
result = f'🎉 You won! The number was {winning_number} ({winning_color}). You gain {payout} coins.'
else:
subtract_currency(user_id, amount, data)
result = f'⚠️ You lost! The number was {winning_number} ({winning_color}). You lose {amount} coins.'
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('Invalid arguments. Usage: `!roulette <bet_type> <amount>`. Example: `!roulette red 50` or `!roulette 17 100`')
else:
await ctx.send('An error occurred while processing the roulette bet.')
# Run the bot
bot.run('YOUR_BOT_TOKEN_HERE') # Replace with your actual bot token
Explanation of the Added Features
1. Blackjack Command
Commands:
!blackjack: Starts a new game of Blackjack. The user places a fixed bet (e.g., 100 coins). The bot deals two cards each to the player and itself.
!hit: The player requests another card. If the player's hand exceeds 21, they bust and lose the bet.
!stand: The player stands, and the bot completes its hand. The outcome is determined based on standard Blackjack rules.
Data Management:
Game state is stored in a separate JSON file (blackjack_data.json) to track ongoing games for each user.
The player's and bot's hands, the remaining deck, and the bet amount are managed within this state.
2. Roulette Command
Command:
!roulette <bet_type> <amount>: Allows users to place a bet on a specific number (0-36) or a color (red or black) with the desired amount.
Bet Types:
Number Bet: Betting on a specific number pays out 35:1 if the bet is successful.
Color Bet: Betting on a color (red or black) pays out 1:1 if the bet is successful.
Outcome Determination:
The bot randomly selects a winning number and determines its color based on a predefined roulette wheel layout.
The bot then calculates the payout based on the bet type and updates the user's balance accordingly.
3. Data Persistence
Currency Data: Managed in currency_data.json.
Blackjack Data: Managed in blackjack_data.json to handle ongoing games and ensure that each user's game state is maintained.
Roulette: Since roulette bets are instantaneous and do not require persistent state across multiple interactions, they do not have a separate data file.
4. Error Handling
Comprehensive error handling has been added for all new commands to ensure that users receive informative messages in case of invalid inputs or actions.
5. Security Notice
Important: Never share your actual bot token publicly. In the provided code, replace 'YOUR_BOT_TOKEN_HERE' with your actual bot token. Ensure that the token is kept secure to prevent unauthorized access to your bot.
python
bot.run('YOUR_BOT_TOKEN_HERE') # Replace with your actual bot token
Additional Enhancements
Dynamic Betting: For a more interactive experience, you can modify the blackjack and roulette commands to accept dynamic bet amounts from users instead of fixed values.
Leaderboard: Implement a leaderboard to showcase top earners in the server.
Enhanced Games: Add more complexity to the games, such as multiple betting options in Roulette or more sophisticated Blackjack rules.
Feel free to customize and enhance these features further to better fit your server's needs!