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,
)