42dssss

תיצור לי בוט עם anti link , clear, customer list, dmall, feedback, giveaways, status, suggestions, tickets, verify, welcome

Kodari AI
KodariAug 19 at 4:56 pm 1
ModerationSuite
Discord bot providing comprehensive server management tools. Features include anti-link protection to block malicious URLs, message clearing commands, customer list tracking, DM-all broadcasting, feedback collection, giveaway hosting, customizable status display, suggestion system, ticket support channels, user verification with role assignment, and customizable welcome messages. Built with discord.py, offering slash commands and configurable settings for server administrators.
  1. אקים בוט discord.py עם תצורה דרך .env ו־config.json.

  2. אוסיף את כל הפיצ’רים שביקשת: אנטי־לינקים, ניקוי, לקוחות, DM, פידבק, הגרלות, סטטוס, הצעות, טיקטים, אימות וברוכים הבאים.

  3. אכלול הרשאות, שמירה מקומית לקבצי JSON, טיפול בשגיאות ו־Views עם כפתורים.

נוצר בוט Discord מלא עם:

  • Anti-Link

  • clear

  • רשימת לקוחות

  • dmall

  • Feedback

  • Giveaways עם זוכים ו־reroll

  • שינוי Status

  • Suggestions

  • Tickets עם כפתורי פתיחה וסגירה

  • Verify עם תפקיד

  • Welcome messages

  • הרשאות צוות

  • שמירת נתונים בקבצי JSON

  • טיפול בשגיאות ו־cooldown ל־DMall

קבצים שנוצרו:

  • bot.py

  • config.json

  • .env.example

  • requirements.txt

הפעלה:

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

הכנס את הטוקן לקובץ .env:

Env
DISCORD_TOKEN=your_bot_token

לאחר מכן יש לעדכן ב־config.json את מזהי ערוץ הברוכים הבאים, ערוצי הפידבק וההצעות, תפקיד האימות, תפקידי הצוות וקטגוריית הטיקטים.

הרצה:

Shell
python bot.py

יש להפעיל ב־Discord Developer Portal את ה־Intents הבאים: Message Content, Server Members ו־Presence.

Kodari can make mistakes. Review important code before using.
Files
bot.py
config.json
requirements.txt
Code
3 589
bot.py
import asyncio
import json
import logging
import os
import random
import re
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
from urllib.parse import urlparse

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


load_dotenv()

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

BASE_DIR = Path(__file__).parent
DATA_DIR = BASE_DIR / "data"
CONFIG_PATH = BASE_DIR / "config.json"
DATA_DIR.mkdir(exist_ok=True)


def load_config() -> dict[str, Any]:
    defaults: dict[str, Any] = {
        "prefix": "!",
        "channels": {"welcome": 0, "feedback": 0, "suggestions": 0},
        "roles": {"verified": 0, "staff": []},
        "ticket_category_id": 0,
        "anti_link": {"enabled": True, "allowed_domains": []},
        "welcome_message": "ברוכים הבאים {member} ל־{server}!",
        "dmall_delay_seconds": 1.0,
    }
    try:
        with CONFIG_PATH.open("r", encoding="utf-8") as file:
            loaded = json.load(file)
    except (FileNotFoundError, json.JSONDecodeError):
        loaded = {}

    defaults.update(loaded)
    defaults["channels"] = {**{
        "welcome": 0,
        "feedback": 0,
        "suggestions": 0,
    }, **loaded.get("channels", {})}
    defaults["roles"] = {**{"verified": 0, "staff": []}, **loaded.get("roles", {})}
    defaults["anti_link"] = {**{
        "enabled": True,
        "allowed_domains": [],
    }, **loaded.get("anti_link", {})}
    return defaults


CONFIG = load_config()
PREFIX = str(CONFIG.get("prefix", "!"))
TOKEN = os.getenv("DISCORD_TOKEN")
URL_PATTERN = re.compile(
    r"(?i)(?:https?://|www\.)[^\s<>]+|(?:discord\.gg|discord(?:app)?\.com/invite)/[^\s<>]+"
)
DURATION_PATTERN = re.compile(r"(?i)(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$")


def read_data(filename: str, default: Any) -> Any:
    path = DATA_DIR / filename
    try:
        with path.open("r", encoding="utf-8") as file:
            return json.load(file)
    except (FileNotFoundError, json.JSONDecodeError):
        return default


def write_data(filename: str, value: Any) -> None:
    path = DATA_DIR / filename
    temporary_path = path.with_suffix(f"{path.suffix}.tmp")
    with temporary_path.open("w", encoding="utf-8") as file:
        json.dump(value, file, ensure_ascii=False, indent=2)
    temporary_path.replace(path)


def configured_channel(guild: discord.Guild, name: str) -> Optional[discord.TextChannel]:
    channel_id = int(CONFIG.get("channels", {}).get(name, 0) or 0)
    channel = guild.get_channel(channel_id) if channel_id else None
    return channel if isinstance(channel, discord.TextChannel) else None


def configured_role(guild: discord.Guild, name: str) -> Optional[discord.Role]:
    role_id = int(CONFIG.get("roles", {}).get(name, 0) or 0)
    return guild.get_role(role_id) if role_id else None


def is_staff(member: discord.Member) -> bool:
    if member.guild_permissions.administrator or member.guild_permissions.manage_guild:
        return True
    staff_ids = {int(role_id) for role_id in CONFIG.get("roles", {}).get("staff", [])}
    return any(role.id in staff_ids for role in member.roles)


def staff_only() -> commands.Check:
    async def predicate(ctx: commands.Context) -> bool:
        return isinstance(ctx.author, discord.Member) and is_staff(ctx.author)

    return commands.check(predicate)


def parse_duration(value: str) -> Optional[int]:
    match = DURATION_PATTERN.fullmatch(value.strip())
    if not match or not any(match.groups()):
        return None
    weeks, days, hours, minutes, seconds = (int(part or 0) for part in match.groups())
    total = weeks * 604800 + days * 86400 + hours * 3600 + minutes * 60 + seconds
    return total if total > 0 else None


def contains_blocked_link(content: str) -> bool:
    allowed = {
        domain.lower().removeprefix("www.")
        for domain in CONFIG.get("anti_link", {}).get("allowed_domains", [])
    }
    for match in URL_PATTERN.findall(content):
        url = match if "://" in match else f"https://{match}"
        hostname = (urlparse(url).hostname or "").lower().removeprefix("www.")
        if not any(hostname == domain or hostname.endswith(f".{domain}") for domain in allowed):
            return True
    return False


def make_embed(title: str, description: str, color: discord.Color = discord.Color.blurple()) -> discord.Embed:
    embed = discord.Embed(title=title, description=description, color=color, timestamp=datetime.now(timezone.utc))
    return embed


class KodariBot(commands.Bot):
    def __init__(self) -> None:
        intents = discord.Intents.default()
        intents.guilds = True
        intents.members = True
        intents.messages = True
        intents.message_content = True
        intents.reactions = True
        super().__init__(command_prefix=PREFIX, intents=intents, help_command=None)
        self.ready_announced = False

    async def setup_hook(self) -> None:
        self.add_view(VerifyView())
        self.add_view(TicketCreateView())
        self.add_view(TicketView())
        self.giveaway_loop.start()

    @tasks.loop(seconds=15)
    async def giveaway_loop(self) -> None:
        giveaways = read_data("giveaways.json", [])
        changed = False
        now = datetime.now(timezone.utc).timestamp()
        for giveaway in giveaways:
            if giveaway.get("ended") or float(giveaway.get("ends_at", 0)) > now:
                continue
            await finish_giveaway(self, giveaway)
            changed = True
        if changed:
            write_data("giveaways.json", giveaways)

    @giveaway_loop.before_loop
    async def before_giveaway_loop(self) -> None:
        await self.wait_until_ready()

    async def on_ready(self) -> None:
        if not self.ready_announced:
            logger.info("Logged in as %s (%s)", self.user, self.user.id if self.user else "unknown")
            self.ready_announced = True


bot = KodariBot()


class VerifyView(discord.ui.View):
    def __init__(self) -> None:
        super().__init__(timeout=None)

    @discord.ui.button(label="אימות", emoji="✅", style=discord.ButtonStyle.success, custom_id="kodari:verify")
    async def verify(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
        if not interaction.guild or not isinstance(interaction.user, discord.Member):
            await interaction.response.send_message("הכפתור זמין רק בתוך שרת.", ephemeral=True)
            return
        role = configured_role(interaction.guild, "verified")
        if not role:
            await interaction.response.send_message("תפקיד האימות עדיין לא הוגדר.", ephemeral=True)
            return
        if role in interaction.user.roles:
            await interaction.response.send_message("אתה כבר מאומת.", ephemeral=True)
            return
        try:
            await interaction.user.add_roles(role, reason="Verification button")
        except discord.Forbidden: