ash.ley.cosplay

make me a diverse moderation and welcome bot

Kodari AI
KodariAug 24 at 2:14 pm 1
DiverseModWelcomeBot
A Discord bot providing diverse moderation tools and welcome features. It includes automated moderation commands for managing members, filtering inappropriate content, and handling spam. The bot also offers customizable welcome messages for new members, role-based permissions, and logging capabilities. It supports multiple server configurations and provides an easy-to-use interface for server administrators to manage community guidelines and member interactions efficiently.
  1. Core bot: secure environment loading, persistent guild settings, logging, and unified error handling.

  2. Moderation: warnings, kick/ban, timeout, purge, slowmode, channel locking, and mod-log configuration.

  3. Welcome: configurable welcome messages, join handling, testing, and automatic roles.

  4. Setup: dependencies, environment template, and command documentation.

Created a complete discord.py moderation and welcome bot with:

  • Persistent JSON storage for settings and warnings

  • Warning history and warning clearing

  • Kick, ban, unban, timeout, and untimeout commands

  • Message purge and slowmode controls

  • Channel lock/unlock commands

  • Configurable moderation log channel

  • Welcome messages with {member}, {username}, {server}, and {count} placeholders

  • Configurable automatic welcome roles

  • Slash and ! prefix command support

  • Permission checks and centralized error handling

  • .env.example, requirements.txt, and setup documentation

Start it with:

Shell
cp .env.example .env
# Add your Discord token to .env
pip install -r requirements.txt
python bot.py
Kodari can make mistakes. Review important code before using.
Files
cogs
bot.py
README.md
requirements.txt
storage.py
utils.py
welcomer
Code
9 657
bot.py
import logging
import os

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

from storage import GuildStore
from utils import reply


load_dotenv()

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("kodari-bot")


class ModerationBot(commands.Bot):
    def __init__(self) -> None:
        intents = discord.Intents.default()
        intents.members = True
        intents.message_content = True

        super().__init__(
            command_prefix=commands.when_mentioned_or("!"),
            intents=intents,
            help_command=None,
        )
        self.store = GuildStore(os.getenv("DATA_FILE", "data/guilds.json"))

    async def setup_hook(self) -> None:
        await self.load_extension("cogs.moderation")
        await self.load_extension("cogs.welcome")
        synced = await self.tree.sync()
        logger.info("Synced %d application commands", len(synced))

    async def on_ready(self) -> None:
        if self.user is not None:
            logger.info("Logged in as %s (%s)", self.user, self.user.id)

    async def on_command_error(
        self, ctx: commands.Context, error: commands.CommandError
    ) -> None:
        if hasattr(ctx.command, "on_error"):
            return

        error = getattr(error, "original", error)
        if isinstance(error, commands.CommandNotFound):
            return
        if isinstance(error, commands.MissingPermissions):
            message = "You do not have permission to use that command."
        elif isinstance(error, commands.BotMissingPermissions):
            message = "I am missing these permissions: " + ", ".join(error.missing_permissions)
        elif isinstance(error, commands.MissingRequiredArgument):
            message = f"Missing argument: `{error.param.name}`. Use `/help` for examples."
        elif isinstance(error, commands.BadArgument):
            message = "One of the supplied arguments is invalid. Use `/help` for examples."
        elif isinstance(error, commands.NoPrivateMessage):
            message = "That command can only be used inside a server."
        else:
            logger.exception("Unhandled command error", exc_info=error)
            message = "Something went wrong while running that command."

        await reply(ctx, message, ephemeral=True)


bot = ModerationBot()


@bot.hybrid_command(name="help", description="Show moderation and welcome commands.")
async def help_command(ctx: commands.Context) -> None:
    embed = discord.Embed(
        title="Moderation Bot Help",
        description="Commands can be used as slash commands or with the `!` prefix.",
        color=discord.Color.blurple(),
    )
    embed.add_field(
        name="Moderation",
        value=(
            "`warn`, `warnings`, `clearwarnings`, `kick`, `ban`, `unban`, "
            "`timeout`, `untimeout`, `clear`, `slowmode`, `lock`, `unlock`, `setmodlog`"
        ),
        inline=False,
    )
    embed.add_field(
        name="Welcome",
        value="`welcome set`, `welcome disable`, `welcome test`, `welcome autorole set`, `welcome autorole disable`",
        inline=False,
    )
    embed.set_footer(text="Duration examples: 30m, 2h, 7d")
    await reply(ctx, embed=embed)


def main() -> None:
    token = os.getenv("DISCORD_TOKEN")
    if not token or token == "replace_with_your_bot_token":
        raise RuntimeError("Set DISCORD_TOKEN in your .env file before starting the bot.")
    bot.run(token, log_handler=None)


if __name__ == "__main__":
    main()