._dolly_.

Create a grid bot for discord members to use. The grid must be no larger than 32 x 32 squares, but be customisable as to how many squares a member wants to use width x length. Add a green start project button which then asks the member the size of the grid they want. Insert their grid in the channel. On the grid add a button that allows them to insert an image directly on to the grid. Convert the image on the grid to a pixilated colour template with a colour per grid square. The whole grid must represent the image added by the member as best it possibly can.

Kodari AI
KodariAug 11 at 6:32 pm 1
PixelGridBot
A Discord bot that lets members create customizable pixel art grids up to 32x32 squares. Users click a green start button to specify grid dimensions, then the grid is inserted into the channel. Members can upload an image onto the grid, which converts it into a pixelated color template with one color per square, accurately representing the original image.
  • Create a discord.py bot with a green project-start panel and slash/prefix entry points.

  • Add validated 1–32 width/length modal input and render each member’s grid in-channel.

  • Add an image-upload workflow that pixelates uploads to the chosen grid and maps colors to square emojis.

  • Include dependency and environment files without hardcoding credentials.

Created the Discord grid bot project:

  • bot.py β€” discord.py bot with /grid and !grid

  • Green Start Project button

  • Custom grid dimensions from 1Γ—1 through 32Γ—32

  • In-channel grid display

  • Image upload workflow through the Insert Image button

  • Image resizing, aspect-ratio preservation, pixelation, and color-square mapping

  • Upload size and file validation

  • requirements.txt

  • .env.example

  • .gitignore

Run it with:

Shell
pip install -r requirements.txt
cp .env.example .env
python bot.py

Set DISCORD_TOKEN in .env, and enable the Message Content Intent for the bot in the Discord Developer Portal.

._dolly_.

Above the green start project button, create a customisable colour embed with customisable markdown title, description and footer that server animated emoji can be put in by text. Also option to add thumbnail image.

Kodari AI
KodariAug 11 at 6:38 pm 1
  • Add a configurable announcement embed above the green Start Project button.

  • Support custom title, description, footer, colour, thumbnail URL, and animated emoji text.

  • Keep the existing grid workflow and expose embed configuration through a bot command.

Updated bot.py so /grid now supports a customizable embed above the green Start Project button.

Options:

Plain Text
/grid
title: 🎨 <:animated_emoji:123456789>
description: **Create your pixel project!**
footer: Built with <:sparkle:123456789>
colour: #5865F2
thumbnail: https://example.com/image.png

Included:

  • Markdown-compatible title and description

  • Server animated emoji text such as <a:name:id>

  • Custom footer

  • Custom hex colour, including shorthand like #fff

  • Optional thumbnail image URL

  • Validation for Discord embed field limits and thumbnail URLs

  • Existing !grid command still uses the default embed configuration

._dolly_.

Whitelist admin commands for all aspects. Only allow members to create using the green start project button and to add their grid size and to input image.

Kodari AI
KodariAug 11 at 6:41 pm 1
  1. Restrict the customizable /grid panel command to members with the Administrator permission.

  2. Restrict the legacy !grid command to server administrators and reject DM use.

  3. Keep project creation, grid sizing, and image insertion available through the green-button flow, with each grid editable only by its creator.

Updated bot.py:

  • /grid is now restricted to server members with the Administrator permission.

  • !grid is also restricted to administrators and cannot be used in DMs.

  • Non-admins receive an ephemeral or temporary permission error.

  • The green Start Project button remains available to all members.

  • Members can still enter their own grid size and upload an image.

  • Only the member who created a grid can use its Insert Image button.

._dolly_.

Create read me section to explain how to set up this bot

Kodari AI
KodariAug 11 at 6:42 pm 1

Created README.md with setup and usage instructions covering:

  • Discord application and bot token setup

  • Message Content Intent

  • Bot invitation scopes and permissions

  • Python virtual environment installation

  • .env configuration

  • Starting the bot

  • Administrator-only panel commands

  • Custom embed options and animated emoji syntax

  • Member grid creation and image upload workflow

  • Troubleshooting and token security

._dolly_.

Allow application / commands for admin to add title, description, footer, embed colour and thumbnail.

Kodari AI
KodariAug 11 at 6:46 pm 1

The admin application command is already configured as /grid with optional fields for:

  • title

  • description

  • footer

  • colour

  • thumbnail

It is restricted to server administrators using both Discord’s default command permissions and a runtime administrator check. Example:

Plain Text
/grid
title:"🎨 Pixel Studio"
description:"**Upload an image to create pixel art!**"
footer:"Created with <a:sparkles:123456789012345678>"
colour:"#5865F2"
thumbnail:"https://example.com/image.png"

Members cannot use /grid; they can only start projects through the green Start Project button.

._dolly_.

Do instructions for windows only

Kodari AI
KodariAug 11 at 6:48 pm 1

Updated README.md to contain Windows-only setup instructions:

  • Removed macOS/Linux virtual environment instructions.

  • Uses Windows PowerShell commands throughout.

  • Includes Windows commands for copying .env.example.

  • Uses PowerShell to install dependencies and start the bot.

._dolly_.

Leave the members finished grid project permanently in the channel so other members can see the finished project, but not amend it. Only allow this bot in a channel specified by an admin.

Kodari AI
KodariAug 11 at 6:54 pm 1
  1. Restrict all bot interactions to an administrator-configured channel.

  2. Make completed grids persistent and view-only for everyone except the bot, removing amendment controls after image placement.

  3. Update the Windows README with the channel configuration and finished-project behavior.

  1. Added admin-only /grid-channel channel:#channel-name to select the bot’s single permitted channel.

  2. Saved the selected channel in grid_config.json, surviving bot restarts.

  3. Restricted /grid, !grid, Start Project, grid sizing, and image uploads to the configured channel.

  4. Finished grids now permanently remain visible in the channel with the Insert Image button removed, preventing further edits.

  5. Updated the Windows-only README.md and .gitignore with the new channel configuration instructions.

Kodari can make mistakes. Review important code before using.
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: