Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 746
bot.py
import asyncio
import json
import logging
import os
import re
from io import BytesIO
from urllib.parse import urlparse
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
from PIL import Image, ImageOps
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("grid-bot")
MAX_GRID_SIZE = 32
MAX_UPLOAD_BYTES = 8 * 1024 * 1024
IMAGE_EXTENSIONS = {".bmp", ".gif", ".jpeg", ".jpg", ".png", ".webp"}
SQUARE_PALETTE = (
(0, 0, 0, "β¬"),
(255, 255, 255, "β¬"),
(237, 28, 36, "π₯"),
(255, 127, 39, "π§"),
(255, 242, 0, "π¨"),
(34, 177, 76, "π©"),
(0, 162, 232, "π¦"),
(163, 73, 164, "πͺ"),
(185, 122, 87, "π«"),
)
DEFAULT_PANEL_TITLE = "Pixel Grid Studio"
DEFAULT_PANEL_DESCRIPTION = (
"Create a grid up to **32 Γ 32** squares, then add an image to turn it into "
"pixel-art color blocks."
)
DEFAULT_PANEL_COLOR = "#57F287"
GRID_CHANNEL_CONFIG = "grid_config.json"
def load_grid_channels() -> dict[str, int]:
try:
with open(GRID_CHANNEL_CONFIG, "r", encoding="utf-8") as config_file:
values = json.load(config_file)
except FileNotFoundError:
return {}
except (json.JSONDecodeError, OSError):
logger.warning("Could not read %s; starting without configured channels", GRID_CHANNEL_CONFIG)
return {}
if not isinstance(values, dict):
return {}
channels: dict[str, int] = {}
for guild_id, channel_id in values.items():
try:
channels[str(guild_id)] = int(channel_id)
except (TypeError, ValueError):
continue
return channels
def save_grid_channels() -> None:
with open(GRID_CHANNEL_CONFIG, "w", encoding="utf-8") as config_file:
json.dump(GRID_CHANNELS, config_file, indent=2)
GRID_CHANNELS = load_grid_channels()
def is_configured_channel(guild_id: int | None, channel_id: int | None) -> bool:
return (
guild_id is not None
and channel_id is not None
and GRID_CHANNELS.get(str(guild_id)) == channel_id
)
def blank_grid(width: int, length: int) -> list[str]:
return ["β¬" * width for _ in range(length)]
def grid_message(width: int, length: int, rows: list[str]) -> str:
return f"**Grid: {width} Γ {length}**\n" + "\n".join(rows)
def nearest_square(red: int, green: int, blue: int) -> str:
palette_color = min(
SQUARE_PALETTE,
key=lambda color: (
(red - color[0]) ** 2
+ (green - color[1]) ** 2
+ (blue - color[2]) ** 2
),
)
return palette_color[3]
def image_grid(image_data: bytes, width: int, length: int) -> list[str]:
try:
with Image.open(BytesIO(image_data)) as source:
source.load()
oriented = ImageOps.exif_transpose(source).convert("RGBA")
background = Image.new("RGBA", oriented.size, (255, 255, 255, 255))
background.alpha_composite(oriented)
image = background.convert("RGB")
fitted = ImageOps.contain(
image,
(width, length),
method=Image.Resampling.LANCZOS,
)
canvas = Image.new("RGB", (width, length), (255, 255, 255))
left = (width - fitted.width) // 2
top = (length - fitted.height) // 2
canvas.paste(fitted, (left, top))
pixels = canvas.load()
return [
"".join(nearest_square(*pixels[x, y]) for x in range(width))
for y in range(length)
]
except Exception as error:
raise ValueError("That file could not be converted into a grid image.") from error
def is_image_attachment(attachment: discord.Attachment) -> bool:
content_type = (attachment.content_type or "").lower()
filename = attachment.filename.lower()
return content_type.startswith("image/") or any(
filename.endswith(extension) for extension in IMAGE_EXTENSIONS
)
class GridBot(commands.Bot):
def __init__(self) -> None:
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix="!", intents=intents)
async def setup_hook(self) -> None:
await self.tree.sync()
logger.info("Application commands synced")
bot = GridBot()
class StartView(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout=900)
async def interaction_check(self, interaction: discord.Interaction) -> bool:
if not is_configured_channel(interaction.guild_id, interaction.channel_id):
await interaction.response.send_message(
"This bot can only be used in the channel configured by a server administrator.",
ephemeral=True,
)
return False
return True
@discord.ui.button(
label="Start Project",
style=discord.ButtonStyle.success,
emoji="π©",
)
async def start_project(
self,
interaction: discord.Interaction,
button: discord.ui.Button,
) -> None:
await interaction.response.send_modal(SizeModal())
class SizeModal(discord.ui.Modal, title="Choose your grid size"):
width = discord.ui.TextInput(
label="Width (1β32)",
placeholder="For example: 16",
min_length=1,
max_length=2,
required=True,
)
length = discord.ui.TextInput(
label="Length (1β32)",
placeholder="For example: 16",
min_length=1,
max_length=2,
required=True,
)
async def on_submit(self, interaction: discord.Interaction) -> None: