The great nerds work

discord bot
 avatar
unknown
python
2 years ago
25 kB
3
Indexable
import discord
from discord.ext import commands
import json
import random
import asyncio

# Define intents
intents = discord.Intents.default()
intents.message_content = True

# Initialize the bot
bot = commands.Bot(command_prefix='!', intents=intents)

# Define the file path for user data
user_data_file = 'C:/Users/krs2l/Desktop/EconomyBotData.json'

# Load user data from the JSON file
def load_user_data():
    try:
        with open(user_data_file, 'r') as file:
            data = json.load(file)
            return data
    except (FileNotFoundError, json.JSONDecodeError):
        return {}

# Save user data to the JSON file
def save_user_data(data):
    with open(user_data_file, 'w') as file:
        json.dump(data, file, indent=4)

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name} ({bot.user.id})')

# Load user data when the bot starts
user_data = load_user_data()

# Define the cooldown duration in seconds (30 minutes)
WORK_COOLDOWN_SECONDS = 1800

TRANSACTION_COOLDOWN_SECONDS = 3  # Cooldown for transaction commands
# Define the house edge (1% less reward)
HOUSE_EDGE = 0.01

# Define a command to register a user
@bot.command(
    name='register',
    description='Register as a user to start using the bot.',
    brief='Register as a user.'
)
async def register(ctx):
    user_id = str(ctx.author.id)
    if user_id not in user_data:
        # Create a new user entry in the user_data dictionary
        user_data[user_id] = {'purse': 0, 'bank': 500, 'items': []}
        save_user_data(user_data)
        await ctx.send("You have been registered as a user!")
    else:
        await ctx.send("You are already registered.")

# Define a command to allow users to work and earn money
@bot.command(
    name='work',
    description='Work to earn money (with a 30-minute cooldown).',
    brief='Earn money.'
)
@commands.cooldown(1, WORK_COOLDOWN_SECONDS, commands.BucketType.user)
async def work(ctx):
    user_id = str(ctx.author.id)
    if user_id in user_data:
        earnings = random.randint(100, 500)
        user_data[user_id]['purse'] += earnings
        save_user_data(user_data)
        await ctx.send(f"You have worked hard and earned ${earnings}!")
    else:
        await ctx.send("You are not registered. Use !register to create your save data.")

# Handle the cooldown error
@work.error
async def work_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.send(f"This command is on cooldown. Please wait {error.retry_after:.2f} seconds.")

# Define a command to display the leaderboard with the total amount of money
@bot.command(
    name='leaderboard',
    aliases=['lb'],
    description='Display the top 10 users with the highest total balance (purse + bank).',
    brief='Show the top balances.'
)
async def leaderboard(ctx):
    sorted_data = sorted(user_data.items(), key=lambda x: x[1]['purse'] + x[1]['bank'], reverse=True)
    leaderboard_message = "Top 10 Balances (Purse + Bank):\n"
    count = 0
    for user_id, data in sorted_data:
        user = await bot.fetch_user(int(user_id))
        total_balance = data['purse'] + data['bank']
        leaderboard_message += f"{user.display_name}: ${total_balance}\n"
        count += 1
        if count >= 10:
            break
    await ctx.send(f"```{leaderboard_message}```")

# Define a command to give a user 100 money

# Define a command to deposit money into the bank
@bot.command(
    name='deposit',
    aliases=['dep'],
    description='Deposit money into your bank. You can use "all" or "half" as the amount.',
    brief='Deposit money.'
)
async def deposit(ctx, amount: str):
    user_id = str(ctx.author.id)
    if user_id in user_data:
        data = user_data[user_id]
        purse_balance = data['purse']

        if amount.lower() == 'all':
            deposit_amount = purse_balance
        elif amount.lower() == 'half':
            deposit_amount = purse_balance // 2
        else:
            try:
                deposit_amount = int(amount)
            except ValueError:
                await ctx.send("Invalid amount. Please specify a valid amount, 'all', or 'half'.")
                return

        if deposit_amount > 0 and purse_balance >= deposit_amount:
            data['purse'] -= deposit_amount
            data['bank'] += deposit_amount
            save_user_data(user_data)
            await ctx.send(f"You have deposited ${deposit_amount} into your bank.")
        else:
            await ctx.send("Invalid amount or insufficient funds.")
    else:
        await ctx.send("You are not registered. Use !register to create your save data.")

# Define a command to withdraw money from the bank
@bot.command(
    name='withdraw',
    aliases=['with'],
    description='Withdraw money from your bank. You can use "all" or "half" as the amount.',
    brief='Withdraw money.'
)
async def withdraw(ctx, amount: str):
    user_id = str(ctx.author.id)
    if user_id in user_data:
        data = user_data[user_id]
        bank_balance = data['bank']

        if amount.lower() == 'all':
            withdraw_amount = bank_balance
        elif amount.lower() == 'half':
            withdraw_amount = bank_balance // 2
        else:
            try:
                withdraw_amount = int(amount)
            except ValueError:
                await ctx.send("Invalid amount. Please specify a valid amount, 'all', or 'half'.")
                return

        if withdraw_amount > 0 and bank_balance >= withdraw_amount:
            data['purse'] += withdraw_amount
            data['bank'] -= withdraw_amount
            save_user_data(user_data)
            await ctx.send(f"You have withdrawn ${withdraw_amount} from your bank.")
        else:
            await ctx.send("Invalid amount or insufficient funds.")
    else:
        await ctx.send("You are not registered. Use !register to create your save data.")

# Define a command to deposit all money into the bank
@bot.command(
    name='depositall',
    aliases=['depall'],
    description='Deposit all your purse money into your bank.',
    brief='Deposit all money.'
)
async def deposit_all(ctx):
    user_id = str(ctx.author.id)
    if user_id in user_data:
        data = user_data[user_id]
        purse_balance = data['purse']
        if purse_balance > 0:
            data['bank'] += purse_balance
            data['purse'] = 0
            save_user_data(user_data)
            await ctx.send(f"You have deposited all your purse money into your bank.")
        else:
            await ctx.send("You don't have any money in your purse to deposit.")
    else:
        await ctx.send("You are not registered. Use !register to create your save data.")

# Define a command to withdraw all money from the bank
@bot.command(
    name='withdrawall',
    aliases=['withall'],
    description='Withdraw all your bank money into your purse.',
    brief='Withdraw all money.'
)
async def withdraw_all(ctx):
    user_id = str(ctx.author.id)
    if user_id in user_data:
        data = user_data[user_id]
        bank_balance = data['bank']
        if bank_balance > 0:
            data['purse'] += bank_balance
            data['bank'] = 0
            save_user_data(user_data)
            await ctx.send(f"You have withdrawn all your bank money into your purse.")
        else:
            await ctx.send("You don't have any money in your bank to withdraw.")
    else:
        await ctx.send("You are not registered. Use !register to create your save data.")

# Rename the tipall command to rainall
@bot.command(
    name='rainall',
    description='Tip all users with a specified amount. You can use "all" or "half" as the amount.',
    brief='Tip all users.'
)
async def rainall(ctx, amount: str):
    user_id = str(ctx.author.id)
    if user_id in user_data:
        user_data_user = user_data[user_id]
        purse_balance = user_data_user['purse']

        if amount.lower() == 'all':
            tip_amount = purse_balance
        elif amount.lower() == 'half':
            tip_amount = purse_balance // 2
        else:
            try:
                tip_amount = int(amount)
            except ValueError:
                await ctx.send("Invalid amount. Please specify a valid amount, 'all', or 'half'.")
                return

        if tip_amount > 0 and purse_balance >= tip_amount:
            for target_id, target_data in user_data.items():
                if target_id != user_id:  # Don't tip yourself
                    target_data['purse'] += tip_amount
            user_data_user['purse'] -= (tip_amount * (len(user_data) - 1))  # Subtract the total tip amount from the tipper
            save_user_data(user_data)
            await ctx.send(f"```You tipped all users ${tip_amount} each!```")
        else:
            await ctx.send("```Invalid amount or insufficient funds in your purse.```")
    else:
        await ctx.send("```You are not registered. Use !register to create your save data.```")

# Modify the tip command to handle various scenarios and add a confirmation prompt
@bot.command(
    name='tip',
    description='Tip another user with a specified amount. You can use "all" or "half" as the amount.',
    brief='Tip another user.'
)
async def tip(ctx, target_user: discord.User, amount: str):
    user_id = str(ctx.author.id)
    target_id = str(target_user.id)

    if user_id in user_data and target_id in user_data:
        user_data_user = user_data[user_id]
        target_user_data = user_data[target_id]
        purse_balance = user_data_user['purse']

        if amount.lower() == 'all':
            tip_amount = purse_balance
        elif amount.lower() == 'half':
            tip_amount = purse_balance // 2
        else:
            try:
                tip_amount = int(amount)
            except ValueError:
                await ctx.send("Invalid amount. Please specify a valid amount, 'all', or 'half'.")
                return

        if tip_amount > 0 and purse_balance >= tip_amount:
            # Calculate the percentage being tipped
            percentage_tipped = (tip_amount / purse_balance) * 100

            if percentage_tipped > 30:
                # Prompt for confirmation
                await ctx.send(f"You are about to tip {target_user.mention} {percentage_tipped:.2f}% of your balance. Are you sure? (Yes/No)")

                def check(msg):
                    return msg.author == ctx.author and msg.channel == ctx.channel and msg.content.lower() in ['yes', 'no']

                try:
                    response = await bot.wait_for('message', check=check, timeout=30)
                except TimeoutError:
                    await ctx.send("You didn't respond within 30 seconds. Tip canceled.")
                    return

                if response.content.lower() == 'yes':
                    user_data_user['purse'] -= tip_amount
                    target_user_data['purse'] += tip_amount
                    save_user_data(user_data)
                    await ctx.send(f"```You tipped {target_user.mention} ${tip_amount}!```")
                else:
                    await ctx.send("Tip canceled.")
            else:
                user_data_user['purse'] -= tip_amount
                target_user_data['purse'] += tip_amount
                save_user_data(user_data)
                await ctx.send(f"```You tipped {target_user.mention} ${tip_amount}!```")
        else:
            await ctx.send("```Invalid amount or insufficient funds in your purse.```")
    else:
        await ctx.send("```One of the users is not registered. Use !register to create their save data.```")

# Define the command to check a user's balance
@bot.command(
    name='balance',
    aliases=['bal'],
    description='Check your current balance.',
    brief='Check your balance.'
)
async def balance(ctx):
    user_id = str(ctx.author.id)
    if user_id in user_data:
        purse_balance = user_data[user_id]['purse']
        bank_balance = user_data[user_id]['bank']
        total_balance = purse_balance + bank_balance
        await ctx.send(f"@{ctx.author.name}'s current balance:\n"
                       f"Purse: ${purse_balance}\n"
                       f"Bank: ${bank_balance}\n"
                       f"Total: ${total_balance}")
    else:
        await ctx.send("You are not registered. Use !register to create your save data.")

# Define a command to roll a dice and potentially win or lose money (No house edge just luck)
@bot.command(
    name='dice',
    description='Roll a dice and potentially win or lose money based on a win chance and bet amount.',
    brief='Roll a dice.'
)
async def dice(ctx, bet_amount: str, win_chance: int):
    user_id = str(ctx.author.id)
    if user_id in user_data:
        data = user_data[user_id]
        purse_balance = data['purse']

        # Check if win chance is within valid limits
        if win_chance < 1 or win_chance > 99:
            await ctx.send("Invalid win chance.")
            return

        # Handle the 'half' case
        if bet_amount.lower() == 'half':
            bet_amount = purse_balance // 2
        elif bet_amount.lower() == 'all':
            bet_amount = purse_balance
        else:
            try:
                bet_amount = int(bet_amount)
            except ValueError:
                await ctx.send("Invalid bet amount. Please specify a valid amount, 'half', or 'all'.")
                return

        # Check if the calculated bet amount is within valid limits
        if bet_amount <= 0 or purse_balance < bet_amount:
            await ctx.send("Invalid bet amount or insufficient funds.")
            return

        # Deduct the bet amount from the user's purse
        data['purse'] -= bet_amount
        save_user_data(user_data)

        # Generate a random number between 1 and 100 to simulate the dice roll
        roll = random.randint(1, 100)

        if roll <= win_chance:  # You win
            multiplier = 100 / win_chance
            winnings = int(bet_amount * multiplier)
            data['purse'] += winnings  # Award only the calculated winnings
            save_user_data(user_data)
            await ctx.send(f"You rolled a {roll} and won ${winnings}!")
        else:  # You lose
            await ctx.send(f"You rolled a {roll} and lost ${bet_amount}. Better luck next time.")
    else:
        await ctx.send("You are not registered. Use !register to create your save data.")


# Define a command to send a message to the bot owner
@bot.command(
    name='contact',
    description='Send a message to the bot owner.',
    brief='Contact the bot owner.'
)
async def contact_owner(ctx, *, message: str):
    owner_id = '1137025087317491852'  # Replace with the actual user ID of the bot owner
    owner = await bot.fetch_user(owner_id)
    await owner.send(f"Message from {ctx.author} (ID: {ctx.author.id}):\n{message}")
    await ctx.send("Your message has been sent to the bot owner.")

# Define a dictionary to store Blackjack game states for users
blackjack_games = {}

@bot.command(
    name='blackjack',
    description='Play a game of Blackjack.',
    brief='Play Blackjack.'
)
async def blackjack(ctx, bet_amount: str):
    user_id = str(ctx.author.id)
    if user_id in user_data:
        user_data_user = user_data[user_id]
        purse_balance = user_data_user['purse']

        if bet_amount.lower() == 'all':
            bet_amount = purse_balance
        else:
            try:
                bet_amount = int(bet_amount)
            except ValueError:
                await ctx.send("Invalid bet amount. Please specify a valid amount or 'all'.")
                return

        if bet_amount <= 0 or bet_amount > purse_balance:
            await ctx.send("Invalid bet amount or insufficient funds in your purse.")
            return

        # Check if a game is already in progress for this user
        if user_id in blackjack_games:
            await ctx.send("You already have a game in progress. Finish that game before starting a new one.")
            return

        # Initialize the deck of cards (simplified)
        suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
        values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
        deck = [{'suit': suit, 'value': value} for suit in suits for value in values]

        # Shuffle the deck
        random.shuffle(deck)

        # Deal two cards to the player and two cards to the dealer
        player_hand = [deck.pop(), deck.pop()]
        dealer_hand = [deck.pop(), deck.pop()]

        # Implement game logic for Hit, Stand, Split, and Double Down (simplified)
        def calculate_hand_value(hand):
            # Calculate the value of a hand (simplified)
            total_value = 0
            num_aces = 0

            for card in hand:
                value = card['value']
                if value.isnumeric():
                    total_value += int(value)
                elif value in ['K', 'Q', 'J']:
                    total_value += 10
                elif value == 'A':
                    total_value += 11
                    num_aces += 1

            # Adjust for aces
            while num_aces > 0 and total_value > 21:
                total_value -= 10
                num_aces -= 1

            return total_value

        def check_blackjack(hand):
            return len(hand) == 2 and calculate_hand_value(hand) == 21

        player_value = calculate_hand_value(player_hand)
        dealer_value = calculate_hand_value(dealer_hand)

        game_over = False
        player_stand = False
        can_split = len(player_hand) == 2 and player_hand[0]['value'] == player_hand[1]['value']
        can_double_down = len(player_hand) == 2 and bet_amount * 2 <= purse_balance  # Check if user can double down

        # Store game state for this user
        blackjack_games[user_id] = {
            'user_data': user_data_user,
            'bet_amount': bet_amount,
            'deck': deck,
            'player_hand': player_hand,
            'dealer_hand': dealer_hand,
            'player_value': player_value,
            'dealer_value': dealer_value,
            'game_over': game_over,
            'player_stand': player_stand,
            'can_split': can_split,
            'can_double_down': can_double_down
        }

        while not game_over:
            # Create a formatted message with game status
            game_status = (
                f"Your hand: {', '.join([card['value'] + ' of ' + card['suit'] for card in player_hand])} ({player_value})\n"
                f"Dealer's hand: {dealer_hand[0]['value']} of {dealer_hand[0]['suit']}, ?"
            )

            if check_blackjack(player_hand):
                game_status += "\nBlackjack! You win!"
                user_data_user['purse'] += bet_amount
                game_over = True
            elif player_value > 21:
                game_status += "\nBust! You lose!"
                user_data_user['purse'] -= bet_amount
                game_over = True
            elif player_stand:
                while dealer_value < 17:
                    dealer_hand.append(deck.pop())
                    dealer_value = calculate_hand_value(dealer_hand)

                game_status += (
                    f"\nDealer's hand: {', '.join([card['value'] + ' of ' + card['suit'] for card in dealer_hand])} ({dealer_value})"
                )

                if dealer_value > 21:
                    game_status += "\nDealer busts! You win!"
                    user_data_user['purse'] += bet_amount
                elif dealer_value > player_value:
                    game_status += "\nDealer wins!"
                    user_data_user['purse'] -= bet_amount
                elif dealer_value < player_value:
                    game_status += "\nYou win!"
                    user_data_user['purse'] += bet_amount
                else:
                    game_status += "\nIt's a push. You get your bet back."

                game_over = True
            else:
                actions = ["hit", "stand"]
                if can_split:
                    actions.append("split")
                if can_double_down:
                    actions.append("double down")

                game_status += f"\nChoose an action: `{', '.join(actions)}`."
                await ctx.send(game_status)

                try:
                    response = await bot.wait_for('message', timeout=60, check=lambda m: m.author == ctx.author and m.content.lower() in actions)
                except asyncio.TimeoutError:
                    await ctx.send("You took too long to decide. Game over.")
                    game_over = True
                else:
                    action = response.content.lower()
                    if action == 'hit':
                        new_card = deck.pop()
                        player_hand.append(new_card)
                        player_value = calculate_hand_value(player_hand)
                    elif action == 'stand':
                        player_stand = True
                    elif action == 'split' and can_split:
                        # Implement split logic here
                        pass
                    elif action == 'double down' and can_double_down:
                        # Double the bet amount and draw one card
                        bet_amount *= 2
                        new_card = deck.pop()
                        player_hand.append(new_card)
                        player_value = calculate_hand_value(player_hand)
                        player_stand = True  # Automatically stand after doubling down

        # Remove the game state for this user
        del blackjack_games[user_id]

        # Save user data
        save_user_data(user_data)

        # Send the final game status message
        await ctx.send(game_status)

    else:
        await ctx.send("You are not registered. Use !register to create your save data.")

# Define the shop items and their prices
shop_items = {
    'item1': 100,
    'item2': 200,
    'item3': 300,
    # Add more items as needed
}

# Define a command to display the shop items
@bot.command(
    name='shop',
    description='View items available in the shop.',
    brief='View shop items.'
)
async def shop(ctx, page: int = 1):
    items_per_page = 5  # Number of items to display per page
    start_index = (page - 1) * items_per_page
    end_index = start_index + items_per_page

    shop_items_list = list(shop_items.keys())[start_index:end_index]

    if not shop_items_list:
        await ctx.send("No items found on this page.")
        return

    shop_message = "Shop Items (Page {}):\n".format(page)
    for item_name in shop_items_list:
        item_price = shop_items[item_name]
        shop_message += "{} - ${}\n".format(item_name, item_price)

    await ctx.send("```{}```".format(shop_message))

# Define a command to allow users to buy items from the shop
@bot.command(
    name='buy',
    description='Buy an item from the shop.',
    brief='Buy an item.'
)
async def buy(ctx, item_name: str):
    user_id = str(ctx.author.id)
    if user_id in user_data:
        data = user_data[user_id]
        purse_balance = data['purse']

        if item_name in shop_items:
            item_price = shop_items[item_name]

            if purse_balance >= item_price:
                data['purse'] -= item_price
                data['items'].append(item_name)
                save_user_data(user_data)
                await ctx.send("You have successfully bought {} for ${}.".format(item_name, item_price))
            else:
                await ctx.send("You don't have enough money to buy this item.")
        else:
            await ctx.send("Item not found in the shop.")
    else:
        await ctx.send("You are not registered. Use !register to create your save data.")

# Define a command to view a user's items
@bot.command(
    name='items',
    description="View the items you've bought from the shop.",
    brief='View your items.'
)
async def view_items(ctx):
    user_id = str(ctx.author.id)
    if user_id in user_data:
        items = user_data[user_id]['items']
        if items:
            item_list = ", ".join(items)
            await ctx.send("{}'s items: {}".format(ctx.author.display_name, item_list))
        else:
            await ctx.send("{} doesn't own any items.".format(ctx.author.display_name))
    else:
        await ctx.send("You are not registered. Use !register to create your save data.")



# Run the bot with your token
bot.run('you aint getting my bot token today man.')
Editor is loading...