Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 211
bot.py
import asyncio
import logging
import os
import time
from typing import Optional
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("raid-drill")
def required_int(name: str) -> int:
value = os.getenv(name, "").strip()
if not value:
raise RuntimeError(f"Missing required environment variable: {name}")
try:
return int(value)
except ValueError as exc:
raise RuntimeError(f"{name} must be an integer") from exc
TOKEN = os.getenv("DISCORD_TOKEN", "").strip()
if not TOKEN:
raise RuntimeError("Missing required environment variable: DISCORD_TOKEN")
TEST_CHANNEL_ID = required_int("TEST_CHANNEL_ID")
TEST_GUILD_ID = int(os.getenv("TEST_GUILD_ID", "0"))
MAX_BURST = max(1, min(int(os.getenv("MAX_BURST", "10")), 10))
COOLDOWN_SECONDS = max(0, int(os.getenv("COOLDOWN_SECONDS", "60")))
SEND_INTERVAL_SECONDS = max(1, int(os.getenv("SEND_INTERVAL_SECONDS", "1")))
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
active_task: Optional[asyncio.Task] = None
stop_event: Optional[asyncio.Event] = None
last_run_at = 0.0
def staff_member(interaction: discord.Interaction) -> Optional[discord.Member]:
if isinstance(interaction.user, discord.Member):
return interaction.user
return None
async def configured_test_channel() -> Optional[discord.TextChannel]:
channel = bot.get_channel(TEST_CHANNEL_ID)
if channel is None:
try:
channel = await bot.fetch_channel(TEST_CHANNEL_ID)
except (discord.HTTPException, discord.NotFound):
return None
return channel if isinstance(channel, discord.TextChannel) else None
async def run_spam_simulation(channel: discord.TextChannel, count: int) -> None:
global active_task, stop_event
try:
for index in range(1, count + 1):
if stop_event is not None and stop_event.is_set():
break
await channel.send(
f"ANTI-RAID DRILL — simulated spam event {index}/{count}."
)
if index < count:
await asyncio.sleep(SEND_INTERVAL_SECONDS)
except discord.Forbidden:
logger.warning("The bot cannot send messages in the configured test channel")
except discord.HTTPException:
logger.exception("Discord rejected the simulated test message")
finally:
active_task = None
stop_event = None
@bot.event
async def on_ready() -> None:
if TEST_GUILD_ID:
guild = discord.Object(id=TEST_GUILD_ID)
bot.tree.copy_global_to(guild=guild)
await bot.tree.sync(guild=guild)
else:
await bot.tree.sync()
logger.info("Logged in as %s", bot.user)
@bot.tree.command(name="spam_test", description="Run a small anti-raid spam simulation")
@app_commands.describe(count="Number of neutral test messages to send")
async def spam_test(
interaction: discord.Interaction,
count: app_commands.Range[int, 1, 10],
) -> None:
global active_task, stop_event, last_run_at
member = staff_member(interaction)
if member is None or not member.guild_permissions.manage_guild:
await interaction.response.send_message(
"Only members with Manage Server can run drills.", ephemeral=True
)
return
if count > MAX_BURST:
await interaction.response.send_message(
f"This installation allows at most {MAX_BURST} messages per drill.",
ephemeral=True,
)
return
if active_task is not None and not active_task.done():
await interaction.response.send_message(
"A drill is already running. Use /stop_test before starting another.",
ephemeral=True,
)
return
remaining = COOLDOWN_SECONDS - (time.monotonic() - last_run_at)
if remaining > 0:
await interaction.response.send_message(
f"This drill is on cooldown for {remaining:.0f} more seconds.",
ephemeral=True,
)
return
channel = await configured_test_channel()
if channel is None:
await interaction.response.send_message(
"The configured test channel was not found or is not a text channel.",
ephemeral=True,
)
return
last_run_at = time.monotonic()
stop_event = asyncio.Event()
active_task = asyncio.create_task(run_spam_simulation(channel, count))
await interaction.response.send_message(
f"Started a {count}-message drill in {channel.mention}.", ephemeral=True
)
@bot.tree.command(name="stop_test", description="Stop the active anti-raid simulation")
async def stop_test(interaction: discord.Interaction) -> None:
member = staff_member(interaction)
if member is None or not member.guild_permissions.manage_guild:
await interaction.response.send_message(
"Only members with Manage Server can stop drills.", ephemeral=True
)
return
if active_task is None or active_task.done() or stop_event is None:
await interaction.response.send_message(
"No drill is currently running.", ephemeral=True
)
return
stop_event.set()
await interaction.response.send_message("Stop requested.", ephemeral=True)
@bot.tree.error
async def on_app_command_error(
interaction: discord.Interaction, error: app_commands.AppCommandError
) -> None:
logger.exception("Application command failed", exc_info=error)
message = "The command failed. Check the bot log for details."
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=True)
bot.run(TOKEN)