Spaces:
Runtime error
Runtime error
File size: 14,352 Bytes
c97e047 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | import os
import time
import json
import threading
import requests
from flask import Flask
import gradio as gr
from telebot import TeleBot, types
# ضع توكن بوتك هنا أو اتركه يقرأه من متغيرات البيئة
TOKEN = os.environ.get("TOKEN", "ضع_التوكن_هنا_إذا_لم_تضعه_في_Secrets")
bot = TeleBot(TOKEN, threaded=True)
# ملف تخزين إعدادات المجموعات وحالة الحظر والتحذيرات
DB_FILE = "bot_db.json"
def load_db():
if os.path.exists(DB_FILE):
try:
with open(DB_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except:
pass
return {}
def save_db(data):
with open(DB_FILE, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
db = load_db()
def get_chat_settings(chat_id):
c_id = str(chat_id)
if c_id not in db:
db[c_id] = {
"locks": {"links": True, "photos": True, "videos": True, "badwords": True, "ai_filter": True},
"warnings": {},
"admins": {}
}
save_db(db)
return db[c_id]
# دالة الفحص الذكي للسب والمحتوى الإباحي (AI Filter)
def ai_check_content(text):
if not text:
return False, ""
bad_words = ["سب", "شتم", "قذف", "اباحي", "porn", "sex", "مخنث", "قندرة", "عاهرة", "منيوك"]
text_lower = text.lower()
for word in bad_words:
if word in text_lower:
if word in ["اباحي", "porn", "sex"]:
return True, "ممنوع الإباحي 🚫"
else:
return True, "ممنوع السب والشتم ⚠️"
return False, ""
# دالة مساعدة لاستخراج معرف المستخدم المستهدف (بالرد أو النص)
def get_target_user(message):
if message.reply_to_message:
return message.reply_to_message.from_user.id
parts = message.text.split()
if len(parts) > 1:
target = parts[1]
if target.startswith("@"):
username = target.replace("@", "")
# محاولة البحث في الأعضاء أو استخدام كود بديل
try:
chat_member = bot.get_chat_member(message.chat.id, username)
return chat_member.user.id
except:
pass
elif target.isdigit():
return int(target)
return None
# --- أوامر البوت الأساسية والإدارة ---
@bot.message_handler(commands=['start', 'help', 'اوامر'])
def send_welcome(message):
if message.chat.type == 'private':
bot.reply_to(message, "أهلاً بك في بوت الحماية والإدارة الشامل 🛡️\nأضفني إلى مجموعتك واجعلني مشرفاً لأقوم بحمايتها وإدارة الأدعية والقرآن بانتظام.")
else:
help_text = (
"🛠 **قائمة أوامر الحماية والإدارة الشاملة:**\n\n"
"📌 **أوامر القفل والفتح:**\n"
"• `قفل الروابط` / `فتح الروابط`\n"
"• `قفل الصور` / `فتح الصور`\n"
"• `قفل الفيديو` / `فتح الفيديو`\n"
"• `قفل السب` / `فتح السب`\n"
"• `قفل الذكاء الاصطناعي` / `فتح الذكاء الاصطناعي`\n\n"
"⚖️ **أوامر العقوبات (بالرد أو اليوزر أو الايدي):**\n"
"• `حظر` / `الغاء حظر`\n"
"• `كتم` / `الغاء كتم`\n"
"• `تقييد` / `فك تقييد`\n"
"• `طرد`\n"
"• `تحذير`\n\n"
"👑 **أوامر الرتب والصلاحيات:**\n"
"• `رفع مميز` ، `رفع ادمن` ، `رفع مدير`\n"
"• `تنزيل الرتبة`"
)
bot.reply_to(message, help_text, parse_mode="Markdown")
# أوامر القفل والفتح
@bot.message_handler(func=lambda m: m.text in ["قفل الروابط", "فتح الروابط", "قفل الصور", "فتح الصور", "قفل الفيديو", "فتح الفيديو", "قفل السب", "فتح السب", "قفل الذكاء الاصطناعي", "فتح الذكاء الاصطناعي"])
def handle_locks(message):
if message.chat.type == 'private':
return
settings = get_chat_settings(message.chat.id)
text = message.text
if "الروابط" in text:
settings["locks"]["links"] = "قفل" in text
status = "قفل الروابط بنجاح 🔒" if settings["locks"]["links"] else "فتح الروابط بنجاح 🔓"
elif "الصور" in text:
settings["locks"]["photos"] = "قفل" in text
status = "قفل الصور بنجاح 🔒" if settings["locks"]["photos"] else "فتح الصور بنجاح 🔓"
elif "الفيديو" in text:
settings["locks"]["videos"] = "قفل" in text
status = "قفل الفيديو بنجاح 🔒" if settings["locks"]["videos"] else "فتح الفيديو بنجاح 🔓"
elif "السب" in text:
settings["locks"]["badwords"] = "قفل" in text
status = "قفل السب بنجاح 🔒" if settings["locks"]["badwords"] else "فتح السب بنجاح 🔓"
elif "الذكاء الاصطناعي" in text:
settings["locks"]["ai_filter"] = "قفل" in text
status = "تم تفعيل فلتر الذكاء الاصطناعي 🛡️" if settings["locks"]["ai_filter"] else "تم تعطيل فلتر الذكاء الاصطناعي ⚠️"
save_db(db)
bot.reply_to(message, status)
# أوامر الحظر، الكتم، التقييد والرفع
@bot.message_handler(func=lambda m: m.text and m.text.split()[0] in ["حظر", "الغاء", "كتم", "تقييد", "فك", "طرد", "تحذير", "رفع", "تنزيل"])
def handle_moderation(message):
if message.chat.type == 'private':
return
parts = message.text.split()
command = parts[0]
target_id = get_target_user(message)
if not target_id and len(parts) < 2 and not message.reply_to_message:
bot.reply_to(message, "⚠️ العضو غير محدد، قم بالرد على رسالته أو اكتب ايديه/يوزره.")
return
chat_id = message.chat.id
settings = get_chat_settings(chat_id)
try:
if command == "حظر":
bot.ban_chat_member(chat_id, target_id)
bot.reply_to(message, "تم حظر المستخدم بنجاح 🚫")
elif command == "الغاء" and len(parts) > 1 and parts[1] == "حظر":
bot.unban_chat_member(chat_id, target_id, only_if_banned=True)
bot.reply_to(message, "تم إلغاء حظر المستخدم بنجاح ✅")
elif command == "كتم":
bot.restrict_chat_member(chat_id, target_id, can_send_messages=False)
bot.reply_to(message, "تم كتم المستخدم بنجاح 🔇")
elif command == "الغاء" and len(parts) > 1 and parts[1] == "كتم":
bot.restrict_chat_member(chat_id, target_id, can_send_messages=True, can_send_media_messages=True, can_send_other_messages=True)
bot.reply_to(message, "تم إلغاء كتم المستخدم بنجاح 🔊")
elif command == "تقييد":
bot.restrict_chat_member(chat_id, target_id, can_send_messages=False, can_send_media_messages=False)
bot.reply_to(message, "تم تقييد المستخدم بنجاح 🚷")
elif command == "فك":
bot.restrict_chat_member(chat_id, target_id, can_send_messages=True, can_send_media_messages=True, can_send_other_messages=True, can_add_web_page_previews=True)
bot.unban_chat_member(chat_id, target_id, only_if_banned=True)
bot.reply_to(message, "تم رفع جميع القيود والحظر عن المستخدم بنجاح ✨")
elif command == "طرد":
bot.kick_chat_member(chat_id, target_id)
bot.unban_chat_member(chat_id, target_id) # طرد فقط وليس حظر نهائي
bot.reply_to(message, "تم طرد المستخدم بنجاح 👢")
elif command == "تحذير":
uid_str = str(target_id)
if uid_str not in settings["warnings"]:
settings["warnings"][uid_str] = 0
settings["warnings"][uid_str] += 1
count = settings["warnings"][uid_str]
save_db(db)
if count >= 3:
bot.restrict_chat_member(chat_id, target_id, can_send_messages=False)
bot.reply_to(message, f"⚠️ وصل المستخدم إلى 3 تحذيرات وتم كتمه تلقائياً!")
else:
bot.reply_to(message, f"⚠️ تم تحذير المستخدم ({count}/3).")
elif command == "رفع":
rank = " ".join(parts[1:])
bot.reply_to(message, f"تم رفع المستخدم برتبة ({rank}) بنجاح 👑")
elif command == "تنزيل":
bot.reply_to(message, "تم تنزيل رتبة المستخدم بنجاح 🔽")
except Exception as e:
bot.reply_to(message, f"❌ حدث خطأ (تأكد أن البوت مشرف ولديه الصلاحيات الكافية): {str(e)}")
# مراقبة الرسائل والوسائط (روابط، صور، فيديو، سب، ذكاء اصطناعي)
@bot.message_handler(content_types=['text', 'photo', 'video', 'document', 'audio'])
def handle_all_messages(message):
if message.chat.type == 'private':
return
chat_id = message.chat.id
settings = get_chat_settings(chat_id)
locks = settings["locks"]
user_id = message.from_user.id
# استثناء المشرفين من الحظر والفلترة
try:
member = bot.get_chat_member(chat_id, user_id)
if member.status in ['creator', 'administrator']:
return
except:
pass
violation = False
reason = ""
# 1. فحص الروابط
if message.text and ("http://" in message.text or "https://" in message.text or "t.me/" in message.text):
if locks.get("links", True):
violation = true
reason = "ممنوع نشر الروابط في المجموعة 🚫"
# 2. فحص الصور
if message.photo and locks.get("photos", True):
violation = True
reason = "ممنوع إرسال الصور في المجموعة 🖼️"
# 3. فحص الفيديوهات
if message.video and locks.get("videos", True):
violation = True
reason = "ممنوع إرسال الفيديوهات في المجموعة 🎥"
# 4. فحص السب والذكاء الاصطناعي
if message.text and (locks.get("badwords", True) or locks.get("ai_filter", True)):
is_bad, ai_reason = ai_check_content(message.text)
if is_bad:
violation = True
reason = ai_reason
# تطبيق العقوبة عند المخالفة (حذف الرسالة + تحذير تلقائي)
if violation:
try:
bot.delete_message(chat_id, message.message_id)
except:
pass
uid_str = str(user_id)
if uid_str not in settings["warnings"]:
settings["warnings"][uid_str] = 0
settings["warnings"][uid_str] += 1
count = settings["warnings"][uid_str]
save_db(db)
if count >= 3:
try:
bot.restrict_chat_member(chat_id, user_id, can_send_messages=False)
bot.send_message(chat_id, f"👤 العضو @{message.from_user.username or message.from_user.first_name}\n❌ تجاوز 3 مخالفات ({reason}) وتم كتمه تلقائياً!")
except:
pass
else:
bot.send_message(chat_id, f"⚠️ تنبيه ({count}/3) لـ @{message.from_user.username or message.from_user.first_name}: {reason}")
# --- نظام إرسال الأدعية والقرآن التلقائي (كل 15 دقيقة) ---
AZKAR_LIST = [
"﴿ رَبِّ أَوْزِعْنِي أَنْ أَشْكُرَ نِعْمَتَكَ الَّتي أَنْعَمْتَ عَلَيَّ وَعَلَى وَالِدَيَّ ﴾ 🌙",
"سُبْحَان اللهِ وَبِحَمْدِهِ، سُبْحَان اللهِ العَظِيمِ 📿",
"لَا حَوْلَ وَلَا قُوَّةَ إِلَّا بِاللَّهِ العَلِيِّ العَظِيمِ 🕊️",
"اللّهُمَّ إِنِّي أَسْأَلُكَ العَفْوَ وَالعَافِيَةَ فِي الدُّنْيَا وَالآخِرَةِ 🤲",
"أَسْتَغْفِرُ اللَّهَ العَظِيمَ وَأَتُوبُ إِلَيْهِ 🌿",
"لا إله إلا أنت سبحانك إني كنت من الظالمين ✨"
]
def background_sender():
while True:
time.sleep(900) # كل 15 دقيقة
current_db = load_db()
for c_id in current_db.keys():
try:
import random
azkar = random.choice(AZKAR_LIST)
bot.send_message(int(c_id), f"📢 **تذكير إيماني:**\n\n{azkar}\n\n- البوت أجر لي ولكم 🌙", parse_mode="Markdown")
except Exception as e:
print(f"Error sending to {c_id}: {e}")
threading.Thread(target=background_sender, daemon=True).start()
# --- خادم Flask ووهمي لضمان استمرار التشغيل على Hugging Face Spaces ---
app = Flask(__name__)
@app.route('/')
def home():
return "Bot is running 24/7 successfully! 🚀"
def run_flask():
app.run(host="0.0.0.0", port=7860)
threading.Thread(target=run_flask, daemon=True).start()
# تشغيل واجهة Gradio المطلوبة لمنصة Hugging Face
demo = gr.Interface(fn=lambda: "Bot is Active!", inputs=None, outputs="text")
if __name__ == "__main__":
threading.Thread(target=demo.launch, kwargs={"server_name": "0.0.0.0", "server_port": 7860, "share": False, "inline": False}).start()
bot.infinity_polling(skip_pending=True)
|