melvin_2021

make an discord bot that can do a welcomer bot , also status , ban , kick , timeout , and also status , timeout , ban , kick , welcomer setup can only be used by admins

Kodari AI
KodariThu at 7:41 pm 2
ModerationSuite
A Discord moderation bot built with discord.py featuring a customizable welcomer system, server status display, and moderation commands including ban, kick, and timeout. Admin-only setup commands configure welcome messages and channel targeting. The bot tracks member join events to send personalized greetings, provides real-time server statistics, and enforces moderation actions with proper permission checks. Includes error handling, logging, and a command prefix system for intuitive user interaction.
  • Add admin-only slash commands for moderation, bot status, and welcome setup.

  • Save welcome settings and send a message when a member joins.

Created the welcomer and admin-only moderation commands.

  • Set DISCORD_TOKEN in .env.

  • Enable Server Members Intent in the Discord Developer Portal under Bot → Privileged Gateway Intents.

  • Use /welcome_setup to choose a welcome channel and message.

Kodari can make mistakes. Review important code before using.
Files
bot.py
requirements.txt
Code
2 198
bot.py
import asyncio
import json
import logging
import os
from datetime import timedelta
from pathlib import Path

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

load_dotenv()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("welcomer")

CONFIG_PATH = Path("config.json")
intents = discord.Intents.default()
intents.members = True


class WelcomerBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix="!", intents=intents)
        self.welcome_settings = {}

    async def setup_hook(self):
        if CONFIG_PATH.exists():
            try:
                self.welcome_settings = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
                if not isinstance(self.welcome_settings, dict):
                    raise ValueError("Configuration must be an object")
            except (OSError, ValueError) as exc:
                raise RuntimeError("Could not load config.json") from exc
        await self.tree.sync()

    async def on_ready(self):
        logger.info("Logged in as %s", self.user)
        print("KODARI_READY", flush=True)

    async def on_member_join(self, member: discord.Member):
        settings = self.welcome_settings.get(str(member.guild.id))
        if not settings:
            return
        channel = member.guild.get_channel(settings["channel_id"])
        if not isinstance(channel, discord.TextChannel):
            logger.warning("Welcome channel unavailable in guild %s", member.guild.id)
            return
        message = settings.get("message", "Welcome {member} to {server}!")
        message = message.replace("{member}", member.mention).replace("{server}", member.guild.name)
        try:
            await channel.send(message, allowed_mentions=discord.AllowedMentions(users=[member], roles=False, everyone=False))
        except discord.HTTPException:
            logger.exception("Could not send welcome message in guild %s", member.guild.id)


bot = WelcomerBot()


@bot.tree.command(name="welcome_setup", description="Set the welcome channel and message")
@app_commands.guild_only()
@app_commands.default_permissions(administrator=True)
@app_commands.checks.has_permissions(administrator=True)
@app_commands.checks.cooldown(1, 5.0, key=lambda i: (i.guild_id, i.user.id))
@app_commands.describe(channel="Channel for welcome messages", message="Use {member} and {server} in your message")
async def welcome_setup(interaction: discord.Interaction, channel: discord.TextChannel, message: app_commands.Range[str, 1, 1800] = "Welcome {member} to {server}!"):
    settings = dict(bot.welcome_settings)
    settings[str(interaction.guild_id)] = {"channel_id": channel.id, "message": message}
    try:
        CONFIG_PATH.write_text(json.dumps(settings, indent=2), encoding="utf-8")
    except OSError:
        logger.exception("Could not save welcome settings")
        await interaction.response.send_message("Could not save welcome settings.", ephemeral=True)
        return
    bot.welcome_settings = settings
    await interaction.response.send_message(f"Welcome messages are configured for {channel.mention}.", ephemeral=True)


@bot.tree.command(name="welcome_disable", description="Disable welcome messages")
@app_commands.guild_only()
@app_commands.default_permissions(administrator=True)
@app_commands.checks.has_permissions(administrator=True)
@app_commands.checks.cooldown(1, 5.0, key=lambda i: (i.guild_id, i.user.id))
async def welcome_disable(interaction: discord.Interaction):
    settings = dict(bot.welcome_settings)
    settings.pop(str(interaction.guild_id), None)
    try:
        CONFIG_PATH.write_text(json.dumps(settings, indent=2), encoding="utf-8")
    except OSError:
        logger.exception("Could not save welcome settings")
        await interaction.response.send_message("Could not save welcome settings.", ephemeral=True)
        return
    bot.welcome_settings = settings
    await interaction.response.send_message("Welcome messages are disabled.", ephemeral=True)


@bot.tree.command(name="status", description="Set the bot's activity and online status")
@app_commands.guild_only()
@app_commands.default_permissions(administrator=True)
@app_commands.checks.has_permissions(administrator=True)
@app_commands.checks.cooldown(1, 10.0, key=lambda i: i.user.id)
@app_commands.choices(availability=[
    app_commands.Choice(name="Online", value="online"),
    app_commands.Choice(name="Idle", value="idle"),
    app_commands.Choice(name="Do not disturb", value="dnd"),
    app_commands.Choice(name="Invisible", value="invisible"),
])
async def status(interaction: discord.Interaction, activity: app_commands.Range[str, 1, 128], availability: app_commands.Choice[str] = None):
    selected = availability.value if availability else "online"
    await bot.change_presence(status=getattr(discord.Status, selected), activity=discord.Game(name=activity))
    await interaction.response.send_message(f"Bot status set to {selected} with activity: {activity}", ephemeral=True)


async def check_target(interaction: discord.Interaction, member: discord.Member) -> bool:
    guild = interaction.guild
    if member.id == guild.owner_id or member.id == interaction.user.id or member.id == bot.user.id:
        await interaction.response.send_message("You cannot moderate that member.", ephemeral=True)
        return False
    if interaction.user.id != guild.owner_id and member.top_role >= interaction.user.top_role:
        await interaction.response.send_message("That member's highest role must be below yours.", ephemeral=True)
        return False
    if guild.me is None or member.top_role >= guild.me.top_role:
        await interaction.response.send_message("My highest role must be above that member's role.", ephemeral=True)
        return False
    return True


@bot.tree.command(name="ban", description="Ban a member from this server")
@app_commands.guild_only()
@app_commands.default_permissions(administrator=True)
@app_commands.checks.has_permissions(administrator=True)
@app_commands.checks.bot_has_permissions(ban_members=True)
@app_commands.checks.cooldown(1, 3.0, key=lambda i: (i.guild_id, i.user.id))
async def ban(interaction: discord.Interaction, member: discord.Member, reason: app_commands.Range[str, 1, 400] = "No reason provided"):
    if not await check_target(interaction, member):
        return
    await member.ban(reason=f"{interaction.user} ({interaction.user.id}): {reason}")
    await interaction.response.send_message(f"Banned {discord.utils.escape_markdown(str(member))}. Reason: {discord.utils.escape_markdown(reason)}", allowed_mentions=discord.AllowedMentions.none())


@bot.tree.command(name="kick", description="Kick a member from this server")
@app_commands.guild_only()
@app_commands.default_permissions(administrator=True)
@app_commands.checks.has_permissions(administrator=True)
@app_commands.checks.bot_has_permissions(kick_members=True)
@app_commands.checks.cooldown(1, 3.0, key=lambda i: (i.guild_id, i.user.id))
async def kick(interaction: discord.Interaction, member: discord.Member, reason: app_commands.Range[str, 1, 400] = "No reason provided"):
    if not await check_target(interaction, member):
        return
    await member.kick(reason=f"{interaction.user} ({interaction.user.id}): {reason}")
    await interaction.response.send_message(f"Kicked {discord.utils.escape_markdown(str(member))}. Reason: {discord.utils.escape_markdown(reason)}", allowed_mentions=discord.AllowedMentions.none())


@bot.tree.command(name="timeout", description="Timeout a member for up to 28 days")
@app_commands.guild_only()
@app_commands.default_permissions(administrator=True)
@app_commands.checks.has_permissions(administrator=True)
@app_commands.checks.bot_has_permissions(moderate_members=True)
@app_commands.checks.cooldown(1, 3.0, key=lambda i: (i.guild_id, i.user.id))
@app_commands.describe(minutes="Timeout duration in minutes (1 to 40320)")
async def timeout(interaction: discord.Interaction, member: discord.Member, minutes: app_commands.Range[int, 1, 40320], reason: app_commands.Range[str, 1, 400] = "No reason provided"):
    if not await check_target(interaction, member):
        return
    await member.timeout(timedelta(minutes=minutes), reason=f"{interaction.user} ({interaction.user.id}): {reason}")
    await interaction.response.send_message(f"Timed out {discord.utils.escape_markdown(str(member))} for {minutes} minutes. Reason: {discord.utils.escape_markdown(reason)}", allowed_mentions=discord.AllowedMentions.none())


@bot.tree.error
async def command_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
    if isinstance(error, app_commands.MissingPermissions):
        message = "Only server administrators can use this command."
    elif isinstance(error, app_commands.BotMissingPermissions):
        message = "I don't have the permissions needed to do that."
    elif isinstance(error, app_commands.CommandOnCooldown):
        message = f"Please wait {error.retry_after:.1f} seconds before trying again."
    elif isinstance(getattr(error, "original", None), discord.Forbidden):
        message = "Discord denied that action. Check my permissions and role position."
    else:
        logger.error("Command failed", exc_info=(type(error), error, error.__traceback__))
        message = "The command failed. Please try again later."
    if interaction.response.is_done():
        await interaction.followup.send(message, ephemeral=True)
    else:
        await interaction.response.send_message(message, ephemeral=True)


async def main():
    token = os.getenv("DISCORD_TOKEN")
    if not token or token == "your_discord_bot_token_here":
        raise RuntimeError("Set DISCORD_TOKEN in .env before starting the bot")
    async with bot:
        await bot.start(token)


if __name__ == "__main__":
    asyncio.run(main())