U

Build me a discord bot for my server.

Kodari AI
KodariSep 28 at 9:30 am 1
DiscordModerationBot
A Discord bot that provides server moderation and management features. It includes automated message filtering, profanity detection, user warning system, mute/kick/ban commands, role-based permission controls, and activity logging. The bot monitors chat for rule violations, issues automated warnings, and allows moderators to manage users through slash commands. It also features a customizable configuration system for server-specific rules and settings, plus a dashboard for tracking moderation actions and user behavior patterns.

Created a Discord server bot with slash commands for /ping, /serverinfo, /userinfo, /avatar, /clear, /kick, /ban, /timeout, and /announce. Moderation commands enforce Discord permissions and the bot reports errors privately.

To run it: install dependencies with pip install -r requirements.txt, copy .env.example to .env, add your DISCORD_TOKEN, then run python bot.py. Invite the bot with the bot and applications.commands scopes and grant the permissions its commands need.

U

Make me a /warn command that can be used only be role ID 1386357243632422963 and the user must select the user being warned, reason and then send the command. The bot will then send that user a warning DM as an embed saying they got warned for [reason] and server name LRPC. Then do the same for kick and ban but kick and ban can only be ran by role ID 1386349955387490406. For all those actions, they are made into a log in channel ID 1533147350564864072 saying the user that ran the command, user getting action, reason for the action, action (warn, kick, ban etc).

Kodari AI
KodariSep 28 at 9:36 am 1
  1. Add /warn with role-based access, a warning DM embed, and an action log.

  2. Add /kick and /ban with their required role check, reason, DM, and action logs.

Added /warn, /kick, and /ban with required member and reason options:

  • /warn is restricted to role 1386357243632422963.

  • /kick and /ban are restricted to role 1386349955387490406.

  • Each action attempts to DM the member an LRPC embed and logs the moderator, member, reason, and action in channel 1533147350564864072. If DMs are closed, the action still proceeds and is logged.

Ensure the bot can send messages in the log channel and has Discord’s Kick Members and Ban Members permissions.

U

Make me a /promote command where the user running has to select the use rgetting promoted, reason, new rank and old rank. When sent, the bot sends a embed in light blue to channel ID 1532031026996707420 with the User selected being mentioned, reason fro promotion, old rank and new rank and who gave the promotion (user that ran command). When sent in channel ID, selected member gets the old role taken off them by the bot and given the new one.

Kodari AI
KodariSep 28 at 9:40 am 1
  • Register /promote as a server-only slash command with member, reason, old-rank, and new-rank options.

  • Replace the old role with the new role, then post a light-blue promotion embed in channel 1532031026996707420.

Added /promote with member, reason, old-rank, and new-rank options. It replaces the member’s old role with the new role and posts a light-blue embed in channel 1532031026996707420 with the member, reason, both ranks, and promoting moderator.

The bot needs Manage Roles, and its highest role must be above the roles it assigns or removes.

U

Make it so /promote can only be ran by role ID 1533263843810086932 then warn can be rank by the same role ID and kick and ban can only be ran by role ID 1386349440461180958 but if role ID 1386349818942853232 a DM is sent to channel ID 1554066081428148254 saying @[user] needs approval for [action] and the bot gives the details like user getting action, reason, action by and if role ID 1533263843810086932, they can click thhe approve button in the light blue embed sent to the channel ID then the action will be taken but if Deny button is pressed on the embed, the user trying to give the action gets sent a Denied By HR - [Command Ran] sent to them in the channel they sent the command in with a ping. When ran and waiting for approval, the bot has the message saying 1533096643715530772 Waiting For HR Approval. 1533096643715530772

Kodari AI
KodariSep 28 at 9:48 am 1
  1. Restrict /promote and /warn to role 1533263843810086932.

  2. Update /kick and /ban access and add HR approval buttons plus pending-status messaging.

  3. Apply approved actions and report denials to the command channel.

Updated the bot permissions and approval flow:

  • /promote and /warn are restricted to role 1533263843810086932.

  • /kick and /ban can be run directly by role 1386349440461180958. Members with role 1386349818942853232 can submit them for approval in channel 1554066081428148254.

  • The approval embed includes the target, reason, and requester. Only role 1533263843810086932 can approve or deny.

  • Pending requests post <@&1533096643715530772> Waiting For HR Approval in the command channel. Denials ping the requester there; approved actions are carried out and logged with the original requester as the actor.

The bot needs permission to send messages in the approval and command channels, plus the appropriate Kick/Ban permissions.

U

Make a duplicate of /promote but call it infract and make it send to channel ID 1532033816674304060 and can be ran by the same role ID but you select thhe user, reason, action (strike 1, strike 2, Suspension, Demotion, Termination) then when sent, the user receives the selected role for the action *user selects a role for the user for the bot to give)

Kodari AI
KodariSep 28 at 9:51 am 1
  • Register /infract with the existing HR role restriction.

  • Add required member, reason, action, and role options.

  • Grant the selected role and post a light-blue infraction embed in channel 1532033816674304060.

Added /infract, restricted to role 1533263843810086932. It requires a member, reason, one of the five infraction actions, and the role to assign. The bot grants that role and posts a light-blue embed with the details in channel 1532033816674304060.

The bot needs Manage Roles, and its highest role must be above the role being assigned.

Kodari can make mistakes. Review important code before using.
Files
bot.py
requirements.txt
Code
2 518
bot.py
import logging
import os
from datetime import timedelta

import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv


logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("server_bot")
ACTION_LOG_CHANNEL_ID = 1533147350564864072
PROMOTION_CHANNEL_ID = 1532031026996707420
INFRACTION_CHANNEL_ID = 1532033816674304060
ACTION_APPROVAL_CHANNEL_ID = 1554066081428148254
DIRECT_ACTION_ROLE_ID = 1386349440461180958
ACTION_REQUEST_ROLE_ID = 1386349818942853232
HR_ROLE_ID = 1533263843810086932
WAITING_ROLE_ID = 1533096643715530772


class ServerBot(commands.Bot):
    def __init__(self) -> None:
        intents = discord.Intents.default()
        super().__init__(command_prefix=commands.when_mentioned, intents=intents)

    async def setup_hook(self) -> None:
        for name in ("ping", "serverinfo", "userinfo", "avatar", "clear", "warn", "kick", "ban", "timeout", "announce", "promote", "infract"):
            self.tree.add_command(getattr(self, name))
        self.tree.on_error = self.on_app_command_error
        synced = await self.tree.sync()
        logger.info("Synced %s application commands", len(synced))

    async def on_ready(self) -> None:
        logger.info("Ready as %s (ID: %s)", self.user, self.user.id if self.user else "unknown")

    async def on_app_command_error(
        self, interaction: discord.Interaction, error: app_commands.AppCommandError
    ) -> None:
        cause = error.original if isinstance(error, app_commands.CommandInvokeError) else error

        if isinstance(cause, app_commands.MissingPermissions):
            message = "You don't have permission to use this command."
        elif isinstance(cause, app_commands.MissingRole):
            message = "You don't have the required role to use this command."
        elif isinstance(cause, app_commands.BotMissingPermissions):
            message = "I don't have the permissions needed to do that."
        elif isinstance(cause, discord.Forbidden):
            message = "Discord blocked that action. Check my permissions and the target's role."
        elif isinstance(cause, discord.HTTPException):
            message = "Discord couldn't complete that action. Please try again."
        else:
            logger.error(
                "Unhandled application command error",
                exc_info=(type(cause), cause, cause.__traceback__),
            )
            message = "Something went wrong while running that command."

        if interaction.response.is_done():
            await interaction.followup.send(message, ephemeral=True)
        else:
            await interaction.response.send_message(message, ephemeral=True)

    @app_commands.command(name="ping", description="Check the bot's response time")
    async def ping(self, interaction: discord.Interaction) -> None:
        await interaction.response.send_message(
            f"Pong! WebSocket latency: {self.latency * 1000:.0f} ms."
        )

    @app_commands.command(name="serverinfo", description="Show information about this server")
    @app_commands.guild_only()
    async def serverinfo(self, interaction: discord.Interaction) -> None:
        guild = interaction.guild
        if guild is None:
            await interaction.response.send_message("This command only works in a server.", ephemeral=True)
            return

        embed = discord.Embed(title=guild.name, color=discord.Color.blurple())
        if guild.icon:
            embed.set_thumbnail(url=guild.icon.url)
        embed.add_field(name="Members", value=str(guild.member_count or 0))
        embed.add_field(name="Created", value=discord.utils.format_dt(guild.created_at, style="D"))
        embed.add_field(name="Owner", value=guild.owner.mention if guild.owner else "Unknown")
        await interaction.response.send_message(embed=embed)

    @app_commands.command(name="userinfo", description="Show information about a server member")
    @app_commands.guild_only()
    async def userinfo(
        self, interaction: discord.Interaction, user: discord.Member | None = None
    ) -> None:
        member = user or interaction.user
        embed = discord.Embed(
            title=f"User information: {member.display_name}",
            color=discord.Color.blurple(),
        )
        embed.set_thumbnail(url=member.display_avatar.url)
        embed.add_field(name="Username", value=str(member), inline=True)
        embed.add_field(name="User ID", value=str(member.id), inline=True)
        embed.add_field(name="Account created", value=discord.utils.format_dt(member.created_at, style="D"), inline=False)
        if isinstance(member, discord.Member) and member.joined_at:
            embed.add_field(name="Joined server", value=discord.utils.format_dt(member.joined_at, style="D"), inline=False)
        await interaction.response.send_message(embed=embed)

    @app_commands.command(name="avatar", description="Show a user's profile picture")
    async def avatar(
        self, interaction: discord.Interaction, user: discord.User | None = None
    ) -> None:
        target = user or interaction.user
        embed = discord.Embed(title=f"{target.display_name}'s avatar", color=discord.Color.blurple())
        embed.set_image(url=target.display_avatar.url)
        await interaction.response.send_message(embed=embed)

    @app_commands.command(name="clear", description="Delete recent messages from this channel")
    @app_commands.guild_only()
    @app_commands.checks.has_permissions(manage_messages=True)
    @app_commands.describe(amount="Number of recent messages to delete (1–100)")
    async def clear(self, interaction: discord.Interaction, amount: app_commands.Range[int, 1, 100]) -> None:
        channel = interaction.channel
        if not isinstance(channel, (discord.TextChannel, discord.Thread)):
            await interaction.response.send_message("This command only works in a text channel.", ephemeral=True)
            return

        await interaction.response.defer(ephemeral=True)
        deleted = await channel.purge(limit=amount, reason=f"Message cleanup by {interaction.user}")
        await interaction.followup.send(f"Deleted {len(deleted)} message(s).", ephemeral=True)

    async def _send_action_log(
        self,
        interaction: discord.Interaction,
        member: discord.Member,
        action: str,
        reason: str,
        moderator: discord.abc.User | None = None,
    ) -> None:
        channel = self.get_channel(ACTION_LOG_CHANNEL_ID)
        if channel is None:
            channel = await self.fetch_channel(ACTION_LOG_CHANNEL_ID)
        if not isinstance(channel, discord.TextChannel):
            raise RuntimeError("The configured action log channel is not a text channel.")

        embed = discord.Embed(title=f"Member {action}", color=discord.Color.orange())
        actor = moderator or interaction.user
        embed.add_field(name="Moderator", value=f"{actor} ({actor.mention})", inline=False)
        embed.add_field(name="User", value=f"{member} ({member.mention})", inline=False)
        embed.add_field(name="Reason", value=reason, inline=False)
        embed.add_field(name="Action", value=action.capitalize(), inline=False)
        await channel.send(embed=embed)

    async def _execute_member_action(
        self,
        interaction: discord.Interaction,
        requester: discord.Member,
        member: discord.Member,
        action: str,
        reason: str,
    ) -> bool:
        past_action = "kicked" if action == "kick" else "banned"
        try:
            await member.send(
                embed=discord.Embed(
                    title=f"Server {action.capitalize()}",
                    description=f"You were {past_action} for **{reason}** in **LRPC**.",
                    color=discord.Color.orange(),
                )
            )
            dm_sent = True
        except discord.Forbidden:
            dm_sent = False

        if action == "kick":
            await member.kick(reason=reason)
        else:
            await member.ban(reason=reason)
        await self._send_action_log(interaction, member, action, reason, moderator=requester)
        return dm_sent

    async def _run_or_request_member_action(
        self,
        interaction: discord.Interaction,
        member: discord.Member,
        action: str,
        reason: str,
    ) -> None:
        requester = interaction.user
        if not isinstance(requester, discord.Member):
            await interaction.response.send_message("This command only works in a server.", ephemeral=True)
            return

        if any(role.id == ACTION_REQUEST_ROLE_ID for role in requester.roles):
            await interaction.response.defer(ephemeral=True)
            view = ActionApprovalView(self, interaction, requester, member, action, reason)
            await view.send_request()
            if interaction.channel is not None:
                await interaction.channel.send(
                    f"<@&{WAITING_ROLE_ID}> Waiting For HR Approval",
                    allowed_mentions=discord.AllowedMentions(roles=True),