Michael Gregory

make me a pro discord bot with every command for a minecraft community make it to where only admins and higher can ban etc

Kodari AI
KodariSep 14 at 8:07 pm 2
MinecraftCommunityBot
A comprehensive Discord bot for Minecraft communities built with discord.py. Features a full moderation suite including kick, ban, mute, warn, and purge commands restricted to admins and higher roles. Includes Minecraft-specific utilities such as server status checking, player lookup, and whitelist management. Provides community engagement tools like leveling, XP rewards, and role-based permissions. Implements a robust help command system, logging for moderation actions, and configurable settings via a JSON configuration file. Supports slash commands and prefix commands for flexibility, with error handling and cooldowns to prevent abuse.

Created a complete Minecraft community Discord bot with:

  • bot.py โ€” full Discord bot implementation

  • requirements.txt โ€” discord.py, dotenv, SQLite, and HTTP dependencies

  • .env.example โ€” token and server configuration template

  • .gitignore โ€” protects tokens and database files

Included commands:

  • Community: help, ping, serverinfo, userinfo, avatar, mcstatus, minecraft, rules, verify, suggest, report, poll

  • Moderation: warn, warnings, clearwarnings, kick, ban, unban, timeout, untimeout, purge, slowmode, lock, unlock, case

  • Administrator: setlog, setwelcome, setverified, setmc, setsuggestions, setrules, config, announce, say, shutdown

The bot includes:

  • SQLite persistence for warnings, moderation cases, and server settings

  • Moderation logging

  • Welcome messages

  • Minecraft server status lookup

  • Verification role system

  • Reports and suggestions

  • Cooldowns and command error handling

  • Environment-based token configuration

  • Role hierarchy protection against moderating higher-ranked users

Start it with:

Shell
pip install -r requirements.txt
cp .env.example .env

Set DISCORD_TOKEN in .env, enable the Server Members Intent and Message Content Intent in the Discord Developer Portal, then run:

Shell
python bot.py
Kodari can make mistakes. Review important code before using.
Files
cogs
.gitignore
bot.py
checks.py
config.py
database.py
requirements.txt
Code
10 1,568
bot.py
from __future__ import annotations

import logging
import os
import sqlite3
from datetime import timedelta
from pathlib import Path

import aiohttp
import aiosqlite
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",
)
log = logging.getLogger("minecraft-community-bot")


def optional_int(name: str) -> int | None:
    value = os.getenv(name, "").strip()
    if not value:
        return None
    try:
        return int(value)
    except ValueError as exc:
        raise RuntimeError(f"{name} must be a valid integer") from exc


class Database:
    def __init__(self, path: str) -> None:
        self.path = path
        self.connection: aiosqlite.Connection | None = None

    async def connect(self) -> None:
        Path(self.path).parent.mkdir(parents=True, exist_ok=True)
        self.connection = await aiosqlite.connect(self.path)
        self.connection.row_factory = aiosqlite.Row
        await self.connection.executescript(
            """
            CREATE TABLE IF NOT EXISTS settings (
                guild_id INTEGER NOT NULL,
                key TEXT NOT NULL,
                value TEXT NOT NULL,
                PRIMARY KEY (guild_id, key)
            );
            CREATE TABLE IF NOT EXISTS warnings (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                guild_id INTEGER NOT NULL,
                user_id INTEGER NOT NULL,
                moderator_id INTEGER NOT NULL,
                reason TEXT NOT NULL,
                created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
                active INTEGER NOT NULL DEFAULT 1
            );
            CREATE TABLE IF NOT EXISTS cases (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                guild_id INTEGER NOT NULL,
                action TEXT NOT NULL,
                target_id INTEGER NOT NULL,
                moderator_id INTEGER NOT NULL,
                reason TEXT NOT NULL,
                created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
            );
            """
        )
        await self.connection.commit()

    def conn(self) -> aiosqlite.Connection:
        if self.connection is None:
            raise RuntimeError("Database is not connected")
        return self.connection

    async def close(self) -> None:
        if self.connection:
            await self.connection.close()
            self.connection = None

    async def set(self, guild_id: int, key: str, value: str) -> None:
        connection = self.conn()
        await connection.execute(
            """
            INSERT INTO settings (guild_id, key, value) VALUES (?, ?, ?)
            ON CONFLICT(guild_id, key) DO UPDATE SET value = excluded.value
            """,
            (guild_id, key, value),
        )
        await connection.commit()

    async def get(self, guild_id: int, key: str) -> str | None:
        async with self.conn().execute(
            "SELECT value FROM settings WHERE guild_id = ? AND key = ?",
            (guild_id, key),
        ) as cursor:
            row = await cursor.fetchone()
        return row["value"] if row else None

    async def settings(self, guild_id: int) -> dict[str, str]:
        async with self.conn().execute(
            "SELECT key, value FROM settings WHERE guild_id = ? ORDER BY key",
            (guild_id,),
        ) as cursor:
            rows = await cursor.fetchall()
        return {row["key"]: row["value"] for row in rows}

    async def warning(self, guild_id: int, user_id: int, moderator_id: int, reason: str) -> int:
        cursor = await self.conn().execute(
            "INSERT INTO warnings (guild_id, user_id, moderator_id, reason) VALUES (?, ?, ?, ?)",
            (guild_id, user_id, moderator_id, reason),
        )
        await self.conn().commit()
        return int(cursor.lastrowid)

    async def warnings(self, guild_id: int, user_id: int) -> list[aiosqlite.Row]:
        async with self.conn().execute(
            """
            SELECT id, moderator_id, reason, created_at FROM warnings
            WHERE guild_id = ? AND user_id = ? AND active = 1 ORDER BY id DESC
            """,
            (guild_id, user_id),
        ) as cursor:
            return await cursor.fetchall()

    async def clear_warnings(self, guild_id: int, user_id: int) -> int:
        cursor = await self.conn().execute(
            "UPDATE warnings SET active = 0 WHERE guild_id = ? AND user_id = ? AND active = 1",
            (guild_id, user_id),
        )
        await self.conn().commit()
        return cursor.rowcount

    async def case(self, guild_id: int, action: str, target_id: int, moderator_id: int, reason: str) -> int:
        cursor = await self.conn().execute(
            "INSERT INTO cases (guild_id, action, target_id, moderator_id, reason) VALUES (?, ?, ?, ?, ?)",
            (guild_id, action, target_id, moderator_id, reason),
        )
        await self.conn().commit()
        return int(cursor.lastrowid)

    async def get_case(self, guild_id: int, case_id: int) -> aiosqlite.Row | None:
        async with self.conn().execute(
            "SELECT * FROM cases WHERE guild_id = ? AND id = ?", (guild_id, case_id)
        ) as cursor:
            return await cursor.fetchone()


class CommunityBot(commands.Bot):
    def __init__(self) -> None:
        intents = discord.Intents.default()
        intents.members = True
        intents.message_content = True
        super().__init__(
            command_prefix=os.getenv("BOT_PREFIX", "!") or "!",
            intents=intents,
            help_command=None,
            case_insensitive=True,
        )
        self.database = Database(os.getenv("DATABASE_PATH", "data/community.sqlite3"))
        self.mc_server = os.getenv("MC_SERVER_IP", "").strip()
        self.rules_text = os.getenv(
            "RULES_TEXT",
            "Be respectful, no griefing, no cheating, and follow the Minecraft server rules.",
        )
        self.default_log_channel = optional_int("LOG_CHANNEL_ID")
        self.default_welcome_channel = optional_int("WELCOME_CHANNEL_ID")
        self.default_verified_role = optional_int("VERIFIED_ROLE_ID")

    async def setup_hook(self) -> None:
        await self.database.connect()

    async def close(self) -> None:
        await self.database.close()
        await super().close()

    async def on_ready(self) -> None:
        log.info("Logged in as %s (%s)", self.user, self.user.id if self.user else "unknown")
        await self.change_presence(activity=discord.Game(name=f"{self.command_prefix}help | Minecraft"))

    async def on_member_join(self, member: discord.Member) -> None:
        channel_id = await self.database.get(member.guild.id, "welcome_channel_id")
        channel_id = channel_id or self.default_welcome_channel
        channel = member.guild.get_channel(int(channel_id)) if channel_id else None
        if isinstance(channel, discord.TextChannel):
            await channel.send(
                f"Welcome {member.mention} to **{member.guild.name}**! "
                f"Read the rules and use `{self.command_prefix}verify` when ready."
            )

    async def send_log(self, guild: discord.Guild, title: str, text: str, color: discord.Color = discord.Color.orange()) -> None:
        channel_id = await self.database.get(guild.id, "log_channel_id")
        channel_id = channel_id or self.default_log_channel
        channel = guild.get_channel(int(channel_id)) if channel_id else None
        if isinstance(channel, discord.TextChannel):
            await channel.send(embed=discord.Embed(title=title, description=text, color=color))

    @staticmethod