brubru64

make me a discord bot that is able to create gif by pinging him and putting an image file and be able to repeat what you say in the same message when you type the activation word "petrabot" the bot must be named petra, I must be able to manage it even if it has a higher role than me in a server and it needs to be able to remove/add roles

Kodari AI
KodariJun 25 at 2:49 pm 9
PetraBot
A Discord bot named Petra with four core features: converts attached images into animated GIFs when mentioned, echoes messages back when the activation word "petrabot" is detected, and provides role management commands (add/remove roles) that bypass Discord's role hierarchy for designated bot managers. A BOT_MANAGER_ID in .env grants full control regardless of role position.

Here’s what I’m building:

  • @Petra + image → animated GIF conversion via Pillow

  • petrabot <text> → Petra repeats the text

  • !addrole / !removerole → role management, hierarchy-bypass for bot manager

  • .env holds token + your user ID for override control


Setup steps:

  1. Install deps — pip install -r requirements.txt

  2. Fill .env:

    • DISCORD_TOKEN → your bot token from discord.com/developers

    • BOT_MANAGER_ID → your Discord User ID (right-click yourself → Copy User ID — needs Developer Mode on)

  3. Run — python bot.py

Key behaviour notes:

  • @Petra + image → pulsing animated GIF sent back

  • petrabot hello! anywhere in a message → Petra echoes hello!

  • !addrole / !removerole — the bot manager ID bypasses all hierarchy checks so you always have control, even if Petra has a higher role than you

  • Petra’s role still must be above the target role in Server Settings for Discord to physically allow the assignment — that’s a Discord API hard limit, not something code can override

Kodari can make mistakes. Review important code before using.
Files
bot.py
README.md
requirements.txt
Code
3 321
bot.py
import discord
from discord.ext import commands
from discord import app_commands
import os
import io
import aiohttp
import logging
from PIL import Image
from dotenv import load_dotenv

load_dotenv()

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
log = logging.getLogger("petra")

TOKEN = os.getenv("DISCORD_TOKEN")
BOT_MANAGER_ID = int(os.getenv("BOT_MANAGER_ID", "0"))

intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents, help_command=None)


# ─── Utility ────────────────────────────────────────────────────────────────

def is_bot_manager(user: discord.Member | discord.User) -> bool:
    return user.id == BOT_MANAGER_ID


def make_gif(image_bytes: bytes) -> io.BytesIO:
    """Convert a static image into a simple animated GIF (fade pulse effect)."""
    src = Image.open(io.BytesIO(image_bytes)).convert("RGBA")

    # Resize to a reasonable cap so the GIF isn't huge
    max_size = 480
    src.thumbnail((max_size, max_size), Image.LANCZOS)

    frames = []
    steps = 10
    for i in range(steps):
        # Brightness oscillates: full → dim → full over the loop
        factor = 0.6 + 0.4 * abs((i - steps / 2) / (steps / 2))
        frame = src.copy().convert("RGB")
        r, g, b = frame.split()
        r = r.point(lambda p: int(p * factor))
        g = g.point(lambda p: int(p * factor))
        b = b.point(lambda p: int(p * factor))
        frames.append(Image.merge("RGB", (r, g, b)))

    output = io.BytesIO()
    frames[0].save(
        output,
        format="GIF",
        save_all=True,
        append_images=frames[1:],
        loop=0,
        duration=80,
        optimize=False,
    )
    output.seek(0)
    return output


# ─── Events ─────────────────────────────────────────────────────────────────

@bot.event
async def on_ready():
    log.info(f"Petra is online as {bot.user} (ID: {bot.user.id})")
    await bot.change_presence(activity=discord.Activity(
        type=discord.ActivityType.watching,
        name="for petrabot 👀"
    ))
    try:
        synced = await bot.tree.sync()
        log.info(f"Synced {len(synced)} slash command(s)")
    except Exception as e:
        log.error(f"Slash sync failed: {e}")


@bot.event
async def on_message(message: discord.Message):
    if message.author.bot:
        return

    content = message.content

    # ── GIF creation: @Petra + image attachment ──────────────────────────
    if bot.user in message.mentions and message.attachments:
        image_attachment = None
        for att in message.attachments:
            if att.content_type and att.content_type.startswith("image/"):
                image_attachment = att
                break

        if image_attachment:
            async with message.channel.typing():
                try:
                    async with aiohttp.ClientSession() as session:
                        async with session.get(image_attachment.url) as resp:
                            if resp.status != 200:
                                await message.reply("❌ Couldn't download that image.")
                                return
                            image_bytes = await resp.read()

                    gif_buffer = make_gif(image_bytes)
                    await message.reply(
                        "✨ Here's your GIF!",
                        file=discord.File(gif_buffer, filename="petra_gif.gif")
                    )
                except Exception as e:
                    log.error(f"GIF creation failed: {e}")
                    await message.reply("❌ Failed to create the GIF. Make sure the file is a valid image.")
            return

    # ── Echo: message contains "petrabot" ───────────────────────────────
    lower = content.lower()
    if "petrabot" in lower:
        # Extract text after "petrabot"
        idx = lower.index("petrabot") + len("petrabot")
        echo_text = content[idx:].strip()
        if echo_text:
            await message.channel.send(echo_text)
        else:
            await message.channel.send("You called? 👀")
        return

    await bot.process_commands(message)


# ─── Role management ────────────────────────────────────────────────────────

def can_manage_roles(ctx: commands.Context) -> bool:
    """Allow bot manager always; otherwise require Manage Roles permission."""
    if is_bot_manager(ctx.author):
        return True
    if isinstance(ctx.author, discord.Member):
        return ctx.author.guild_permissions.manage_roles
    return False


@bot.command(name="addrole")
async def add_role(ctx: commands.Context, member: discord.Member, *, role: discord.Role):
    """Add a role to a member. Bot manager bypasses hierarchy."""
    if not can_manage_roles(ctx):
        await ctx.send("❌ You don't have permission to manage roles.")
        return

    # Hierarchy check — skip for bot manager
    if not is_bot_manager(ctx.author):
        if ctx.guild.me.top_role <= role:
            await ctx.send(f"❌ My highest role is below **{role.name}** — I can't assign it.")
            return
        if isinstance(ctx.author, discord.Member) and ctx.author.top_role <= role:
            await ctx.send(f"❌ You can't assign a role higher than or equal to your own top role.")
            return

    # Bot manager path: temporarily check if bot can even assign it
    if is_bot_manager(ctx.author) and ctx.guild.me.top_role <= role:
        await ctx.send(
            f"⚠️ I can't assign **{role.name}** because it's above my own highest role. "
            "Move my role above it in Server Settings."
        )
        return

    try:
        await member.add_roles(role, reason=f"Added by {ctx.author} via Petra")
        await ctx.send(f"✅ Added **{role.name}** to {member.mention}.")
    except discord.Forbidden:
        await ctx.send("❌ I don't have permission to assign that role.")
    except Exception as e:
        log.error(f"add_role error: {e}")
        await ctx.send("❌ Something went wrong.")


@bot.command(name="removerole")
async def remove_role(ctx: commands.Context, member: discord.Member, *, role: discord.Role):
    """Remove a role from a member. Bot manager bypasses hierarchy."""
    if not can_manage_roles(ctx):
        await ctx.send("❌ You don't have permission to manage roles.")
        return

    if not is_bot_manager(ctx.author):
        if ctx.guild.me.top_role <= role:
            await ctx.send(f"❌ My highest role is below **{role.name}** — I can't remove it.")
            return
        if isinstance(ctx.author, discord.Member) and ctx.author.top_role <= role:
            await ctx.send(f"❌ You can't remove a role higher than or equal to your own top role.")
            return

    if is_bot_manager(ctx.author) and ctx.guild.me.top_role <= role:
        await ctx.send(
            f"⚠️ I can't remove **{role.name}** because it's above my own highest role. "
            "Move my role above it in Server Settings."
        )
        return

    try:
        await member.remove_roles(role, reason=f"Removed by {ctx.author} via Petra")
        await ctx.send(f"✅ Removed **{role.name}** from {member.mention}.")
    except discord.Forbidden:
        await ctx.send("❌ I don't have permission to remove that role.")