EBLSO 2

make me a discord bot modertion working 24/7 and arabic and fancy

Kodari AI
KodariSep 20 at 7:00 pm 1
ArabicModerationBot
A 24/7 Discord moderation bot built with discord.py that supports Arabic language commands. Features include automatic message filtering, profanity detection, warn/kick/ban/mute systems, role management, logging of moderation actions, and scheduled uptime monitoring. The bot uses slash commands and prefix commands in Arabic, with configurable punishment thresholds, auto-moderation for spam and links, and a persistent database for warnings and infractions. Includes an anti-raid system, slowmode management, and a dashboard-style log channel for transparent moderation history.
  1. إنشاء بوت Discord يعمل بـ discord.py مع إعادة اتصال تلقائية وتهيئة آمنة من .env.

  2. إضافة أوامر إشراف عربية وفاخرة: حظر، طرد، كتم، تحذير، عرض التحذيرات، تنظيف، قفل/فتح القنوات، وتسجيل الإجراءات.

  3. إضافة قاعدة SQLite لحفظ التحذيرات وإعدادات سجل الإدارة، مع فحص الصلاحيات والرتب ومحددات استخدام.

  4. إضافة ملفات التشغيل والتثبيت والتوثيق.

تم إنشاء بوت Discord عربي وفاخر للإشراف، ويشمل:

  • أوامر Slash تحت /mod

  • حظر وطرد وكتم الأعضاء

  • نظام تحذيرات محفوظ في SQLite

  • عرض سجل تحذيرات الأعضاء

  • حذف الرسائل

  • قفل وفتح القنوات

  • سجل إداري قابل للتخصيص

  • حماية من استهداف الرتب الأعلى أو البوت نفسه

  • فحص الصلاحيات ومحددات الاستخدام

  • Embeds عربية بتصميم احترافي

  • إعادة اتصال تلقائية عند انقطاع Discord

  • إعدادات آمنة باستخدام .env

الملفات الرئيسية:

  • bot.py

  • requirements.txt

  • .env.example

  • .gitignore

  • README.md

للتشغيل:

Shell
python -m pip install -r requirements.txt
cp .env.example .env
python bot.py

ضع توكن البوت داخل .env:

Env
DISCORD_TOKEN=توكن_البوت

للتشغيل 24/7 فعلياً، شغّله على VPS أو خدمة استضافة دائمة مع مدير عمليات مثل systemd أو Docker.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 452
bot.py
import asyncio
import datetime as dt
import logging
import os
import sqlite3
from pathlib import Path
from typing import Optional

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


load_dotenv()

TOKEN = os.getenv("DISCORD_TOKEN")
if not TOKEN:
    raise RuntimeError("ضع DISCORD_TOKEN في ملف .env قبل تشغيل البوت")

DATA_DIR = Path("data")
DATA_DIR.mkdir(exist_ok=True)

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("arabic-moderation")


class ModerationDatabase:
    def __init__(self, path: Path):
        self.connection = sqlite3.connect(path, check_same_thread=False)
        self.connection.row_factory = sqlite3.Row
        self.connection.execute("PRAGMA journal_mode=WAL")
        self.connection.execute(
            """
            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
            )
            """
        )
        self.connection.execute(
            """
            CREATE TABLE IF NOT EXISTS guild_settings (
                guild_id INTEGER PRIMARY KEY,
                log_channel_id INTEGER
            )
            """
        )
        self.connection.commit()

    def add_warning(self, guild_id: int, user_id: int, moderator_id: int, reason: str) -> int:
        cursor = self.connection.execute(
            """
            INSERT INTO warnings (guild_id, user_id, moderator_id, reason, created_at)
            VALUES (?, ?, ?, ?, ?)
            """,
            (guild_id, user_id, moderator_id, reason, dt.datetime.now(dt.timezone.utc).isoformat()),
        )
        self.connection.commit()
        return int(cursor.lastrowid)

    def get_warnings(self, guild_id: int, user_id: int) -> list[sqlite3.Row]:
        return list(
            self.connection.execute(
                "SELECT * FROM warnings WHERE guild_id = ? AND user_id = ? ORDER BY id DESC",
                (guild_id, user_id),
            )
        )

    def get_log_channel(self, guild_id: int) -> Optional[int]:
        row = self.connection.execute(
            "SELECT log_channel_id FROM guild_settings WHERE guild_id = ?", (guild_id,)
        ).fetchone()
        return int(row["log_channel_id"]) if row and row["log_channel_id"] else None

    def set_log_channel(self, guild_id: int, channel_id: int) -> None:
        self.connection.execute(
            """
            INSERT INTO guild_settings (guild_id, log_channel_id) VALUES (?, ?)
            ON CONFLICT(guild_id) DO UPDATE SET log_channel_id = excluded.log_channel_id
            """,
            (guild_id, channel_id),
        )
        self.connection.commit()

    def close(self) -> None:
        self.connection.close()


class ModerationBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.guilds = True
        intents.members = True
        self.database = ModerationDatabase(DATA_DIR / "moderation.sqlite3")
        super().__init__(
            command_prefix=commands.when_mentioned,
            intents=intents,
            help_command=None,
            allowed_mentions=discord.AllowedMentions.none(),
        )

    async def setup_hook(self) -> None:
        await self.tree.sync()
        logger.info("تمت مزامنة أوامر السلاش")

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


bot = ModerationBot()
mod_group = app_commands.Group(name="mod", description="أدوات الإشراف والحماية")
bot.tree.add_command(mod_group)


def make_embed(
    title: str,
    description: str,
    color: discord.Colour = discord.Colour.blurple(),
) -> discord.Embed:
    embed = discord.Embed(title=title, description=description, colour=color, timestamp=dt.datetime.now(dt.timezone.utc))
    embed.set_footer(text="🛡️ Kodari Security • نظام الإشراف العربي")
    return embed


def reason_text(reason: str) -> str:
    return reason.strip() or "بدون سبب محدد"


def can_moderate(interaction: discord.Interaction, target: discord.Member) -> tuple[bool, str]:
    guild = interaction.guild
    moderator = interaction.user
    me = guild.me if guild else None
    if not guild or not isinstance(moderator, discord.Member) or not me:
        return False, "هذا الأمر متاح داخل السيرفر فقط."
    if target.id == moderator.id:
        return False, "لا يمكنك تطبيق الإجراء على نفسك."
    if target.id == guild.owner_id:
        return False, "لا يمكن تطبيق الإجراء على مالك السيرفر."
    if target.id == me.id:
        return False, "لا يمكنني تطبيق الإجراء على نفسي."
    if target.top_role >= me.top_role:
        return False, "رتبة العضو أعلى من رتبتي أو مساوية لها."
    if target.top_role >= moderator.top_role and moderator.id != guild.owner_id:
        return False, "رتبة العضو أعلى من رتبتك أو مساوية لها."
    return True, ""


async def send_log(guild: discord.Guild, embed: discord.Embed) -> None:
    channel_id = bot.database.get_log_channel(guild.id)
    if not channel_id:
        return
    channel = guild.get_channel(channel_id)
    if isinstance(channel, discord.TextChannel):
        try:
            await channel.send(embed=embed)
        except discord.HTTPException:
            logger.warning("تعذر إرسال سجل الإدارة إلى %s", channel_id)


async def reject_target(interaction: discord.Interaction, target: discord.Member) -> bool:
    allowed, message = can_moderate(interaction, target)
    if not allowed:
        await interaction.response.send_message(
            embed=make_embed("🚫 لا يمكن تنفيذ الإجراء", message, discord.Colour.red()),
            ephemeral=True,
        )
        return True
    return False


@bot.event
async def on_ready() -> None:
    if bot.user:
        logger.info("البوت متصل: %s (%s)", bot.user, bot.user.id)


@bot.event
async def on_disconnect() -> None:
    logger.warning("انقطع الاتصال مؤقتاً، ستتم إعادة المحاولة تلقائياً")


@mod_group.command(name="help", description="عرض دليل أوامر الإشراف بالعربية")
@app_commands.guild_only()
async def mod_help(interaction: discord.Interaction) -> None:
    embed = make_embed(
        "✨ مركز قيادة الإشراف",
        "استخدم الأوامر التالية لإدارة السيرفر بأمان:",
        discord.Colour.from_rgb(88, 101, 242),
    )
    embed.add_field(name="🔨 الإدارة", value="`/mod ban` • `/mod kick` • `/mod timeout`\n`/mod warn` • `/mod warnings`", inline=False)
    embed.add_field(name="🧹 القنوات", value="`/mod clear` • `/mod lock` • `/mod unlock`", inline=False)