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