Field not updating in Discord.py

Question: I’m trying to create a blackjack bot in Discord but my field for the actual result of the game isn’t updating

I’ve tried adding print statements to find the error but that was no help. This is what I recieved from my print statements

**Current behavior: Embed: Your Cards: (17) 3, 3, 1 Dealer’s Cards: (24) 7, 7, 10 Result In progress

Print statements: Reaction received Player hits Reaction removed Reaction received Player stands**

Desired behavior Your Cards: 17 3, 3, 1 Dealer’s Cards: 24 7, 7, 10 Result:
Dealer has gone bust. Game over.

Repl link: https://replit.com/@chaosok/IdenticalLavishIntroductory#main.py

This is where I put the actual prints in my code:

if dealer_total >= 17:
    if dealer_total > 21 or (player_total <= 21 and player_total > dealer_total):
        await handle_win(ctx, accounts, author_id, bet, message, dealer_hand, dealer_total)
        print("Player won. Game over.")
    elif player_total < dealer_total:
        await handle_loss(ctx, accounts, author_id, bet, message, dealer_hand, dealer_total)
        print("Dealer won. Game over.")
    else:
        await handle_tie(ctx, accounts, author_id, bet, message, dealer_hand, dealer_total)
        print("It's a tie. Game over.")
    break

Here is my actual code I have currently:

import discord
import json
import random
import asyncio
from discord.ext import commands

intents = discord.Intents.all()
intents.typing = False

bot = commands.Bot(command_prefix=',', intents=intents)
bot.remove_command('help')

def load_accounts():
    try:
        with open('accounts.json', 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        return {}

def save_accounts(accounts):
    with open('accounts.json', 'w') as f:
        json.dump(accounts, f, indent=4)

@bot.event
async def on_ready():
    print(f'{bot.user.name} is online')

@bot.command(name="help")
async def help_command(ctx, command_name: str = None):
    if command_name:
        if command_name == "open":
            embed = discord.Embed(
                title="Command: Open",
                description="",
                color=0x7289DA
            )
            embed.add_field(name="", value="**Description:** Open a new account with a starting balance of 15 coins.", inline=False)
            embed.add_field(name="Permissions", value="❌", inline=True)
            embed.add_field(name="Aliases", value="❌", inline=True)
            embed.add_field(name="Usage", value="```,open```", inline=False)
            embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar.url)
            embed.set_footer(text="Type ,help <command> for more information on a specific command")
            await ctx.send(embed=embed)
        elif command_name == "balance":
            embed = discord.Embed(
                title="Command: balance",
                description="",
                color=0x7289DA
            )
            embed.add_field(name="", value="**Description:** Check your account balance.", inline=False)
            embed.add_field(name="Permissions", value="❌", inline=True)
            embed.add_field(name="Aliases", value="`bal`", inline=True)
            embed.add_field(name="Usage", value="```,balance```", inline=False)
            embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar.url)
            embed.set_footer(text="Type ,help <command> for more information on a specific command")
            await ctx.send(embed=embed)
        elif command_name == "leaderboard":
            embed = discord.Embed(
                title="Command: leaderboard",
                description="This command views the leaderboard of top users.",
                color=0x7289DA
            )
            embed.add_field(name="", value="**Description:** View the leaderboard of top users.", inline=False)
            embed.add_field(name="Permissions", value="❌", inline=True)
            embed.add_field(name="Aliases", value="`lb`", inline=True)
            embed.add_field(name="Usage", value="```,leaderboard```", inline=False)
            embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar.url)
            embed.set_footer(text="Type ,help <command> for more information on a specific command")
            await ctx.send(embed=embed)
        elif command_name == "daily":
            embed = discord.Embed(
                title="Command: daily",
                description="",
                color=0x7289DA
            )
            embed.add_field(name="", value="**Description:** Claims your daily coins.", inline=False)
            embed.add_field(name="Permissions", value="❌", inline=True)
            embed.add_field(name="Aliases", value="❌", inline=True)
            embed.add_field(name="Usage", value="```,daily```", inline=False)
            embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar.url)
            embed.set_footer(text="Type ,help <command> for more information on a specific command")
            await ctx.send(embed=embed)
        else:
            await ctx.send("That command does not exist.")
    else:
        embed = discord.Embed(
            title="Bot Commands",
            description="Here's a list of available commands:",
            color=0x7289DA
        )
        embed.add_field(name="`open`", value="Open a new account with a starting balance of 15 coins.", inline=False)
        embed.add_field(name="`balance`", value="Check your account balance.", inline=False)
        embed.add_field(name="`leaderboard`", value="View the leaderboard of top users.", inline=False)
        embed.add_field(name="`daily`", value="Claim your daily coins.", inline=False)
        embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar.url)
        embed.set_footer(text="Type ,help <command> for more information on a specific command")

        await ctx.send(embed=embed)

@bot.command(name="open")
async def open_command(ctx):
    author_id = str(ctx.author.id)
    accounts = load_accounts()
    if author_id not in accounts:
        accounts[author_id] = {'balance': 15}
        save_accounts(accounts)
        embed = discord.Embed(title="", color=0xabe86a)
        embed.add_field(name="", value=f"{ctx.author.mention}: Account successfully opened with the starting balance of **15** coins.", inline=False)
        await ctx.send(embed=embed)
    else:
        embed = discord.Embed(title="", color=0xe69f23)
        embed.add_field(name="", value=f"{ctx.author.mention}: You already have an account.", inline=False)
        await ctx.send(embed=embed)

@bot.command(name="balance", aliases=["bal"])
async def balance_command(ctx, user: commands.MemberConverter = None):
    if user is None:
        user = ctx.author

    author_id = str(user.id)
    accounts = load_accounts()

    if author_id in accounts:
        balance = accounts[author_id]['balance']
        formatted_balance = "{:,}".format(balance)
        all_balances = sorted([account['balance'] for account in accounts.values()], reverse=True)
        user_rank = all_balances.index(balance) + 1 if balance in all_balances else "N/A"

        embed = discord.Embed(title="", color=0xabe86a)
        embed.set_author(name=user.name, icon_url=user.avatar.url)
        embed.add_field(name="", value=f"<:money:1221139949055639695> {user.mention}'s balance is **{formatted_balance}**", inline=False)
        embed.set_footer(text=f"Global Rank: #{user_rank}")

        await ctx.send(embed=embed)
    else:
        await ctx.send("This user doesn't have an account.")

@bot.command(name="leaderboard", aliases=["lb"])
async def leaderboard_command(ctx):
    accounts = load_accounts()

    top_accounts = sorted(accounts.items(), key=lambda x: x[1]['balance'], reverse=True)[:10]

    leaderboard_text = ""
    for idx, (user_id, data) in enumerate(top_accounts, start=1):
        user = await bot.fetch_user(int(user_id))
        balance_with_commas = "{:,}".format(data['balance'])
        leaderboard_text += f"#{idx} **{user.name}#{user.discriminator}** with **{balance_with_commas}**\n"

    author_id = str(ctx.author.id)
    all_balances = sorted([account['balance'] for account in accounts.values()], reverse=True)
    user_rank = all_balances.index(accounts[author_id]['balance']) + 1 if author_id in accounts else "N/A"

    embed = discord.Embed(title="", color=0x7289DA)
    embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar.url)
    embed.description = leaderboard_text
    embed.set_footer(text=f"Your current ranking: #{user_rank}")

    await ctx.send(embed=embed)

@bot.command(pass_context=True)
@commands.cooldown(1, 86400, commands.BucketType.user)
async def daily(ctx):
    author_id = str(ctx.author.id)
    accounts = load_accounts()
    if author_id in accounts:
        balance = accounts[author_id]['balance']
        accounts[author_id]['balance'] += 100
        save_accounts(accounts)

        embed = discord.Embed(title="", description=f"You've claimed **100.00** coins. You now have **{balance}** coins.", color=0xabe86a)
        await ctx.send(embed=embed)
    else:
        embed = discord.Embed(title="", description="You don't have an account. Use the ,open command to create one.", color=0xe69f23)
        await ctx.send(embed=embed)
      
@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        remaining_time = error.retry_after
        hours = remaining_time // 3600
        minutes = (remaining_time // 60) % 60
        seconds = remaining_time % 60

        embed = discord.Embed(
            title="",
            description=f"You've already claimed your daily coins. Try again in: `{hours:02.0f}:{minutes:02.0f}:{seconds:02.0f}`",
            color=discord.Color.red()
        )
        await ctx.send(embed=embed)
      
@bot.command(name="blackjack", aliases=["bj"])
async def blackjack_command(ctx, bet: int):
  author_id = str(ctx.author.id)
  accounts = load_accounts()

  if author_id not in accounts:
      await ctx.send("You don't have an account. Use the ,open command to create one.")
      return

  if accounts[author_id]['balance'] < bet:
      await ctx.send("You don't have enough balance to place this bet.")
      return

  accounts[author_id]['balance'] -= bet
  save_accounts(accounts)

  player_hand = [draw_card(), draw_card()]
  dealer_hand = [draw_card(), draw_card()]

  player_total = calculate_total(player_hand)
  dealer_total = calculate_total(dealer_hand[1:])

  embed = discord.Embed(title="", color=0x232428)
  embed.add_field(name=f"Your Cards: {player_total}", value=format_hand(player_hand), inline=False)
  embed.add_field(name=f"Dealer's Cards: {dealer_total}", value=f"{format_hand(dealer_hand[1:])} ??? " , inline=False)
  embed.add_field(name="Result", value="In progress", inline=False)
  embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar.url)
  embed.set_thumbnail(url="https://i.imgur.com/JBPnaZz.png")

  message = await ctx.send(embed=embed)

  if player_total == 21:
      await handle_win(ctx, accounts, author_id, bet, message, dealer_hand, dealer_total)
      return

  await message.add_reaction("✅")
  await message.add_reaction("❌")

  def check(reaction, user):
      return user == ctx.author and str(reaction.emoji) in ["✅", "❌"]

  while True:
      try:
          reaction, user = await bot.wait_for("reaction_add", timeout=60, check=check)

          if str(reaction.emoji) == "✅":
              player_hand.append(draw_card())
              player_total = calculate_total(player_hand)
              embed.set_field_at(0, name=f"Your Cards: {player_total}", value=format_hand(player_hand), inline=False)
              await message.edit(embed=embed)

              if player_total > 21:
                  await handle_loss(ctx, accounts, author_id, bet, message, dealer_hand, dealer_total)
                  return

          else:
              while dealer_total < 17:
                  dealer_hand.append(draw_card())
                  dealer_total = calculate_total(dealer_hand)

              embed.set_field_at(1, name=f"Dealer's Cards: {dealer_total}", value=format_hand(dealer_hand), inline=False)
              await message.edit(embed=embed)

              if dealer_total >= 17:
                  if dealer_total > 21 or player_total > dealer_total:
                      await handle_win(ctx, accounts, author_id, bet, message, dealer_hand, dealer_total)
                      return
                  elif player_total < dealer_total:
                      await handle_loss(ctx, accounts, author_id, bet, message, dealer_hand, dealer_total)
                      return
                  else:
                      await handle_tie(ctx, accounts, author_id, bet, message, dealer_hand, dealer_total)
                      return

          await message.remove_reaction(reaction, user)
      except asyncio.TimeoutError:
          await message.delete()
          break

async def handle_win(ctx, accounts, author_id, bet, message, dealer_hand, dealer_total):
  accounts[author_id]['balance'] += bet * 2
  save_accounts(accounts)
  embed = discord.Embed(title="Blackjack", color=0x00FF00)
  embed.add_field(name=f"Your Cards: {format_total(player_hand)}", value=format_hand(player_hand), inline=False)
  embed.add_field(name="Dealer's Hand", value=format_hand(dealer_hand), inline=False)
  embed.add_field(name="Result", value=f"You won! New Balance: {accounts[author_id]['balance']}", inline=False)
  embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar.url)
  embed.set_thumbnail(url="https://i.imgur.com/JBPnaZz.png")
  await message.edit(embed=embed)

async def handle_loss(ctx, accounts, author_id, bet, message, dealer_hand, dealer_total):
  save_accounts(accounts)
  embed = discord.Embed(title="Blackjack", color=0xFF0000)
  embed.add_field(name=f"Your Cards: {format_total(player_hand)}", value=format_hand(player_hand), inline=False)
  embed.add_field(name="Dealer's Hand", value=format_hand(dealer_hand), inline=False)
  embed.add_field(name="Result", value=f"You lost! New Balance: {accounts[author_id]['balance']}", inline=False)
  embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar.url)
  embed.set_thumbnail(url="https://i.imgur.com/JBPnaZz.png")
  await message.edit(embed=embed)

async def handle_tie(ctx, accounts, author_id, bet, message, dealer_hand, dealer_total):
  accounts[author_id]['balance'] += bet
  save_accounts(accounts)
  embed = discord.Embed(title="Blackjack", color=0xFFFF00)
  embed.add_field(name=f"Your Cards: {format_total(player_hand)}", value=format_hand(player_hand), inline=False)
  embed.add_field(name="Dealer's Hand", value=format_hand(dealer_hand), inline=False)
  embed.add_field(name="Result", value=f"It's a tie! New Balance: {accounts[author_id]['balance']}", inline=False)
  embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar.url)
  embed.set_thumbnail(url="https://i.imgur.com/JBPnaZz.png")
  await message.edit(embed=embed)

def draw_card():
  return random.randint(1, 10)

def calculate_total(hand):
  total = sum(hand)
  if total <= 11 and 1 in hand:
      total += 10
  return total

def format_hand(hand):
  return ", ".join(str(card) for card in hand)
  
@bot.command(name="give", aliases=["transfer"])
async def give_command(ctx, recipient: discord.Member, amount: int):
    sender_id = str(ctx.author.id)
    recipient_username = recipient.name

    if amount <= 0:
        embed = discord.Embed(
            title="",
            description="Amount must be above **0.01**",
            color=0xe69f23
        )
        await ctx.send(embed=embed)
        return

    accounts = load_accounts()

    if sender_id not in accounts:
        embed = discord.Embed(
            title="",
            description="You don't have an account. Use the ,open command to create one.",
            color=0xe69f23
        )
        await ctx.send(embed=embed)
        return

    if accounts[sender_id]['balance'] < amount:
      formatted_balance = "{:,.2f}".format(accounts[sender_id]['balance'])
      embed = discord.Embed(
          title="",
          description=f"{ctx.author.mention}: You do not have **{amount:,.2f}** coins to transfer!",
          color=0xe69f23
      )
      await ctx.send(embed=embed)
      return

    accounts[sender_id]['balance'] -= amount
    recipient_id = str(recipient.id)
    accounts[recipient_id] = accounts.get(recipient_id, {'balance': 0})
    accounts[recipient_id]['balance'] += amount

    save_accounts(accounts)

    embed = discord.Embed(
        title="",
        description=f"{ctx.author.mention}: Transferred **{amount:,.2f}** coins to **{recipient_username}**!",
        color=0xabe86a
    )
    await ctx.send(embed=embed)

@bot.command(name="set")
async def set_balance(ctx, target_user: discord.Member, amount: str):
    if ctx.author.id != 538773310704582666:
        await ctx.send("You are not authorized to use this command.")
        return
      
    accounts = load_accounts()

    target_user_id = str(target_user.id)
    if target_user_id not in accounts:
        await ctx.send("This user doesn't have an account.")
        return

    if amount.startswith('+'):
        operation = 'add'
        amount = amount[1:]
    elif amount.startswith('-'):
        operation = 'remove'
        amount = amount[1:]
    else:
        operation = 'set'

    try:
        amount = int(amount)
    except ValueError:
        await ctx.send("Invalid amount. Please provide a valid number.")
        return

    if operation == 'add':
        accounts[target_user_id]['balance'] += amount
    elif operation == 'remove':
        accounts[target_user_id]['balance'] -= amount
    else:
        accounts[target_user_id]['balance'] = amount

    save_accounts(accounts)

    await ctx.send(f"The balance for {target_user.mention} has been {'increased' if operation == 'add' else 'decreased' if operation == 'remove' else 'set to'} {accounts[target_user_id]['balance']} coins.")

bot.run('[REDACTED - CHANGE ASAP]')

Hi @chaosok!

Please remove your bot’s API token from your code, as it will let other control your bot.

2 Likes

Didnt even realise this when I posted. Thanks for reminding me

1 Like

Also, please regenerate that token ASAP. It should be considered compromised.

2 Likes