mason123567890

ban kick promote infract send DMS about sever black listed and it says that if you dont leave then you will get kicked and also tickets the bot will be called Florida State Roleplay Utilities

Kodari AI
KodariAug 18 at 5:09 pm 1
FloridaStateRPUtilities
A Discord moderation and ticketing bot for Florida State Roleplay servers. Features include ban, kick, promote, and infraction management commands. Automatically sends DMs to blacklisted users warning them to leave or face a kick. Includes a full ticket system for support requests. Provides role management utilities and server moderation tools designed specifically for roleplay community operations.
  1. Create the Florida State Roleplay Utilities Discord bot with moderation and staff commands.

  2. Add blacklist DM warnings with configurable delayed kick enforcement.

  3. Add a persistent ticket panel with private ticket creation and closing.

  4. Add configuration, dependency, environment, and setup files.

Created the Florida State Roleplay Utilities Discord bot with:

  • !ban, !kick, !promote, and !infract

  • DM notifications for moderation actions

  • !blacklist warnings with delayed kick enforcement if the member does not leave

  • Persistent infraction storage

  • Private ticket panel with open/close buttons

  • Staff role and moderation log support

  • .env token configuration

  • Setup documentation and dependency files

Kodari can make mistakes. Review important code before using.
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,