Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

whats wrong with my discord bot code: from PIL import Image, ImageDraw, ImageFont,…

  1. User

    whats wrong with my discord bot code: from PIL import Image, ImageDraw, ImageFont, ImageOps import requests from io import BytesIO import os

    @bot.command() async def fontcheck(ctx): """Check if emoji font is loaded""" try: ImageFont.truetype("NotoColorEmoji.ttf", 36) await ctx.send("✅ Emoji font loaded successfully!") except Exception as e: await ctx.send(f"❌ Font error: {str(e)}")

    async def generate_profile_image( user: discord.User, balance: int, rolls: int, items_bought: int, total_items: int, luck: float, speed: float, cooldown: int ) -> discord.File: """Generate a custom profile card with user stats.""" try: from PIL import Image, ImageDraw, ImageFont import os import requests from io import BytesIO import discord

        # Fallback text measuring function (for older Pillow versions)
        def measure_text(text: str, font: ImageFont.FreeTypeFont):
            # create a mask for the text, then measure the bounding box
            mask = font.getmask(text, mode="L")
            bbox = mask.getbbox()
            if bbox:
                return bbox[2] - bbox[0], bbox[3] - bbox[1]
            else:
                return 0, 0
    
        WIDTH, HEIGHT = 1200, 450
        avatar_size = 300
    
        # ===== 1. Background =====
        if os.path.exists("profile_bg.png"):
            bg = Image.open("profile_bg.png").convert("RGBA").resize((WIDTH, HEIGHT))
        else:
            bg = Image.new("RGBA", (WIDTH, HEIGHT), (25, 25, 25, 255))
            draw_bg = ImageDraw.Draw(bg)
            for i in range(HEIGHT):
                draw_bg.line([(0, i), (WIDTH, i)], fill=(30 + i // 8, 30 + i // 8, 30 + i // 8))
        draw = ImageDraw.Draw(bg)
    
        # ===== 2. Avatar =====
        avatar_url = user.display_avatar.url
        response = requests.get(avatar_url, timeout=10)
        avatar = Image.open(BytesIO(response.content)).convert("RGBA")
        avatar = avatar.resize((avatar_size, avatar_size))
    
        mask = Image.new("L", (avatar_size, avatar_size), 0)
        ImageDraw.Draw(mask).ellipse((0, 0, avatar_size, avatar_size), fill=255)
        bg.paste(avatar, (50, (HEIGHT - avatar_size) // 2), mask)
    
        # ===== 3. Fonts =====
        emoji_font = None
        for path in [
            "C:/Windows/Fonts/seguiemj.ttf",
            "/System/Library/Fonts/Apple Color Emoji.ttf",
            "/usr/share/fonts/truetype/noto/NotoColorEmoji.ttf",
            "NotoColorEmoji.ttf"
        ]:
            try:
                emoji_font = ImageFont.truetype(path, 36)
                break
            except:
                pass
        if not emoji_font:
            print("Couldn't load emoji font – emojis may not appear.")
    
        try:
            arial_bold_path = "/System/Library/Fonts/Supplemental/Arial Bold.ttf"
            title_font_size = 42
            stat_font_size = 36
            title_font = ImageFont.truetype(arial_bold_path, title_font_size)
            stat_font = ImageFont.truetype(arial_bold_path, stat_font_size)
        except Exception as e:
            print(f"Font error: {e}")
            title_font = ImageFont.load_default()
            stat_font = ImageFont.load_default()
    
        text_color = (255, 255, 255)
    
        # ===== 4. Title =====
        username = user.name
        title_text = f"{username}'s Profile"
        title_w, title_h = measure_text(title_text, title_font)
    
        # ===== 5. Stats =====
        stats_left = [
            ("💰", "Balance:", f"${balance:,}"),
            ("🍀", "Luck Multiplier:", f"{luck:.2f}x"),
            ("⚡", "Roll Speed:", f"{speed:.2f}x"),
            ("⌛", "Cooldown:", f"{cooldown}s")
        ]
        stats_right = [
            ("🎲", "Total Rolls:", f"{rolls:,}"),
            ("🛒", "Items Bought:", f"{items_bought:,}"),
            ("📦", "Total Items:", f"{total_items:,}")
        ]
    
        line_spacing = 50
        max_line_count = max(len(stats_left), len(stats_right))
        total_stats_height = max_line_count * line_spacing
        spacing_from_title = 70
        total_block_height = title_h + spacing_from_title + total_stats_height
        top_offset = (HEIGHT - total_block_height) // 2  # vertical center
    
        # draw the title
        header_x = 400
        header_y = top_offset
        draw.text((header_x, header_y), title_text, text_color, font=title_font)
    
        y_start = header_y + title_h + spacing_from_title
    
        col1_x = 400
        col2_x = col1_x + 450
    
        # function to draw a stat row
        def draw_stat_row(x, y, emoji, label, value):
            if emoji_font:
                try:
                    draw.text((x, y - 5), emoji, font=emoji_font, embedded_color=True)
                except TypeError:
                    draw.text((x, y - 5), emoji, font=emoji_font, fill=text_color)
                x += 45
            draw.text((x, y), label, text_color, font=stat_font)
            label_w, _ = measure_text(label, stat_font)
            gap = 10
            draw.text((x + label_w + gap, y), value, text_color, font=stat_font)
    
        current_y_left = y_start
        for emoji, label, value in stats_left:
            draw_stat_row(col1_x, current_y_left, emoji, label, value)
            current_y_left += line_spacing
    
        current_y_right = y_start
        for emoji, label, value in stats_right:
            draw_stat_row(col2_x, current_y_right, emoji, label, value)
            current_y_right += line_spacing
    
        # ===== 6. Save & Return =====
        temp_path = f"temp_profile_{user.id}.png"
        bg.save(temp_path)
        return discord.File(temp_path, filename="profile.png")
    
    except Exception as e:
        print(f"Profile Image Error: {str(e)}")
        raise
    finally:
        if 'temp_path' in locals() and os.path.exists(temp_path):
            os.remove(temp_path)
    

    @bot.command() async def profile(ctx, member: discord.Member = None): """View a user's profile with custom image""" member = member or ctx.author inventory = load_json(INVENTORY_FILE) user_id = str(member.id)

    stats_data = {
        "balance": inventory.get(user_id, {}).get("balance", 0),
        "rolls": inventory.get(user_id, {}).get("gamble_count", 0),
        "items_bought": inventory.get(user_id, {}).get("items_bought", 0),
        "total_items": sum(item["amount"] for item in inventory.get(user_id, {}).get("items", {}).values()),
        "luck": UserStats(member.id).get_stat("luck"),
        "speed": UserStats(member.id).get_stat("roll_speed"),
        "cooldown": UserStats(member.id).get_stat("roll_cooldown")
    }
    
    try:
        file = await generate_profile_image(member, **stats_data)
        embed = discord.Embed(color=discord.Color.blurple())
        embed.set_image(url="attachment://profile.png")
        await ctx.send(file=file, embed=embed)
    except Exception as e:
        await send_error(ctx, f"Failed to generate profile: {str(e)}", "profile")
    

    i get this error: /usr/bin/python3 /Users/supermegaoriginalusrname/PycharmProjects/PythonProject2 copy/gamblingbot/gamblingbot8-beta.py /Users/supermegaoriginalusrname/Library/Python/3.9/lib/python/site-packages/urllib3/init.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020 warnings.warn( [2025-03-09 16:23:15] [INFO ] discord.client: logging in using static token [2025-03-09 16:23:16] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: d52b2311582e9097e0dd40a705e2d5f8). Connected to Discord as Exy-Gambling-Bot#8860! Profile Image Error: 'FreeTypeFont' object has no attribute 'getsize'

  2. Assistant

    The error message indicates that your code is trying to use the getsize method on a FreeTypeFont object, which does not exist. This usually happens because of incorrect function calls. In the context you provided, you're trying to measure text size with a function (likely the measure_text function) but it might not be handling the font object in the way that the ImageFont class expects.

    Here's how you can resolve this error:

    1. Use the Right Method to Measure Text Size: Instead of using getsize, you should use the getbbox method (or getmask as you seem to have done) to get the bounding box for your text. You already have a custom function, measure_text, which decrees what getsize would have done. The original Pillow's getsize method has been deprecated in some versions, and you may rely on your custom function instead.

    2. Check the Emoji Font Loading: If there’s any chance emoji handling is involved when you’re drawing text, ensure your emoji font is loaded correctly. You are already handling exceptions, but just monitor that part.

    3. Update the draw_stat_row function: Make sure to replace the calls to getsize() or adjust as needed in your text drawing areas.

    Here is how you might modify the relevant sections of your code:

    Updated Measure Function:

    def measure_text(text: str, font: ImageFont.FreeTypeFont):
        # Use the bounding box to measure text
        bbox = font.getmask(text).getbbox()
        if bbox:
            return bbox[2] - bbox[0], bbox[3] - bbox[1]  # Width and Height
        return 0, 0
    

    Drawing Text:

    Here’s a section of how you might be calling the measure_text function:

    # Draw the title
    header_x = 400
    header_y = top_offset
    draw.text((header_x, header_y), title_text, text_color, font=title_font)
    title_size = measure_text(title_text, title_font) 
    # Here's where you'll want to track sizes without using `getsize()`
    

    Additional Suggestions:

    • Update Libraries: Make sure you’re using the latest versions of Pillow and other libraries to avoid deprecated methods.
    • Use Logging: Since you're using logging to print errors, consider adding more context to your error messages. It can help understand problems better.

    Final Debugging:

    If you continue to receive a similar error message regarding the FreeTypeFont, carefully go through any places where font-related operations happen, ensuring that configurations are set correctly and align with the expected interface in whichever Pillow version you are using.

    By following these steps, you should be able to correct the issue regarding the missing getsize method of the FreeTypeFont object in your bot code.