Files
bot.py
requirements.txt
Code
2 419
bot.py
import logging
import os
import re
import sqlite3
from datetime import timedelta
import discord
from discord.ext import commands
from dotenv import load_dotenv
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
log = logging.getLogger("moderation-bot")
load_dotenv()
def parse_duration(value: str) -> timedelta:
match = re.fullmatch(r"\s*(\d+)\s*([smhd])\s*", value.lower())
if not match:
raise commands.BadArgument("Use a duration such as `30s`, `10m`, `2h`, or `7d`.")
amount = int(match.group(1))
units = {"s": 1, "m": 60, "h": 3600, "d": 86400}
seconds = amount * units[match.group(2)]
if amount < 1 or seconds > 28 * 86400:
raise commands.BadArgument("Duration must be greater than zero and no longer than 28 days.")
return timedelta(seconds=seconds)
class ModerationBot(commands.Bot):
async def setup_hook(self) -> None:
await self.add_cog(ModerationCog(self))
synced = await self.tree.sync()
log.info("Synced %s application commands", len(synced))
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = ModerationBot(command_prefix=commands.when_mentioned_or("!"), intents=intents)
class ModerationCog(commands.Cog):
def __init__(self, client: ModerationBot):
self.bot = client
self.db = sqlite3.connect("moderation.db")
self.db.execute(
"CREATE TABLE IF NOT EXISTS warnings "
"(id INTEGER PRIMARY KEY AUTOINCREMENT, guild_id INTEGER NOT NULL, "
"user_id INTEGER NOT NULL, moderator_id INTEGER NOT NULL, reason TEXT NOT NULL, "
"created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)"
)
self.db.commit()
def cog_unload(self) -> None:
self.db.close()
async def manageable(self, ctx: commands.Context, member: discord.Member) -> bool:
if member.id == ctx.author.id:
await ctx.send("You can’t moderate yourself.")
return False
if member.id == ctx.guild.owner_id:
await ctx.send("The server owner can’t be moderated by a bot command.")
return False
if member.top_role >= ctx.author.top_role and ctx.author.id != ctx.guild.owner_id:
await ctx.send("That member’s highest role is equal to or above yours.")
return False
if member.top_role >= ctx.guild.me.top_role:
await ctx.send("That member’s highest role is equal to or above the bot’s.")
return False
return True
@commands.hybrid_command(name="ban", description="Ban a member from this server.")
@commands.guild_only()
@commands.has_guild_permissions(ban_members=True)
@commands.bot_has_guild_permissions(ban_members=True)
async def ban(self, ctx: commands.Context, member: discord.Member, *, reason: str = "No reason provided"):
if not await self.manageable(ctx, member):
return
await member.ban(reason=f"{ctx.author} ({ctx.author.id}): {reason}", delete_message_seconds=0)
await ctx.send(f"Banned **{member}**. Reason: {reason}")
@commands.hybrid_command(name="unban", description="Unban a user by ID.")
@commands.guild_only()
@commands.has_guild_permissions(ban_members=True)
@commands.bot_has_guild_permissions(ban_members=True)
async def unban(self, ctx: commands.Context, user_id: str, *, reason: str = "No reason provided"):
try:
target_id = int(user_id)
except ValueError as exc:
raise commands.BadArgument("Provide a valid numeric user ID.") from exc
user = await self.bot.fetch_user(target_id)
await ctx.guild.unban(user, reason=f"{ctx.author} ({ctx.author.id}): {reason}")
await ctx.send(f"Unbanned **{user}**. Reason: {reason}")
@commands.hybrid_command(name="kick", description="Kick a member from this server.")
@commands.guild_only()
@commands.has_guild_permissions(kick_members=True)
@commands.bot_has_guild_permissions(kick_members=True)
async def kick(self, ctx: commands.Context, member: discord.Member, *, reason: str = "No reason provided"):
if not await self.manageable(ctx, member):
return
await member.kick(reason=f"{ctx.author} ({ctx.author.id}): {reason}")
await ctx.send(f"Kicked **{member}**. Reason: {reason}")
@commands.hybrid_command(name="softban", description="Ban and immediately unban a member to clear recent messages.")
@commands.guild_only()
@commands.has_guild_permissions(ban_members=True)
@commands.bot_has_guild_permissions(ban_members=True)
async def softban(self, ctx: commands.Context, member: discord.Member, *, reason: str = "No reason provided"):
if not await self.manageable(ctx, member):
return
audit_reason = f"Softban by {ctx.author} ({ctx.author.id}): {reason}"
await member.ban(reason=audit_reason, delete_message_seconds=604800)
await ctx.guild.unban(member, reason=audit_reason)
await ctx.send(f"Softbanned **{member}** (banned and unbanned; recent messages cleared).")
@commands.hybrid_command(name="timeout", description="Timeout a member for a duration like 10m or 2h.")
@commands.guild_only()
@commands.has_guild_permissions(moderate_members=True)
@commands.bot_has_guild_permissions(moderate_members=True)
async def timeout(self, ctx: commands.Context, member: discord.Member, duration: str, *, reason: str = "No reason provided"):
if not await self.manageable(ctx, member):
return
until = discord.utils.utcnow() + parse_duration(duration)
await member.timeout(until, reason=f"{ctx.author} ({ctx.author.id}): {reason}")
await ctx.send(f"Timed out **{member}** until {discord.utils.format_dt(until, style='R')}. Reason: {reason}")
@commands.hybrid_command(name="untimeout", description="Remove a member’s timeout.")
@commands.guild_only()
@commands.has_guild_permissions(moderate_members=True)
@commands.bot_has_guild_permissions(moderate_members=True)
async def untimeout(self, ctx: commands.Context, member: discord.Member, *, reason: str = "No reason provided"):
if not await self.manageable(ctx, member):
return
await member.timeout(None, reason=f"{ctx.author} ({ctx.author.id}): {reason}")
await ctx.send(f"Removed timeout from **{member}**. Reason: {reason}")
@commands.hybrid_command(name="warn", description="Record a warning for a member.")
@commands.guild_only()
@commands.has_guild_permissions(moderate_members=True)
async def warn(self, ctx: commands.Context, member: discord.Member, *, reason: str = "No reason provided"):
if not await self.manageable(ctx, member):
return
cursor = self.db.execute(
"INSERT INTO warnings (guild_id, user_id, moderator_id, reason) VALUES (?, ?, ?, ?)",
(ctx.guild.id, member.id, ctx.author.id, reason),
)
self.db.commit()
await ctx.send(f"Warned **{member}** (warning #{cursor.lastrowid}). Reason: {reason}")
@commands.hybrid_command(name="warnings", description="Show a member’s recent warnings.")
@commands.guild_only()
@commands.has_guild_permissions(moderate_members=True)
async def warnings(self, ctx: commands.Context, member: discord.Member):
rows = self.db.execute(
"SELECT id, moderator_id, reason, created_at FROM warnings "
"WHERE guild_id = ? AND user_id = ? ORDER BY id DESC LIMIT 10",
(ctx.guild.id, member.id),
).fetchall()
if not rows:
await ctx.send(f"**{member}** has no recorded warnings.")
return
embed = discord.Embed(title=f"Warnings for {member}", color=discord.Color.orange())
for warning_id, moderator_id, reason, created_at in rows:
embed.add_field(
name=f"Warning #{warning_id} · {created_at} UTC",
value=f"Moderator: <@{moderator_id}>\nReason: {reason}",
inline=False,
)
await ctx.send(embed=embed)
@commands.hybrid_command(name="clearwarnings", description="Clear all recorded warnings for a member.")
@commands.guild_only()
@commands.has_guild_permissions(moderate_members=True)
async def clearwarnings(self, ctx: commands.Context, member: discord.Member):
cursor = self.db.execute(
"DELETE FROM warnings WHERE guild_id = ? AND user_id = ?",
(ctx.guild.id, member.id),
)
self.db.commit()
await ctx.send(f"Cleared **{cursor.rowcount}** warning(s) for **{member}**.")
@commands.hybrid_command(name="purge", description="Delete a number of recent messages.")
@commands.guild_only()
@commands.has_guild_permissions(manage_messages=True)
@commands.bot_has_guild_permissions(manage_messages=True, read_message_history=True)
async def purge(self, ctx: commands.Context, amount: int):
if not 1 <= amount <= 500:
await ctx.send("Amount must be between 1 and 500.")
return
deleted = await ctx.channel.purge(limit=amount)
await ctx.send(f"Deleted {len(deleted)} message(s).", delete_after=5)
@commands.hybrid_command(name="purgeuser", description="Delete recent messages from one member.")
@commands.guild_only()
@commands.has_guild_permissions(manage_messages=True)
@commands.bot_has_guild_permissions(manage_messages=True, read_message_history=True)