aapo ekulnd

Create discord bot, where can mute players, Make the name CustomSMPBotti

Kodari AI
KodariOct 23 at 1:43 pm 1
CustomSMPBotti
A Discord moderation bot that provides mute functionality for server administrators. Features include muting members via slash commands, timed mutes with automatic unmuting, mute role management, and persistent mute tracking across restarts. Includes permission checks, audit logging, and configurable mute duration options. Built with discord.py and designed for easy integration into any server.
  1. Add main.py with /mute and /unmute slash commands for Discord server members.

  2. Add dependency and token configuration files.

  3. Brand the bot as CustomSMPBotti; its Discord application username must be set in the Developer Portal.

Created CustomSMPBotti with /mute and /unmute slash commands. These apply Discord timeouts to server members; mute durations accept formats like 10m, 2h, or 1d (up to 28 days).

Add your bot token to .env, install dependencies from requirements.txt, and grant the bot Moderate Members permission. Set its username to CustomSMPBotti in the Discord Developer Portal. This mutes Discord members, not players in Minecraft itself.

aapo ekulnd

how i test this

Kodari AI
KodariOct 23 at 1:45 pm 1

To test CustomSMPBotti in a Discord server:

  1. In the Discord Developer Portal, open your bot application, copy its bot token, and put it in .env:

    Env
    DISCORD_TOKEN=your_bot_token_here
    

    Keep the token private.

  2. Invite the bot to your server using OAuth2 with the bot and applications.commands scopes. Give it Moderate Members permission.

  3. Install the dependencies and start the bot from the project folder:

    Shell
    python -m pip install -r requirements.txt
    python main.py
    

    On Windows, you can use py instead of python.

  4. In your server, try /mute on a test member with a short duration, such as 1m, then try /unmute. Use a member whose role is below the bot’s role; Discord won’t let the bot timeout server owners or members with equal or higher roles.

Slash commands can take a little while to appear after the bot starts.

Kodari can make mistakes. Review important code before using.
Files
main.py
requirements.txt
Code
2 167
main.py
import logging
import os
import re
from datetime import datetime, timedelta, timezone

import discord
from discord import app_commands
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("CustomSMPBotti")

DURATION_PATTERN = re.compile(r"^(\d+)([mhd])$", re.IGNORECASE)
DURATION_UNITS = {
    "m": timedelta(minutes=1),
    "h": timedelta(hours=1),
    "d": timedelta(days=1),
}


def parse_duration(value: str) -> timedelta:
    match = DURATION_PATTERN.fullmatch(value.strip())
    if match is None:
        raise ValueError("Use a duration such as `10m`, `2h`, or `1d`.")

    amount = int(match.group(1))
    duration = DURATION_UNITS[match.group(2).lower()] * amount
    if duration < timedelta(minutes=1):
        raise ValueError("The mute duration must be at least 1 minute.")
    if duration > timedelta(days=28):
        raise ValueError("Discord timeouts cannot be longer than 28 days.")
    return duration


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

    async def setup_hook(self) -> None:
        await self.tree.sync()
        logger.info("Slash commands synced")


bot = CustomSMPBotti()


@bot.event
async def on_ready() -> None:
    logger.info("CustomSMPBotti connected as %s", bot.user)
    print("KODARI_READY", flush=True)


@bot.tree.command(name="mute", description="Mute a server member for a set duration")
@app_commands.default_permissions(moderate_members=True)
@app_commands.describe(
    member="The server member to mute",
    duration="Duration: for example 10m, 2h, or 1d (maximum 28d)",
    reason="Why this member is being muted",
)
async def mute(
    interaction: discord.Interaction,
    member: discord.Member,
    duration: str,
    reason: str = "No reason provided",
) -> None:
    if interaction.guild is None or not interaction.permissions.moderate_members:
        await interaction.response.send_message(
            "You need the **Moderate Members** permission to use this command.",
            ephemeral=True,
        )
        return

    try:
        timeout = parse_duration(duration)
    except ValueError as error:
        await interaction.response.send_message(str(error), ephemeral=True)
        return

    until = datetime.now(timezone.utc) + timeout
    try:
        await member.timeout(until, reason=f"{reason} — by {interaction.user}")
    except discord.Forbidden:
        await interaction.response.send_message(
            "I couldn't mute that member. Check my **Moderate Members** permission and role position.",
            ephemeral=True,
        )
        return
    except discord.HTTPException:
        logger.exception("Discord rejected a timeout for member %s", member.id)
        await interaction.response.send_message(
            "Discord couldn't apply the mute. Please try again.", ephemeral=True
        )
        return

    await interaction.response.send_message(
        f"Muted {member.mention} for **{duration.strip()}**. Reason: {reason}",
        allowed_mentions=discord.AllowedMentions.none(),
    )
    logger.info("%s muted %s in guild %s for %s", interaction.user, member, interaction.guild_id, duration)


@bot.tree.command(name="unmute", description="Remove a server member's timeout")
@app_commands.default_permissions(moderate_members=True)
@app_commands.describe(member="The server member to unmute", reason="Why the timeout is being removed")
async def unmute(
    interaction: discord.Interaction,
    member: discord.Member,
    reason: str = "No reason provided",
) -> None:
    if interaction.guild is None or not interaction.permissions.moderate_members:
        await interaction.response.send_message(
            "You need the **Moderate Members** permission to use this command.",
            ephemeral=True,
        )
        return

    try:
        await member.timeout(None, reason=f"{reason} — by {interaction.user}")
    except discord.Forbidden:
        await interaction.response.send_message(
            "I couldn't unmute that member. Check my **Moderate Members** permission and role position.",
            ephemeral=True,
        )
        return
    except discord.HTTPException:
        logger.exception("Discord rejected removing timeout for member %s", member.id)
        await interaction.response.send_message(
            "Discord couldn't remove the mute. Please try again.", ephemeral=True
        )
        return

    await interaction.response.send_message(
        f"Removed the timeout for {member.mention}. Reason: {reason}",
        allowed_mentions=discord.AllowedMentions.none(),
    )
    logger.info("%s unmuted %s in guild %s", interaction.user, member, interaction.guild_id)


@bot.tree.error
async def on_app_command_error(
    interaction: discord.Interaction,
    error: app_commands.AppCommandError,
) -> None:
    logger.error("Slash command failed", exc_info=(type(error), error, error.__traceback__))
    message = "The command failed unexpectedly. Please try again later."
    if isinstance(error, app_commands.MissingPermissions):
        message = "You need the **Moderate Members** permission to use this command."

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


token = os.getenv("DISCORD_TOKEN")
if not token:
    raise RuntimeError("DISCORD_TOKEN is missing. Add your bot token to the .env file.")

bot.run(token)