ttjchimp

create a raid bot

Kodari AI
KodariJun 23 at 9:07 pm 7
RaidBot
A Discord bot for organizing and managing raid events in gaming communities. Features include raid creation with customizable slots and roles, sign-up/leave commands, automatic roster management, and raid reminders. Supports multiple raids simultaneously, role-based sign-ups (tank, healer, DPS), raid leader controls, and embeds for clean raid display. Built with discord.py using slash commands and persistent event tracking.

How It Works

  • /raid_create — Takes a name, display datetime (e.g. June 20 at 8PM UTC), an ISO datetime for the reminder system, and optional role slot counts. Posts a live embed showing the full roster.

  • Sign-ups update the original embed in-place so the roster is always visible in one place.

  • Reminder loop runs every minute and pings all signed members ~30 min before the raid’s ISO datetime.

  • Raids persist in raids.json across restarts.

Note: For the reminder system to work, pass datetime_iso in full ISO 8601 format with timezone, e.g. 2025-06-20T20:00:00+00:00.

Kodari can make mistakes. Review important code before using.
Files
main.py
README.md
requirements.txt
Code
3 380
main.py
import discord
from discord.ext import commands, tasks
from discord import app_commands
import os
import json
import asyncio
from datetime import datetime, timezone
from dotenv import load_dotenv

load_dotenv()

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

raids: dict = {}

def save_raids():
    with open("raids.json", "w") as f:
        json.dump(raids, f, indent=2)

def load_raids():
    global raids
    if os.path.exists("raids.json"):
        with open("raids.json", "r") as f:
            raids = json.load(f)

def build_raid_embed(raid: dict) -> discord.Embed:
    embed = discord.Embed(
        title=f"⚔️ {raid['name']}",
        description=raid.get("description", "No description provided."),
        color=discord.Color.gold(),
        timestamp=datetime.fromisoformat(raid["created_at"])
    )

    embed.add_field(name="📅 Date & Time", value=raid["datetime"], inline=True)
    embed.add_field(name="👑 Raid Leader", value=f"<@{raid['leader_id']}>", inline=True)
    embed.add_field(name="🆔 Raid ID", value=f"`{raid['id']}`", inline=True)

    for role_name, role_data in raid["roles"].items():
        signed = role_data["signed"]
        max_slots = role_data["slots"]
        emoji = role_data["emoji"]
        if signed:
            members = "\n".join(f"• <@{uid}>" for uid in signed)
        else:
            members = "*No sign-ups yet*"
        embed.add_field(
            name=f"{emoji} {role_name} ({len(signed)}/{max_slots})",
            value=members,
            inline=True
        )

    total_signed = sum(len(r["signed"]) for r in raid["roles"].values())
    total_slots = sum(r["slots"] for r in raid["roles"].values())
    status = "🟢 Open" if raid["open"] else "🔴 Closed"
    embed.set_footer(text=f"Status: {status}  |  Total: {total_signed}/{total_slots}")
    return embed

@bot.event
async def on_ready():
    load_raids()
    print(f"✅ Logged in as {bot.user} (ID: {bot.user.id})")
    try:
        synced = await bot.tree.sync()
        print(f"✅ Synced {len(synced)} slash command(s)")
    except Exception as e:
        print(f"❌ Failed to sync commands: {e}")
    reminder_loop.start()

@tasks.loop(minutes=1)
async def reminder_loop():
    now = datetime.now(timezone.utc)
    for raid_id, raid in list(raids.items()):
        if not raid.get("open"):
            continue
        reminder_sent = raid.get("reminder_sent", False)
        if reminder_sent:
            continue
        try:
            raid_dt = datetime.fromisoformat(raid["datetime_iso"])
            diff_minutes = (raid_dt - now).total_seconds() / 60
            if 0 < diff_minutes <= 30:
                channel = bot.get_channel(int(raid["channel_id"]))
                if channel:
                    signed_ids = []
                    for role_data in raid["roles"].values():
                        signed_ids.extend(role_data["signed"])
                    mentions = " ".join(f"<@{uid}>" for uid in set(signed_ids))
                    await channel.send(
                        f"⏰ **Reminder:** The raid **{raid['name']}** starts in ~30 minutes!\n{mentions}"
                    )
                    raids[raid_id]["reminder_sent"] = True
                    save_raids()
        except Exception:
            pass

@bot.tree.command(name="raid_create", description="Create a new raid event.")
@app_commands.describe(
    name="Name of the raid",
    datetime_str="Date and time (e.g. 2025-06-20 20:00 UTC)",
    datetime_iso="ISO format datetime for reminders (e.g. 2025-06-20T20:00:00+00:00)",
    description="Short description of the raid",
    tank_slots="Number of tank slots (default 2)",
    healer_slots="Number of healer slots (default 3)",
    dps_slots="Number of DPS slots (default 15)"
)
async def raid_create(
    interaction: discord.Interaction,
    name: str,
    datetime_str: str,
    datetime_iso: str,
    description: str = "No description provided.",
    tank_slots: int = 2,
    healer_slots: int = 3,
    dps_slots: int = 15
):
    raid_id = str(int(datetime.now(timezone.utc).timestamp()))

    raid = {
        "id": raid_id,
        "name": name,
        "description": description,
        "datetime": datetime_str,
        "datetime_iso": datetime_iso,
        "channel_id": str(interaction.channel_id),
        "leader_id": str(interaction.user.id),
        "open": True,
        "created_at": datetime.now(timezone.utc).isoformat(),
        "reminder_sent": False,
        "message_id": None,
        "roles": {
            "Tank": {"emoji": "🛡️", "slots": tank_slots, "signed": []},
            "Healer": {"emoji": "💚", "slots": healer_slots, "signed": []},
            "DPS": {"emoji": "⚔️", "slots": dps_slots, "signed": []}
        }
    }

    embed = build_raid_embed(raid)
    await interaction.response.send_message(embed=embed)
    msg = await interaction.original_response()
    raid["message_id"] = str(msg.id)
    raids[raid_id] = raid
    save_raids()

@bot.tree.command(name="raid_join", description="Sign up for a raid.")
@app_commands.describe(
    raid_id="The raid ID to join",
    role="Your role: Tank, Healer, or DPS"
)
@app_commands.choices(role=[
    app_commands.Choice(name="Tank", value="Tank"),
    app_commands.Choice(name="Healer", value="Healer"),
    app_commands.Choice(name="DPS", value="DPS")
])
async def raid_join(interaction: discord.Interaction, raid_id: str, role: str):
    if raid_id not in raids:
        await interaction.response.send_message("❌ Raid not found.", ephemeral=True)
        return

    raid = raids[raid_id]
    if not raid["open"]:
        await interaction.response.send_message("❌ This raid is closed.", ephemeral=True)
        return

    user_id = str(interaction.user.id)
    for role_name, role_data in raid["roles"].items():
        if user_id in role_data["signed"]:
            await interaction.response.send_message(
                f"❌ You are already signed up as **{role_name}**. Use `/raid_leave` first.", ephemeral=True
            )
            return

    role_data = raid["roles"][role]
    if len(role_data["signed"]) >= role_data["slots"]:
        await interaction.response.send_message(f"❌ **{role}** slots are full.", ephemeral=True)
        return

    role_data["signed"].append(user_id)
    save_raids()

    embed = build_raid_embed(raid)
    await interaction.response.send_message(
        f"✅ You've signed up as **{role}** for **{raid['name']}**!", ephemeral=True
    )
    await update_raid_message(interaction, raid, embed)

@bot.tree.command(name="raid_leave", description="Remove yourself from a raid.")
@app_commands.describe(raid_id="The raid ID to leave")
async def raid_leave(interaction: discord.Interaction, raid_id: str):
    if raid_id not in raids:
        await interaction.response.send_message("❌ Raid not found.", ephemeral=True)
        return

    raid = raids[raid_id]
    user_id = str(interaction.user.id)
    removed = False

    for role_data in raid["roles"].values():
        if user_id in role_data["signed"]:
            role_data["signed"].remove(user_id)