k74ey

Create a complete Discord moderation bot in Python using discord.py.

Use ONLY prefix commands with +. No slash commands.

Commands: +ban ID [reason] +unban ID +kick ID [reason] +warn ID [reason] +warnings ID +mute ID [duration] +unmute ID +clear number +blacklist ID [reason] +unblacklist ID +blacklistlist +unbanall +unbanallblacklist +giveaway +end ID +reroll ID +help +ping +userinfo ID +serverinfo +lock +unlock

Add:

* Full moderation logs. * Ticket/channel message transcripts. * SQLite database for warnings, blacklist and giveaways. * Permission and error handling. * Users are always targeted by Discord ID, never mentions. * Use DISCORD_TOKEN for the bot token. * Make it suitable for 24/7 hosting and automatic restart.

Generate all required files and fully working code. No TODOs or pseudocode.

📎 1 file 34 chars
📄
DISCORD_TOKEN.md
md 5 lines
▶
```
DISCORD_TOKEN=

```
Kodari AI
KodariSep 7 at 4:17 pm 2
ModerationMaster
A comprehensive Discord moderation bot built with discord.py, using prefix commands only. Features include ban, kick, warn, mute, clear, blacklist, giveaway management, and channel locking. It maintains SQLite databases for warnings, blacklists, and giveaways, generates full moderation logs, and provides ticket/channel message transcripts. Users are targeted by ID, with robust permission and error handling, designed for 24/7 hosting with automatic restart capability.

Created a complete prefix-only Discord moderation bot with:

  • All requested moderation, blacklist, giveaway, utility, and channel-lock commands

  • Numeric Discord ID targeting only

  • SQLite persistence for warnings, blacklist entries, giveaways, and ticket transcripts

  • Moderation logs and deleted/edited message logging

  • Automatic blacklist enforcement

  • Giveaway recovery across restarts

  • Permission, hierarchy, cooldown, and command error handling

  • Docker deployment with automatic restart

  • .env configuration support and token protection

  • Setup documentation and dependency files

Before starting, copy .env.example to .env, set DISCORD_TOKEN, configure the log channel IDs, and enable Message Content and Server Members intents in the Discord Developer Portal.

Because the token was included in the prompt, rotate it in the Discord Developer Portal before production use.

k74ey

tu veux le id du log salon?

Kodari AI
KodariSep 7 at 4:18 pm 1

Oui. Envoie-moi l’ID du salon où tu veux recevoir les logs de modération.

Si tu veux des salons séparés, envoie aussi :

  • ID du salon des logs de modération

  • ID du salon des transcripts de tickets

  • ID du salon des giveaways, si différent

Ne m’envoie jamais le token du bot.

k74ey

1529994863226130452

Kodari AI
KodariSep 7 at 4:23 pm 1

L’ID 1529994863226130452 est configuré pour :

  • les logs de modération ;

  • les transcripts.

Il faut maintenant créer un fichier .env à partir de .env.example et y mettre ton token :

Env
DISCORD_TOKEN=ton_nouveau_token
MOD_LOG_CHANNEL_ID=1529994863226130452
TRANSCRIPT_LOG_CHANNEL_ID=1529994863226130452

⚠️ Le token envoyé précédemment est exposé publiquement : régénère-le dans le portail Discord Developer avant de lancer le bot.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
docker-compose.yml
Dockerfile
README.md
requirements.txt
run.sh
Code
7 905
bot.py
from __future__ import annotations

import io
import json
import logging
import os
import random
import re
import time
from datetime import timedelta
from typing import Any

import aiosqlite
import discord
from discord.ext import commands, tasks
from dotenv import load_dotenv


load_dotenv()

logging.basicConfig(
    level=os.getenv("LOG_LEVEL", "INFO").upper(),
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("moderation_bot")

TOKEN = os.getenv("DISCORD_TOKEN")
if not TOKEN:
    raise RuntimeError("DISCORD_TOKEN is not set. Put it in a .env file.")

PREFIX = "+"
DATABASE_PATH = os.getenv("DATABASE_PATH", "data/bot.sqlite3")
MOD_LOG_CHANNEL_ID = int(os.getenv("MOD_LOG_CHANNEL_ID", "0"))
TRANSCRIPT_LOG_CHANNEL_ID = int(
    os.getenv("TRANSCRIPT_LOG_CHANNEL_ID", str(MOD_LOG_CHANNEL_ID))
)


class Database:
    def __init__(self, path: str):
        self.path = path

    async def initialize(self) -> None:
        directory = os.path.dirname(self.path)
        if directory:
            os.makedirs(directory, exist_ok=True)
        async with aiosqlite.connect(self.path) as db:
            await db.executescript(
                """
                PRAGMA journal_mode = WAL;
                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 INTEGER NOT NULL
                );
                CREATE TABLE IF NOT EXISTS blacklist (
                    guild_id INTEGER NOT NULL,
                    user_id INTEGER NOT NULL,
                    reason TEXT NOT NULL,
                    created_at INTEGER NOT NULL,
                    PRIMARY KEY (guild_id, user_id)
                );
                CREATE TABLE IF NOT EXISTS giveaways (
                    message_id INTEGER PRIMARY KEY,
                    guild_id INTEGER NOT NULL,
                    channel_id INTEGER NOT NULL,
                    host_id INTEGER NOT NULL,
                    prize TEXT NOT NULL,
                    winner_count INTEGER NOT NULL,
                    end_time INTEGER NOT NULL,
                    ended INTEGER NOT NULL DEFAULT 0,
                    winners_json TEXT NOT NULL DEFAULT '[]'
                );
                CREATE TABLE IF NOT EXISTS transcript_messages (
                    message_id INTEGER PRIMARY KEY,
                    channel_id INTEGER NOT NULL,
                    guild_id INTEGER NOT NULL,
                    author_id INTEGER NOT NULL,
                    author_name TEXT NOT NULL,
                    content TEXT NOT NULL,
                    created_at INTEGER NOT NULL
                );
                CREATE INDEX IF NOT EXISTS idx_warnings_user
                    ON warnings (guild_id, user_id);
                CREATE INDEX IF NOT EXISTS idx_transcripts_channel
                    ON transcript_messages (channel_id, created_at);
                """
            )
            await db.commit()

    async def execute(self, query: str, parameters: tuple[Any, ...] = ()) -> None:
        async with aiosqlite.connect(self.path) as db:
            await db.execute(query, parameters)
            await db.commit()

    async def fetchone(
        self, query: str, parameters: tuple[Any, ...] = ()
    ) -> aiosqlite.Row | None:
        async with aiosqlite.connect(self.path) as db:
            db.row_factory = aiosqlite.Row
            cursor = await db.execute(query, parameters)
            return await cursor.fetchone()

    async def fetchall(
        self, query: str, parameters: tuple[Any, ...] = ()
    ) -> list[aiosqlite.Row]:
        async with aiosqlite.connect(self.path) as db:
            db.row_factory = aiosqlite.Row
            cursor = await db.execute(query, parameters)
            return await cursor.fetchall()

    async def add_warning(
        self, guild_id: int, user_id: int, moderator_id: int, reason: str
    ) -> None:
        await self.execute(
            "INSERT INTO warnings (guild_id, user_id, moderator_id, reason, created_at) "
            "VALUES (?, ?, ?, ?, ?)",
            (guild_id, user_id, moderator_id, reason, int(time.time())),
        )

    async def get_warnings(self, guild_id: int, user_id: int) -> list[aiosqlite.Row]:
        return await self.fetchall(
            "SELECT * FROM warnings WHERE guild_id = ? AND user_id = ? "
            "ORDER BY created_at DESC",
            (guild_id, user_id),
        )

    async def set_blacklist(self, guild_id: int, user_id: int, reason: str) -> None:
        await self.execute(
            "INSERT INTO blacklist (guild_id, user_id, reason, created_at) VALUES (?, ?, ?, ?) "
            "ON CONFLICT(guild_id, user_id) DO UPDATE SET reason = excluded.reason, "
            "created_at = excluded.created_at",
            (guild_id, user_id, reason, int(time.time())),
        )

    async def remove_blacklist(self, guild_id: int, user_id: int) -> None:
        await self.execute(
            "DELETE FROM blacklist WHERE guild_id = ? AND user_id = ?",
            (guild_id, user_id),
        )

    async def is_blacklisted(self, guild_id: int, user_id: int) -> bool:
        row = await self.fetchone(
            "SELECT 1 FROM blacklist WHERE guild_id = ? AND user_id = ?",
            (guild_id, user_id),
        )
        return row is not None

    async def get_blacklist(self, guild_id: int) -> list[aiosqlite.Row]:
        return await self.fetchall(
            "SELECT * FROM blacklist WHERE guild_id = ? ORDER BY created_at DESC",
            (guild_id,),
        )

    async def create_giveaway(
        self,
        message_id: int,
        guild_id: int,
        channel_id: int,
        host_id: int,
        prize: str,
        winner_count: int,
        end_time: int,
    ) -> None:
        await self.execute(
            "INSERT INTO giveaways "
            "(message_id, guild_id, channel_id, host_id, prize, winner_count, end_time) "
            "VALUES (?, ?, ?, ?, ?, ?, ?)",
            (
                message_id,
                guild_id,
                channel_id,
                host_id,
                prize,
                winner_count,
                end_time,
            ),
        )

    async def get_giveaway(self, message_id: int) -> aiosqlite.Row | None:
        return await self.fetchone(
            "SELECT * FROM giveaways WHERE message_id = ?", (message_id,)
        )

    async def get_due_giveaways(self, now: int) -> list[aiosqlite.Row]:
        return await self.fetchall(
            "SELECT * FROM giveaways WHERE ended = 0 AND end_time <= ?", (now,)
        )

    async def finish_giveaway(self, message_id: int, winner_ids: list[int]) -> None:
        await self.execute(
            "UPDATE giveaways SET ended = 1, winners_json = ? WHERE message_id = ?",
            (json.dumps(winner_ids), message_id),
        )

    async def set_giveaway_winners(
        self, message_id: int, winner_ids: list[int]