Create a complete, deploy-ready Python Discord bot for the user's Ametis SMP support server. Use discord.py (if needed, declare external dependencies in this project's existing dependency/manifest mechanism; do not run builds). The project is currently empty. Implement the following requirements, preserving ordinary conversation and avoiding moderation of the bot's own messages:

1) Branding: bot should use the name/presence text “Ametis SMP Destek” where programmatically possible. Discord bot username/avatar cannot be recolored by code, so use a purple (#8A2BE2) embed color for help/info and support replies. Include README steps telling the user to set the bot's Discord username to Ametis SMP Destek in the Developer Portal if desired, invite it with Message Content Intent, View Channels, Send Messages, Embed Links, Manage Messages, and Moderate Members permissions, and enable Message Content Intent. Do not pretend code can change the Discord profile username color. 2) Info auto-replies: when a human message asks about “sürüm” / “versiyon”, reply that Ametis SMP runs Minecraft 1.21 (e.g. “Ametis SMP sürümü: 1.21”). When they ask for “ip”, reply “cairo-truman.tun.ply.gg”. Match IP as a standalone word/request (not the substring in arbitrary words); keep regular chat unaffected. Use Turkish messages and purple embeds if appropriate. 3) Profanity moderation: delete a message containing a configured Turkish profanity word, issue a clear, polite warning (“Küfür etme lütfen. Son 5 uyarı ...” wording), count each violating message per guild/user, and on the 5th profanity offense apply a 20-minute Discord timeout. Tell them about the timeout. Maintain counts reliably (SQLite is preferred) and reset the relevant counter after a successfully applied threshold timeout. Include a maintainable profanity word list/config and use word-boundary matching to reduce false positives. 4) @everyone moderation: detect actual @everyone mass mentions (not plain quoted text if it can be distinguished); delete the offending message, warn the member and count violations per guild/user. On their 3rd offense, apply a 20-minute timeout (duration was unspecified; choose 20 minutes as a sensible default), clearly notifying them. Reset this counter after successful timeout. Do not punish server moderators/admins; make exemptions sensible for members with Manage Messages or Moderate Members / Administrator. 5) Advertisement moderation: detect URLs/domains in user messages (notably .com; include common domains like .net/.org/.gg/.io and URL schemes), delete the message, and timeout the author for 5 hours; send a brief Turkish notice. Apply moderator/admin exemptions. Ensure bot's own IP response does not get moderated. 6) Keep all other normal chat untouched. Handle missing permissions/API failures gracefully by logging and informing moderators if possible; bot must not crash. Keep secrets out of source: read DISCORD_TOKEN from environment. Add clear README startup/deploy and configuration instructions. Ensure an entrypoint and dependency declarations fit the generated Python Discord bot project conventions. Make warning/count logic understandable and avoid multiple duplicate punishments for one message.

Implement the files directly. Do not build or claim compile/test verification.

Kodari AI
KodariOct 16 at 4:33 pm 2
AmetisSmpDestekBot
A Turkish Discord support bot for Ametis SMP that provides automatic info replies about Minecraft version 1.21 and server IP, moderates profanity with word-boundary detection and timeout escalation, handles @everyone mass mentions with violation counting, and blocks advertisement URLs with extended timeouts. Uses SQLite for persistent violation tracking, purple embeds for branding, moderator/admin exemptions, and graceful error handling. Reads DISCORD_TOKEN from environment variables with comprehensive README deployment instructions.
  1. Create the bot entry point with info replies, SQLite-backed warnings, and single-pass moderation.

  2. Add dependencies, editable profanity/mod-log configuration, and deployment instructions.

Created the deploy-ready bot with bot.py, requirements.txt, editable profanity and moderation-log settings in config.json, and setup instructions in README.md.

To receive messages, enable Message Content Intent in the Discord Developer Portal under Bot → Privileged Gateway Intents. Add your token to .env (copy .env.example), install dependencies with python -m pip install -r requirements.txt, then start with python bot.py. No tests or builds were run.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
config.json
README.md
requirements.txt
Code
5 462
bot.py
import json
import logging
import os
import re
import sqlite3
from datetime import timedelta
from pathlib import Path

import discord
from dotenv import load_dotenv


BASE_DIR = Path(__file__).resolve().parent
BRAND_NAME = "Ametis SMP Destek"
PURPLE = discord.Color(0x8A2BE2)
DATABASE_PATH = BASE_DIR / "warnings.sqlite3"
CONFIG_PATH = BASE_DIR / "config.json"

DEFAULT_PROFANITY_WORDS = [
    "amk",
    "aq",
    "orospu",
    "sik",
    "siktir",
    "piç",
    "yarrak",
    "göt",
    "ananı",
    "pezevenk",
    "kahpe",
]

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("ametis_smp_bot")


def load_config():
    try:
        with CONFIG_PATH.open(encoding="utf-8") as config_file:
            config = json.load(config_file)
        if not isinstance(config, dict):
            raise ValueError("config.json must contain a JSON object")
    except FileNotFoundError:
        logger.warning("config.json not found; using built-in defaults")
        config = {}
    except (OSError, json.JSONDecodeError, ValueError):
        logger.exception("Could not read config.json; using built-in defaults")
        config = {}

    configured_words = config.get("profanity_words", DEFAULT_PROFANITY_WORDS)
    if not isinstance(configured_words, list):
        logger.warning("profanity_words must be a JSON list; using built-in defaults")
        configured_words = DEFAULT_PROFANITY_WORDS
    profanity_words = [
        word.strip()
        for word in configured_words
        if isinstance(word, str) and word.strip()
    ]

    raw_log_channel_id = config.get("moderation_log_channel_id")
    try:
        log_channel_id = int(raw_log_channel_id) if raw_log_channel_id else None
    except (TypeError, ValueError):
        logger.warning("moderation_log_channel_id must be a channel ID or null")
        log_channel_id = None

    return profanity_words, log_channel_id


PROFANITY_WORDS, MODERATION_LOG_CHANNEL_ID = load_config()
PROFANITY_PATTERN = (
    re.compile(
        r"(?<!\w)(?:"
        + "|".join(re.escape(word) for word in PROFANITY_WORDS)
        + r")(?!\w)",
        re.IGNORECASE,
    )
    if PROFANITY_WORDS
    else None
)
VERSION_PATTERN = re.compile(r"(?<!\w)(?:sürüm|versiyon)(?!\w)", re.IGNORECASE)
IP_PATTERN = re.compile(r"(?<!\w)ip(?!\w)", re.IGNORECASE)
ACTUAL_EVERYONE_PATTERN = re.compile(r"(?<!\w)@everyone(?!\w)", re.IGNORECASE)
URL_PATTERN = re.compile(
    r"(?:\b(?:https?|ftp)://[^\s<>()]+"
    r"|\bwww\.[^\s<>()]+"
    r"|(?<![\w@])(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}\b(?:/[^\s<>()]*)?)",
    re.IGNORECASE,
)


class ViolationStore:
    def __init__(self, database_path):
        self.connection = sqlite3.connect(database_path)
        self.connection.execute(
            """
            CREATE TABLE IF NOT EXISTS violations (
                guild_id TEXT NOT NULL,
                user_id TEXT NOT NULL,
                kind TEXT NOT NULL,
                count INTEGER NOT NULL DEFAULT 0,
                PRIMARY KEY (guild_id, user_id, kind)
            )
            """
        )
        self.connection.commit()

    def increment(self, guild_id, user_id, kind):
        with self.connection:
            self.connection.execute(
                """
                INSERT INTO violations (guild_id, user_id, kind, count)
                VALUES (?, ?, ?, 1)
                ON CONFLICT (guild_id, user_id, kind)
                DO UPDATE SET count = count + 1
                """,
                (str(guild_id), str(user_id), kind),
            )
            row = self.connection.execute(
                "SELECT count FROM violations WHERE guild_id = ? AND user_id = ? AND kind = ?",
                (str(guild_id), str(user_id), kind),
            ).fetchone()
        return row[0]

    def reset(self, guild_id, user_id, kind):
        with self.connection:
            self.connection.execute(
                "DELETE FROM violations WHERE guild_id = ? AND user_id = ? AND kind = ?",
                (str(guild_id), str(user_id), kind),
            )


violation_store = ViolationStore(DATABASE_PATH)


async def report_moderators(guild, details):
    if MODERATION_LOG_CHANNEL_ID is None:
        logger.warning("Moderator notification (no log channel configured): %s", details)
        return

    try:
        channel = guild.get_channel(MODERATION_LOG_CHANNEL_ID)
        if channel is None:
            channel = await guild.fetch_channel(MODERATION_LOG_CHANNEL_ID)
        if not hasattr(channel, "send"):
            logger.warning("Configured moderation log channel cannot send messages")
            return
        embed = discord.Embed(
            title=f"{BRAND_NAME} — Moderasyon bildirimi",
            description=details,
            color=PURPLE,
        )
        await channel.send(embed=embed, allowed_mentions=discord.AllowedMentions.none())
    except discord.HTTPException:
        logger.exception("Could not send a moderation notification to the log channel")


async def delete_offending_message(message, reason):
    try:
        await message.delete()
    except discord.HTTPException:
        logger.exception(
            "Could not delete message %s in guild %s",
            message.id,
            message.guild.id,
        )
        await report_moderators(
            message.guild,
            f"{reason}: {message.author} kullanıcısının mesajı silinemedi. "
            "Botta Manage Messages iznini ve kanal erişimini kontrol edin.",
        )


async def apply_timeout(member, duration, reason):
    try:
        await member.timeout(duration, reason=f"Ametis SMP: {reason}")
        return True
    except discord.HTTPException:
        logger.exception(
            "Could not timeout user %s in guild %s",
            member.id,
            member.guild.id,
        )
        await report_moderators(
            member.guild,
            f"{member} kullanıcısına timeout uygulanamadı ({reason}). "
            "Botta Moderate Members iznini ve rol hiyerarşisini kontrol edin.",
        )
        return False


async def send_user_notice(channel, description, guild=None):
    embed = discord.Embed(
        title=BRAND_NAME,
        description=description,
        color=PURPLE,
    )