ملفات البوت
bot.py
"""حارس الروم — بوت ديسكورد لقفل الرومات وفتحها والردود التلقائية.
التشغيل: python bot.py
التوكن يُقرأ من متغير البيئة DISCORD_BOT_TOKEN أو من ملف .env بجانب البوت.
"""
import json
import os
from pathlib import Path
import discord
from discord import app_commands
BASE_DIR = Path(__file__).resolve().parent
REPLIES_FILE = BASE_DIR / "replies.json"
def load_env_file() -> None:
"""يقرأ ملف .env بسيطًا (KEY=VALUE) دون مكتبات إضافية."""
env_path = BASE_DIR / ".env"
if not env_path.exists():
return
for line in env_path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))
def load_replies() -> dict[str, str]:
if not REPLIES_FILE.exists():
return {}
try:
data = json.loads(REPLIES_FILE.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
return {}
if not isinstance(data, dict):
return {}
return {str(k): str(v) for k, v in data.items()}
def save_replies(replies: dict[str, str]) -> None:
REPLIES_FILE.write_text(
json.dumps(replies, ensure_ascii=False, indent=2), encoding="utf-8"
)
intents = discord.Intents.default()
intents.message_content = True # يجب تفعيله أيضًا من بوابة المطورين
class GuardBot(discord.Client):
def __init__(self) -> None:
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
self.replies: dict[str, str] = load_replies()
async def setup_hook(self) -> None:
await self.tree.sync()
bot = GuardBot()
@bot.tree.command(name="lock", description="يقفل الروم الحالي ويمنع الأعضاء من الكتابة")
@app_commands.default_permissions(manage_channels=True)
@app_commands.guild_only()
async def lock(interaction: discord.Interaction) -> None:
channel = interaction.channel
if not isinstance(channel, (discord.TextChannel, discord.Thread)) or isinstance(channel, discord.Thread):
await interaction.response.send_message("هذا الأمر يعمل في الرومات النصية فقط.", ephemeral=True)
return
if not interaction.permissions.manage_channels:
await interaction.response.send_message("تحتاج صلاحية إدارة الرومات", ephemeral=True)
return
everyone = interaction.guild.default_role
overwrite = channel.overwrites_for(everyone)
if overwrite.send_messages is False:
await interaction.response.send_message("الروم مقفل بالفعل", ephemeral=True)
return
overwrite.send_messages = False
try:
await channel.set_permissions(everyone, overwrite=overwrite, reason=f"قفل بواسطة {interaction.user}")
except discord.Forbidden:
await interaction.response.send_message(
"لا أملك صلاحية إدارة الصلاحيات في هذا الروم", ephemeral=True
)
return
await interaction.response.send_message("🔒 تم قفل الروم. لا يستطيع الأعضاء الكتابة الآن.")
@bot.tree.command(name="unlock", description="يفتح الروم ويعيد للأعضاء الكتابة")
@app_commands.default_permissions(manage_channels=True)
@app_commands.guild_only()
async def unlock(interaction: discord.Interaction) -> None:
channel = interaction.channel
if not isinstance(channel, discord.TextChannel):
await interaction.response.send_message("هذا الأمر يعمل في الرومات النصية فقط.", ephemeral=True)
return
if not interaction.permissions.manage_channels:
await interaction.response.send_message("تحتاج صلاحية إدارة الرومات", ephemeral=True)
return
everyone = interaction.guild.default_role
overwrite = channel.overwrites_for(everyone)
if overwrite.send_messages is not False:
await interaction.response.send_message("الروم مفتوح بالفعل", ephemeral=True)
return
overwrite.send_messages = None # الوضع المحايد
try:
await channel.set_permissions(everyone, overwrite=overwrite, reason=f"فتح بواسطة {interaction.user}")
except discord.Forbidden:
await interaction.response.send_message(
"لا أملك صلاحية إدارة الصلاحيات في هذا الروم", ephemeral=True
)
return
await interaction.response.send_message("🔓 تم فتح الروم. يستطيع الأعضاء الكتابة الآن.")
autoreply = app_commands.Group(
name="autoreply",
description="إدارة الردود التلقائية",
default_permissions=discord.Permissions(manage_channels=True),
guild_only=True,
)
def can_manage(interaction: discord.Interaction) -> bool:
return interaction.permissions.manage_channels
@autoreply.command(name="add", description="يضيف كلمة وردّها")
@app_commands.describe(word="الكلمة التي يراقبها البوت", reply="الرد الذي يرسله البوت")
async def autoreply_add(interaction: discord.Interaction, word: str, reply: str) -> None:
if not can_manage(interaction):
await interaction.response.send_message("تحتاج صلاحية إدارة الرومات", ephemeral=True)
return
word = word.strip()
reply = reply.strip()
if not word or not reply:
await interaction.response.send_message("اكتب الكلمة والرد", ephemeral=True)
return
# استبدال أي كلمة مطابقة دون اعتبار لحالة الأحرف
for existing in [k for k in bot.replies if k.casefold() == word.casefold()]:
del bot.replies[existing]
bot.replies[word] = reply
save_replies(bot.replies)
await interaction.response.send_message(f"تمت إضافة الرد على «{word}».", ephemeral=True)
@autoreply.command(name="remove", description="يحذف كلمة من الردود")
@app_commands.describe(word="الكلمة المراد حذفها")
async def autoreply_remove(interaction: discord.Interaction, word: str) -> None:
if not can_manage(interaction):
await interaction.response.send_message("تحتاج صلاحية إدارة الرومات", ephemeral=True)
return
matches = [k for k in bot.replies if k.casefold() == word.strip().casefold()]
if not matches:
await interaction.response.send_message("لا توجد هذه الكلمة في الردود", ephemeral=True)
return
for key in matches:
del bot.replies[key]
save_replies(bot.replies)
await interaction.response.send_message("تم حذف الرد.", ephemeral=True)
@autoreply.command(name="list", description="يعرض كل الردود المحفوظة")
async def autoreply_list(interaction: discord.Interaction) -> None:
if not can_manage(interaction):
await interaction.response.send_message("تحتاج صلاحية إدارة الرومات", ephemeral=True)
return
if not bot.replies:
await interaction.response.send_message("لا توجد ردود بعد", ephemeral=True)
return
lines = [f"• {word} ← {reply}" for word, reply in bot.replies.items()]
await interaction.response.send_message("\n".join(lines)[:1900], ephemeral=True)
bot.tree.add_command(autoreply)
@bot.event
async def on_ready() -> None:
print(f"تم تسجيل الدخول باسم {bot.user}")
@bot.event
async def on_message(message: discord.Message) -> None:
if message.author.bot:
return
content = message.content.casefold()
for word, reply in bot.replies.items():
if word.casefold() in content:
await message.reply(reply, mention_author=False)
break
if __name__ == "__main__":
load_env_file()
token = os.environ.get("DISCORD_BOT_TOKEN")
if not token:
raise SystemExit("لم يتم العثور على DISCORD_BOT_TOKEN. ضعه في ملف .env أو متغير البيئة.")
bot.run(token)