Files
.gitignore
database.py
main.py
README.md
requirements.txt
Code
5 683
main.py
from __future__ import annotations
import logging
import os
from datetime import datetime, timedelta, timezone
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
from database import Database
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("national_highways")
async def respond(
interaction: discord.Interaction,
content: str | None = None,
embed: discord.Embed | None = None,
) -> None:
payload: dict[str, object] = {"content": content, "embed": embed, "ephemeral": True}
if interaction.response.is_done():
await interaction.followup.send(**payload)
else:
await interaction.response.send_message(**payload)
def guild_from(interaction: discord.Interaction) -> discord.Guild | None:
return interaction.guild
def can_act_on_member(interaction: discord.Interaction, member: discord.Member) -> str | None:
guild = guild_from(interaction)
actor = interaction.user
if guild is None or not isinstance(actor, discord.Member):
return "This command can only be used inside a server."
if member == actor:
return "You cannot use this action on yourself."
if member == guild.owner:
return "The server owner cannot be targeted by this bot."
if actor.id != guild.owner_id and member.top_role >= actor.top_role:
return "You can only target members below your highest role."
if guild.me is None or member.top_role >= guild.me.top_role:
return "That member is at or above the bot's highest role."
return None
def can_manage_role(interaction: discord.Interaction, role: discord.Role) -> str | None:
guild = guild_from(interaction)
actor = interaction.user
if guild is None or not isinstance(actor, discord.Member):
return "This command can only be used inside a server."
if role.is_default() or role.managed:
return "That role cannot be assigned by the bot."
if actor.id != guild.owner_id and role >= actor.top_role:
return "You can only manage roles below your highest role."
if guild.me is None or role >= guild.me.top_role:
return "That role must be below the bot's highest role."
return None
@app_commands.checks.has_permissions(ban_members=True)
@app_commands.checks.cooldown(1, 5.0, key=lambda interaction: (interaction.guild_id, interaction.user.id))
@app_commands.guild_only()
async def ban_member(
interaction: discord.Interaction,
member: discord.Member,
reason: str = "No reason provided",
) -> None:
problem = can_act_on_member(interaction, member)
if problem:
await respond(interaction, problem)
return
guild = interaction.guild
assert guild is not None
try:
await guild.ban(member, reason=f"Ban by {interaction.user}: {reason}")
except discord.HTTPException:
logger.exception("Failed to ban member %s in guild %s", member.id, guild.id)
await respond(interaction, "Discord rejected the ban. Check the bot's permissions and role hierarchy.")
return
await respond(interaction, f"Banned {member.mention}. Reason: {reason}")
@app_commands.checks.has_permissions(kick_members=True)
@app_commands.checks.cooldown(1, 5.0, key=lambda interaction: (interaction.guild_id, interaction.user.id))
@app_commands.guild_only()
async def kick_member(
interaction: discord.Interaction,
member: discord.Member,
reason: str = "No reason provided",
) -> None:
problem = can_act_on_member(interaction, member)
if problem:
await respond(interaction, problem)
return
guild = interaction.guild
assert guild is not None
try:
await member.kick(reason=f"Kick by {interaction.user}: {reason}")
except discord.HTTPException:
logger.exception("Failed to kick member %s in guild %s", member.id, guild.id)
await respond(interaction, "Discord rejected the kick. Check the bot's permissions and role hierarchy.")
return
await respond(interaction, f"Kicked {member.mention}. Reason: {reason}")
@app_commands.checks.has_permissions(moderate_members=True)
@app_commands.checks.cooldown(1, 5.0, key=lambda interaction: (interaction.guild_id, interaction.user.id))
@app_commands.guild_only()
@app_commands.describe(duration_minutes="Timeout length in minutes, from 1 to 40320")
async def timeout_member(
interaction: discord.Interaction,
member: discord.Member,
duration_minutes: app_commands.Range[int, 1, 40320],
reason: str = "No reason provided",
) -> None:
problem = can_act_on_member(interaction, member)
if problem:
await respond(interaction, problem)
return
guild = interaction.guild
assert guild is not None
until = discord.utils.utcnow() + timedelta(minutes=duration_minutes)
try:
await member.timeout(until, reason=f"Timeout by {interaction.user}: {reason}")
except discord.HTTPException:
logger.exception("Failed to timeout member %s in guild %s", member.id, guild.id)
await respond(interaction, "Discord rejected the timeout. Check the bot's permissions and role hierarchy.")
return
await respond(
interaction,
f"Timed out {member.mention} for {duration_minutes} minutes. Reason: {reason}",
)
ban_command = app_commands.Command(name="ban", description="Ban a member from the server", callback=ban_member)
kick_command = app_commands.Command(name="kick", description="Kick a member from the server", callback=kick_member)
timeout_command = app_commands.Command(
name="timeout",
description="Timeout a member",
callback=timeout_member,
)
def moderation_embed(title: str, color: discord.Color) -> discord.Embed:
embed = discord.Embed(title=title, color=color, timestamp=datetime.now(timezone.utc))
embed.set_footer(text="National Highways Department")
return embed
class InfractionGroup(app_commands.Group):
def __init__(self, database: Database) -> None:
super().__init__(name="infraction", description="Manage department infractions")
self.database = database
@app_commands.command(name="issue", description="Issue an infraction to a member")
@app_commands.guild_only()
@app_commands.checks.has_permissions(manage_messages=True)
@app_commands.checks.cooldown(1, 5.0, key=lambda interaction: (interaction.guild_id, interaction.user.id))
@app_commands.describe(
member="The member receiving the infraction",
infraction_type="The type of infraction",
severity="The severity of the infraction",
reason="Why the infraction is being issued",
)
@app_commands.choices(
infraction_type=[
app_commands.Choice(name="Policy Violation", value="Policy Violation"),
app_commands.Choice(name="Conduct", value="Conduct"),
app_commands.Choice(name="Attendance", value="Attendance"),
app_commands.Choice(name="Other", value="Other"),
],
severity=[
app_commands.Choice(name="Warning", value="Warning"),
app_commands.Choice(name="Written Warning", value="Written Warning"),
app_commands.Choice(name="Final Warning", value="Final Warning"),
],
)
async def issue(
self,
interaction: discord.Interaction,
member: discord.Member,
infraction_type: app_commands.Choice[str],
severity: app_commands.Choice[str],
reason: str,
) -> None:
problem = can_act_on_member(interaction, member)
if problem:
await respond(interaction, problem)
return
guild = interaction.guild
assert guild is not None
infraction_id = self.database.create_infraction(