Files
data
.gitignore
bot.py
config.json
README.md
requirements.txt
Code
6 613
bot.py
import asyncio
import json
import logging
import os
import re
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
import discord
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("fsrp-utilities")
CONFIG_PATH = Path("config.json")
INFRACTIONS_PATH = Path("data/infractions.json")
def load_config() -> dict:
with CONFIG_PATH.open("r", encoding="utf-8") as file:
return json.load(file)
config = load_config()
prefix = config.get("prefix", "!")
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(
command_prefix=prefix,
intents=intents,
case_insensitive=True,
help_command=None,
)
blacklist_tasks: dict[tuple[int, int], asyncio.Task] = {}
def load_infractions() -> dict:
INFRACTIONS_PATH.parent.mkdir(parents=True, exist_ok=True)
if not INFRACTIONS_PATH.exists():
INFRACTIONS_PATH.write_text("{}", encoding="utf-8")
return {}
try:
with INFRACTIONS_PATH.open("r", encoding="utf-8") as file:
return json.load(file)
except (json.JSONDecodeError, OSError):
logger.warning("Could not read the infraction database; starting empty.")
return {}
infractions = load_infractions()
def configured_channel(guild: discord.Guild, key: str) -> Optional[discord.TextChannel]:
channel_id = int(config.get(key, 0) or 0)
channel = guild.get_channel(channel_id)
return channel if isinstance(channel, discord.TextChannel) else None
def configured_role(guild: discord.Guild, key: str) -> Optional[discord.Role]:
role_id = int(config.get(key, 0) or 0)
return guild.get_role(role_id) if role_id else None
def reason_text(reason: str) -> str:
return reason.strip() or "No reason provided"
async def safe_dm(user: discord.User | discord.Member, message: str) -> bool:
try:
await user.send(message)
return True
except (discord.Forbidden, discord.HTTPException):
return False
async def log_action(
guild: discord.Guild,
title: str,
description: str,
color: discord.Color = discord.Color.blurple(),
) -> None:
channel = configured_channel(guild, "moderation_log_channel_id")
if channel is None:
return
embed = discord.Embed(
title=title,
description=description,
color=color,
timestamp=datetime.now(timezone.utc),
)
embed.set_footer(text="Florida State Roleplay Utilities")
try:
await channel.send(embed=embed)
except discord.HTTPException:
logger.exception("Failed to send an audit log in %s", guild.id)
def can_act_on(ctx: commands.Context, member: discord.Member) -> Optional[str]:
if member == ctx.author:
return "You cannot use this command on yourself."
if member == ctx.guild.me:
return "I cannot use a moderation command on myself."
if member.top_role >= ctx.guild.me.top_role:
return "That member's highest role is above or equal to my highest role."
if member.top_role >= ctx.author.top_role and ctx.author != ctx.guild.owner:
return "That member's highest role is above or equal to your highest role."
return None
async def blacklist_enforcement(
guild_id: int,
member_id: int,
reason: str,
moderator_id: int,
) -> None:
grace_seconds = max(1, int(config.get("blacklist_grace_seconds", 600)))
await asyncio.sleep(grace_seconds)
guild = bot.get_guild(guild_id)
if guild is None:
return
member = guild.get_member(member_id)
if member is None:
return
try:
await member.kick(reason=f"Server blacklist enforcement: {reason}")
await log_action(
guild,
"Blacklisted member kicked",
f"**Member:** {member} (`{member.id}`)\n"
f"**Moderator:** <@{moderator_id}>\n**Reason:** {reason}",
discord.Color.red(),
)
except discord.Forbidden:
logger.warning("Could not kick blacklisted member %s in %s", member_id, guild_id)
finally:
blacklist_tasks.pop((guild_id, member_id), None)
class TicketPanelView(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout=None)
@discord.ui.button(
label="Open a ticket",
style=discord.ButtonStyle.primary,
emoji="๐ซ",
custom_id="fsrp:open_ticket",
)
async def open_ticket(
self,
interaction: discord.Interaction,
button: discord.ui.Button,
) -> None:
if interaction.guild is None or not isinstance(interaction.user, discord.Member):
await interaction.response.send_message(
"Tickets can only be opened inside the server.", ephemeral=True
)
return
guild = interaction.guild
member = interaction.user
existing = discord.utils.find(
lambda channel: isinstance(channel, discord.TextChannel)
and channel.topic == f"ticket_owner={member.id}",
guild.text_channels,
)
if existing is not None:
await interaction.response.send_message(
f"You already have an open ticket: {existing.mention}", ephemeral=True
)
return
category_id = int(config.get("ticket_category_id", 0) or 0)
category = guild.get_channel(category_id) if category_id else None
if category is not None and not isinstance(category, discord.CategoryChannel):
category = None
support_role = configured_role(guild, "staff_role_id")
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
member: discord.PermissionOverwrite(
view_channel=True,
send_messages=True,