_o1c
📎 1 file 3,066 chars
📄
pasted-code-1785963381514.txt
txt 113 lines
▶
ابي بوت ديسكورد



ابي لما اسوي امر او كوماند 
/set-orders 
يرسل embed في نفس الchannel ويكون في الرساله select menu يطلع خيارات
🛒 | Plugins
🛒 | Skripts
🛒 | Hubs
🛒 | Spawns
🛒 | Kits
🛒 | Maps
🛒 | Others

وإذا حددت على وحده يخليني اكتب رساله في الروم لمده 30 ثانيه واذا ارسلت رساله معينه يكتب البوت 
✅ Sent Successfully 

و شي مهم الرساله يصير لها لوق في روم 1534648140114956438

ويصير للرساله إيدي معين مكون من ثلاثه ارقام (لا تنسى بشرح لك إياها الحين) مثال 
User: {user}
Message: {message}
ID: 719

==============================

لما ارسل رساله تروح للروم بالأيدي حقها
ونقول ذي الرساله فيها صوره .png وكلام الخ 
ينسخ البوت الرساله ذي ويرسلها للخيار (الرساله حقت /set-orders)

(معلومه ابي بنفس الرساله) في السطر الي قبل الاخير 
<:tada:1271874203125022870> **Customers**: {Customers}
بعدين بشرحه! (طبعا {Customers} يكون العدد صفر 0)



🛒 | Plugins = 1395736987377598515
🛒 | Skripts = 1395736998634979480
🛒 | Hubs = 1395736999817777192
🛒 | Spawns = 1395737000522547322
🛒 | Kits = 1395737002510520320
🛒 | Maps = 1395737004557467679
🛒 | Others = 1395737006134530118

يرسل البوت نفس الرساله لكن على الرساله في الروم الثاني وبرضو يكون فيها أزرار select menu لما يضغط على الselect menu يطلع له خياريين 

‏<:shopIcon:1271874292480479293> للشراء
<:staff_icon:1272131230766202901> للاستفسار

إذا ضغط على للشراء 
يفتح له زي تكت يروح يفتح له روم في category 

1395736966011686945

ويكون في embed :
**الزبون {user} تم فتح تذكره شراء عبر المنتج:**

 ويرسل الكلام حق السلعه الي محددها او الرساله المنتج الي فتح به تذكره في الembed ولو كان في الرساله صوره يرسلها برضو 
(ويكون في خيار 🔒 Close بلون الفضي إذا ضغط عليه ينتظر خمسه ثواني ثم يسكر التكت "يحذف الروم") وتجي الرساله للوق 1395737007572910174
===========================
يرسل رساله عاديه البوت في التذكره حقت الشخص 

**في حال تريد المزيد من الاستفسار يرجئ اشعار الاداره وانتظار الرد**!
**في حال تريد الشراء مباشره فيرجئ التحويل لـ المستخدم**:

<:Rajhi:1272588221720821831> راجحي:
آيبان: `SA05 8000 0859 6080 1084 9705`
تفاصيل السعر: في المنتج!
عند الانتهاء يرجئ ارسال **الإيصال** وانتظار الاداره!

<:shop:1271874261707133000> كردت برو بوت:
تفاصيل السعر: في المنتج!
المستخدم: <@850445105630150677> 

============================

واذا كتبت 
!Done {id}
يرسل الملف حق المنتج في نفس الchannel يعني كيف؟

لما اكتب امر
/file-id {id} {file}

تذكر يوم قلت لك id الرساله الي تروح للوق؟ احط الأيدي حقها والملف في الامر ويسجل تطابق للملف في المنتج في حالت كتبت 
!Done {id}
للادمن استريتور طبعا فقط adminstator

وتذكر يوم قلت لك 
{Customers}
يضيف فيها واحد إذا كتبت ويعدل الرساله 
!Done {id}
حق الرساله
زي

‏<:tada:1271874203125022870> **Customers**: 1

(ابي لما اكتب !Done برضو يجيه رتبه <@&1395736786319446092> )

واذا فتح للاستفسار في المنتج يفتح له تكت في كاتجوري 1395736965042802721

ويكون في embed :
**الزبون {user} تم فتح تذكره استفسار عبر المنتج:**

 ويرسل الكلام حق السلعه الي محددها او الرساله المنتج الي فتح به تذكره في الembed ولو كان في الرساله صوره يرسلها برضو 
(ويكون في خيار 🔒 Close بلون الفضي إذا ضغط عليه ينتظر خمسه ثواني ثم يسكر التكت "يحذف الروم") وتجي الرساله للوق 1395737007572910174






Kodari AI
KodariAug 5 at 8:58 pm 2
DiscordOrderSystem
A Discord bot for managing product orders via slash commands. Users run /set-orders to receive an embed with a select menu of product categories (Plugins, Skripts, Hubs, Spawns, Kits, Maps, Others). Selecting a category prompts the user to send a message within 30 seconds, which is logged to a specified channel with a unique 3-digit ID and customer count. The bot copies the message to the corresponding category channel with a select menu offering purchase or inquiry options. Purchase opens a ticket in a purchase category, inquiry opens a ticket in an inquiry category, both with close buttons. Admins use /file-id to attach files to product IDs and !Done {id} to mark orders complete, incrementing customer counts and assigning roles.
  1. إنشاء بوت discord.py مع /set-orders وقائمة الأقسام وتسجيل المنتجات بأرقام من 3 خانات.

  2. إضافة قوائم الشراء والاستفسار، فتح التذاكر، زر الإغلاق، وسجلات التذاكر.

  3. إضافة أوامر الإدارة !file-id و!Done مع تحديث عدد العملاء وإرسال ملف المنتج.

  4. إضافة إعدادات القنوات، المتطلبات، وملف .env نموذجي بدون تضمين التوكن المكشوف.

تم إنشاء مشروع البوت بالملفات التالية:

  • bot.py — البوت كاملًا مع:

    • /set-orders

    • قوائم الأقسام والمنتجات

    • أرقام منتجات من 3 خانات

    • قوائم الشراء والاستفسار

    • فتح وإغلاق التذاكر

    • تسجيل المنتجات والتذاكر

    • !file-id

    • !Done

    • تحديث عدد العملاء ومنشن الرتبة

  • config.json — جميع أ IDs للقنوات والتصنيفات والرتبة.

  • requirements.txt

  • .env.example

  • README.md

لتشغيله:

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

مهم جدًا: التوكن الموجود في الرسالة تم تجاهله ولم يتم وضعه في أي ملف. يجب إلغاؤه فورًا من Discord Developer Portal وإنشاء توكن جديد، لأنه أصبح مكشوفًا.

_o1c

خلاص سويت reset token وين احطه؟ في اي ملف

Kodari AI
KodariAug 6 at 7:57 am 1

حطه في ملف .env بجانب ملف bot.py، وليس داخل config.json.

أنشئ ملفًا جديدًا اسمه بالضبط:

Plain Text
.env

واكتب داخله:

Env
DISCORD_TOKEN=التوكن_الجديد_هنا

مثال:

Env
DISCORD_TOKEN=MTUz...التوكن...

بدون علامات اقتباس. بعدها شغّل:

Shell
python bot.py

إذا كان عندك ملف .env.example، انسخه وغيّر اسمه إلى .env ثم استبدل القيمة. لا ترسل ملف .env لأي شخص ولا ترفعه إلى GitHub.

Kodari can make mistakes. Review important code before using.
Files
bot.py
config.json
README.md
requirements.txt
Code
4 736
bot.py
import asyncio
import io
import json
import logging
import os
from pathlib import Path
from typing import Any, Optional
from urllib.parse import urlparse

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


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


with Path("config.json").open("r", encoding="utf-8") as config_file:
    CONFIG = json.load(config_file)


SHOP_EMOJI = discord.PartialEmoji(name="shopIcon", id=1271874292480479293)
STAFF_EMOJI = discord.PartialEmoji(name="staff_icon", id=1272131230766202901)


class DataStore:
    def __init__(self, path: str = "data.json") -> None:
        self.path = Path(path)
        self.data: dict[str, Any] = {
            "next_id": 100,
            "products": {},
        }
        self.load()

    def load(self) -> None:
        if not self.path.exists():
            return
        try:
            loaded = json.loads(self.path.read_text(encoding="utf-8"))
            if isinstance(loaded, dict):
                self.data.update(loaded)
        except (OSError, json.JSONDecodeError):
            logger.exception("Could not load data.json; starting with empty data")

        if not isinstance(self.data.get("products"), dict):
            self.data["products"] = {}
        if not isinstance(self.data.get("next_id"), int):
            self.data["next_id"] = 100

    def save(self) -> None:
        self.path.write_text(
            json.dumps(self.data, ensure_ascii=False, indent=2),
            encoding="utf-8",
        )

    def allocate_id(self) -> int:
        used = {int(key) for key in self.data["products"] if str(key).isdigit()}
        start = max(100, int(self.data.get("next_id", 100)))
        for offset in range(900):
            product_id = 100 + ((start - 100 + offset) % 900)
            if product_id not in used:
                self.data["next_id"] = 100 + ((product_id - 99) % 900)
                return product_id
        raise RuntimeError("All three-digit product IDs are in use")

    def get_product(self, product_id: str | int) -> Optional[dict[str, Any]]:
        try:
            key = str(int(product_id))
        except (TypeError, ValueError):
            return None
        return self.data["products"].get(key)


def category_config(category_key: str) -> Optional[dict[str, Any]]:
    for category in CONFIG["product_categories"]:
        if category["key"] == category_key:
            return category
    return None


def product_text(product: dict[str, Any]) -> str:
    text = (product.get("content") or "").strip() or "(بدون نص)"
    links = []
    for attachment in product.get("attachments", []):
        url = attachment.get("url")
        filename = attachment.get("filename", "file")
        if url:
            links.append(f"[{filename}]({url})")
    if links:
        text += "\n\n" + "\n".join(links)
    return text


def build_product_embed(product: dict[str, Any]) -> discord.Embed:
    category = category_config(product["category"])
    label = category["label"] if category else product["category"]
    embed = discord.Embed(
        title=f"{label} | ID: {int(product['id']):03d}",
        description=product_text(product)[:4096],
        colour=discord.Colour.blurple(),
    )
    for attachment in product.get("attachments", []):
        content_type = attachment.get("content_type") or ""
        if content_type.startswith("image/") and attachment.get("url"):
            embed.set_image(url=attachment["url"])
            break
    embed.add_field(
        name="\u200b",
        value=(
            f"<:tada:1271874203125022870> **Customers**: "
            f"{int(product.get('customers', 0))}"
        ),
        inline=False,
    )
    return embed


def build_ticket_embed(
    product: dict[str, Any], user: discord.Member, ticket_kind: str
) -> discord.Embed:
    label = "شراء" if ticket_kind == "purchase" else "استفسار"
    embed = discord.Embed(
        title=f"تذكرة {label}",
        description=(
            f"**الزبون {user.mention} تم فتح تذكره {label} عبر المنتج:**\n\n"
            f"{product_text(product)[:3800]}"
        ),
        colour=discord.Colour.blurple(),
    )
    for attachment in product.get("attachments", []):
        content_type = attachment.get("content_type") or ""
        if content_type.startswith("image/") and attachment.get("url"):
            embed.set_image(url=attachment["url"])
            break
    return embed


async def download_attachment(url: str) -> Optional[bytes]:
    try:
        timeout = aiohttp.ClientTimeout(total=25)
        async with aiohttp.ClientSession(timeout=timeout) as session:
            async with session.get(url) as response:
                if response.status != 200:
                    return None
                if response.content_length and response.content_length > 24 * 1024 * 1024:
                    return None
                data = await response.read()
                return data if len(data) <= 24 * 1024 * 1024 else None
    except (aiohttp.ClientError, asyncio.TimeoutError):
        return None


async def send_downloaded_file(channel: discord.abc.Messageable, url: str) -> None:
    data = await download_attachment(url)
    if data is None:
        raise RuntimeError("تعذر تحميل الملف أو أن حجمه أكبر من الحد المسموح")
    filename = Path(urlparse(url).path).name or "product-file"
    filename = filename[:100]
    await channel.send(file=discord.File(io.BytesIO(data), filename=filename))


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


class OrdersSelect(discord.ui.Select):
    def __init__(self) -> None:
        options = [
            discord.SelectOption(
                label=category["label"],
                value=category["key"],
                emoji="🛒",
            )
            for category in CONFIG["product_categories"]
        ]
        super().__init__(
            custom_id="orders_category_select",
            placeholder="اختر القسم المطلوب",
            min_values=1,
            max_values=1,
            options=options,
        )

    async def callback(self, interaction: discord.Interaction) -> None:
        category_key = self.values[0]
        category = category_config(category_key)
        if category is None or interaction.guild is None:
            await interaction.response.send_message(
                "حدث خطأ في تحديد القسم.", ephemeral=True
            )
            return