Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Custom Commands/cardviewer/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 AngerRandom

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
28 changes: 28 additions & 0 deletions Custom Commands/cardviewer/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
> [!NOTE]
> This custom command was made by [AngerRandom](https://github.com/AngerRandom), I just made a easy to follow tutorial with markdown.

# How do I add this?

1. Drag the `cardgenerator.py` folder to `ballsdex/packages/balls`

It should look like this:

<img width="615" height="196" alt="image" src="https://github.com/user-attachments/assets/f83e1aa3-991f-4fd8-9b1b-e37edc93715d" />

2. Open `cog.py` in the same folder and import the following:
- from ballsdex.packages.balls.cardgenerator import CardGenerator
- import io
- from ballsdex.core.utils.transformers import BallTransform
- ballsdex.core.utils.transformers import SpecialTransform

If you need a reminder on how to import or don't know how, click [here](https://github.com/ContestedWheel/EvalEvalEval-BD/wiki/Adding-custom-commands#importing)

3. Open `command.py` and copy it's contents.

4. Add the command like normal. If you need a reminder on how to add them or don't know how, click [here](https://github.com/ContestedWheel/EvalEvalEval-BD/wiki/Adding-custom-commands#adding-a-command)

4.1. Optionally, uncomment the 4th app_commands if you want the command to be an admin command.

5. Save the file, and restart the bot using `docker compose restart`. Refresh your Discord if you don't see the command.

If there is any issue with this README, please let me know ASAP by pinging me in the Ballsdex Developers server (tag is ihailthenight1234).
143 changes: 143 additions & 0 deletions Custom Commands/cardviewer/cardgenerator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import os
import textwrap
from pathlib import Path
from typing import Any

from PIL import Image, ImageDraw, ImageFont, ImageOps

from ballsdex.settings import settings
from ballsdex.core.models import Ball, Special # Adjust import as needed

SOURCES_PATH = Path(os.path.dirname(os.path.abspath(__file__)), "../../core/image_generator")
WIDTH = 1500
HEIGHT = 2000

CORNERS = ((34, 261), (1393, 992))
artwork_size = [b - a for a, b in zip(*CORNERS)]

# If you have custom fonts in your bot, make sure to edit this below with the file names of your fonts.
# Don't forget the file extension at the end.
title_font = ImageFont.truetype(str(SOURCES_PATH / "ArsenicaTrial-Extrabold.ttf"), 170)
capacity_name_font = ImageFont.truetype(str(SOURCES_PATH / "Bobby Jones Soft.otf"), 110)
capacity_description_font = ImageFont.truetype(str(SOURCES_PATH / "OpenSans-Semibold.ttf"), 75)
stats_font = ImageFont.truetype(str(SOURCES_PATH / "Bobby Jones Soft.otf"), 130)
credits_font = ImageFont.truetype(str(SOURCES_PATH / "arial.ttf"), 40)

credits_color_cache = {}

class CardGenerator:
def __init__(self, ball: Ball, special: Special, media_path: str = "./admin_panel/media/"):
self.ball = ball
self.special = special
self.media_path = media_path
self.image = None
self.draw = None

def wrap_text(self, text: str, font: ImageFont.FreeTypeFont, max_width: int) -> list[str]:
paragraphs = text.split('%%')
lines = []
for para in paragraphs:
words = para.strip().split(' ')
current_line = ''
for word in words:
test_line = f"{current_line} {word}".strip()
if self.draw.textlength(test_line, font=font) <= max_width:
current_line = test_line
else:
if current_line:
lines.append(current_line)
current_line = word
if current_line:
lines.append(current_line)
return lines

def get_credit_color(self, region: tuple) -> tuple:
region_crop = self.image.crop(region)
brightness = sum(region_crop.convert("L").getdata()) / region_crop.width / region_crop.height
return (255, 255, 255, 255) if brightness > 100 else (255, 255, 255, 255)

def generate_image(self) -> tuple[Image.Image, dict[str, Any]]:
ball = self.ball
ball_health_color = (86, 255, 100, 255)
card_name = ball.cached_regime.name

# Load background image
if self.special:
card_name = getattr(self.special, "name", card_name)
self.image = Image.open(self.media_path + self.special.background).convert("RGBA")
else:
self.image = Image.open(self.media_path + ball.cached_regime.background).convert("RGBA")

icon = (
Image.open(self.media_path + ball.cached_economy.icon).convert("RGBA")
if ball.cached_economy else None
)

self.draw = ImageDraw.Draw(self.image)
shadow_color = "black"
shadow_offset = 3

# Title
self.draw.text((50, 20 + shadow_offset), ball.short_name or ball.country, font=title_font,
fill=shadow_color, stroke_width=8, stroke_fill=(0, 0, 0, 255))
self.draw.text((50, 20), ball.short_name or ball.country, font=title_font,
fill=(255, 255, 255, 255), stroke_width=8, stroke_fill=(0, 0, 0, 255))

# Capacity Name
cap_name_lines = textwrap.wrap(ball.capacity_name, width=26)
for i, line in enumerate(cap_name_lines):
y = 1025 + 100 * i
self.draw.text((100, y + shadow_offset), line, font=capacity_name_font, fill=shadow_color,
stroke_width=6, stroke_fill=(0, 0, 0, 255))
self.draw.text((100, y), line, font=capacity_name_font, fill=(255, 255, 255, 255),
stroke_width=6, stroke_fill=(0, 0, 0, 255))

# Capacity Description
max_width = 1325
wrapped_desc = self.wrap_text(ball.capacity_description, capacity_description_font, max_width)
for i, line in enumerate(wrapped_desc):
y = 1060 + 100 * len(cap_name_lines) + 80 * i
self.draw.text((60, y + shadow_offset), line, font=capacity_description_font, fill=shadow_color,
stroke_width=5, stroke_fill=(0, 0, 0, 255))
self.draw.text((60, y), line, font=capacity_description_font, fill=(255, 255, 255, 255),
stroke_width=5, stroke_fill=(0, 0, 0, 255))

# Rarity
if settings.show_rarity:
self.draw.text((60, y + 100), ball.rarity_name, font=capacity_description_font,
stroke_width=5, stroke_fill=(0, 0, 0, 255))

# Stats
self.draw.text((320, 1670 + shadow_offset), str(ball.health), font=stats_font,
fill=shadow_color, stroke_width=7, stroke_fill=(0, 0, 0, 255))
self.draw.text((320, 1670), str(ball.health), font=stats_font,
fill=ball_health_color, stroke_width=7, stroke_fill=(0, 0, 0, 255))

self.draw.text((1120, 1670 + shadow_offset), str(ball.attack), font=stats_font,
fill=shadow_color, stroke_width=7, stroke_fill=(0, 0, 0, 255), anchor="ra")
self.draw.text((1120, 1670), str(ball.attack), font=stats_font,
fill=(255, 66, 92, 255), stroke_width=7, stroke_fill=(0, 0, 0, 255), anchor="ra")

# Credits
if card_name not in credits_color_cache:
credits_color_cache[card_name] = self.get_credit_color((0, int(self.image.height * 0.8),
self.image.width, self.image.height))
self.draw.text((30, 1870),
f"Ballsdex by El Laggron, BrawlDex by AngerRandom, Brawl Stars by Supercell\n{ball.credits}",
font=credits_font,
fill=credits_color_cache[card_name],
stroke_width=3,
stroke_fill=(0, 0, 0, 255))

# Artwork
artwork = Image.open(self.media_path + ball.collection_card).convert("RGBA")
self.image.paste(ImageOps.fit(artwork, artwork_size), CORNERS[0])
artwork.close()

# Icon
if icon:
icon = ImageOps.fit(icon, (192, 192))
self.image.paste(icon, (1200, 30), mask=icon)
icon.close()

return self.image, {"format": "PNG"}
28 changes: 28 additions & 0 deletions Custom Commands/cardviewer/command.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# This is the viewcard command by AngerRandom.
# This command sends the card of a countryball in ephemeral.
# Uncomment the 4th app_commands if you want the command to be an admin command.
@app_commands.command(name="viewcard", description="View a card of an existing countryball.")
@app_commands.describe(countryball="The countryball to view card of")
@app_commands.describe(special="Apply a special to the card.")
# @app_commands.checks.has_any_role(*settings.root_role_ids)
async def viewcard(
self,
interaction: discord.Interaction["BallsDexBot"],
countryball: BallTransform,
special: SpecialTransform | None = None
):
generator = CardGenerator(countryball, special)
generator.special = special
image, _ = generator.generate_image()

buffer = io.BytesIO()
image.save(buffer, format="PNG")
buffer.seek(0)

# Send it as a Discord file
discord_file = discord.File(fp=buffer, filename="card.png")
try:
await interaction.response.send_message(file=discord_file, ephemeral=True)
except Exception as e:
log.error("Something went wrong.", exc_info=e)
await interaction.response.send_message("Something went wrong.", ephemeral=True)