Spaces:
Sleeping
Sleeping
Upload bot_server.py with huggingface_hub
Browse files- bot_server.py +539 -721
bot_server.py
CHANGED
|
@@ -1,32 +1,13 @@
|
|
| 1 |
"""
|
| 2 |
-
الوكيل
|
| 3 |
-
========================================
|
| 4 |
-
|
| 5 |
-
ال
|
| 6 |
-
1.
|
| 7 |
-
2.
|
| 8 |
-
3.
|
| 9 |
-
4.
|
| 10 |
-
5.
|
| 11 |
-
6. LangChain tools pattern - مهارات قابلة للاستدعاء
|
| 12 |
-
7. Semantic Router - توجيه فوري
|
| 13 |
-
|
| 14 |
-
المهارات المحلية (رد فوري < 1 ثانية):
|
| 15 |
-
- 🧮 حاسبة رياضية (eval آمن)
|
| 16 |
-
- 🌐 مترجم فوري (قاموس محلي)
|
| 17 |
-
- 💱 محول عملات (USD/SAR/EUR)
|
| 18 |
-
- 📏 محول وحدات (km/mile, C/F)
|
| 19 |
-
- ⏰ وقت وتاريخ
|
| 20 |
-
- 📝 عداد كلمات/أحرف
|
| 21 |
-
- 🔢 محول أرقام (عربي/إنجليزي/روماني)
|
| 22 |
-
- 🎲 عشوائي
|
| 23 |
-
- 📦 base64/URL encode/decode
|
| 24 |
-
|
| 25 |
-
سرعة الـ LLM:
|
| 26 |
-
- ردود مسبقة الإعداد: < 0.1s
|
| 27 |
-
- كاش دلالي: < 0.05s
|
| 28 |
-
- مهارات محلية: < 0.05s
|
| 29 |
-
- ردود LLM جديدة: 2-5s (حد فيزيائي)
|
| 30 |
"""
|
| 31 |
import asyncio
|
| 32 |
import json
|
|
@@ -39,7 +20,10 @@ import hashlib
|
|
| 39 |
import math
|
| 40 |
import traceback
|
| 41 |
import random
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
import aiohttp
|
| 45 |
from aiohttp import web
|
|
@@ -63,24 +47,19 @@ WEBHOOK_PATH = "/webhook"
|
|
| 63 |
PORT = 7860
|
| 64 |
|
| 65 |
LOG = []
|
| 66 |
-
STATS = {
|
| 67 |
-
|
| 68 |
-
"cache_hits": 0,
|
| 69 |
-
"local_skills": 0,
|
| 70 |
-
"llm_calls": 0,
|
| 71 |
-
"failures": 0,
|
| 72 |
-
}
|
| 73 |
|
| 74 |
|
| 75 |
# ============================================================
|
| 76 |
-
# 1) TURBOVEC
|
| 77 |
# ============================================================
|
| 78 |
|
| 79 |
class TurboCache:
|
| 80 |
-
def __init__(self, max_size
|
| 81 |
-
self.cache
|
| 82 |
self.max_size = max_size
|
| 83 |
-
self.
|
| 84 |
self.hits = 0
|
| 85 |
self.misses = 0
|
| 86 |
self.stopwords = {
|
|
@@ -94,545 +73,177 @@ class TurboCache:
|
|
| 94 |
"and", "or", "but", "not", "no", "yes",
|
| 95 |
}
|
| 96 |
|
| 97 |
-
def
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
return text
|
| 102 |
|
| 103 |
-
def _hash(self,
|
| 104 |
-
return hashlib.md5(self.
|
| 105 |
|
| 106 |
-
def
|
| 107 |
-
|
| 108 |
-
|
| 109 |
|
| 110 |
@staticmethod
|
| 111 |
-
def
|
| 112 |
-
if not a or not b:
|
| 113 |
-
return 0.0
|
| 114 |
return len(a & b) / len(a | b)
|
| 115 |
|
| 116 |
-
def get(self,
|
| 117 |
-
h = self._hash(
|
| 118 |
if h in self.cache:
|
| 119 |
-
|
| 120 |
-
if time.time() -
|
| 121 |
self.hits += 1
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
best_entry = entry
|
| 134 |
-
if best_entry and best_score >= self.similarity_threshold:
|
| 135 |
-
if time.time() - best_entry["time"] < 7200:
|
| 136 |
-
self.hits += 1
|
| 137 |
-
best_entry["hits"] += 1
|
| 138 |
-
return best_entry["response"], best_entry["model"]
|
| 139 |
-
|
| 140 |
self.misses += 1
|
| 141 |
return None
|
| 142 |
|
| 143 |
-
def put(self,
|
| 144 |
-
h = self._hash(
|
| 145 |
if len(self.cache) >= self.max_size:
|
| 146 |
-
|
| 147 |
-
del self.cache[
|
| 148 |
-
self.cache[h] = {
|
| 149 |
-
"response": response,
|
| 150 |
-
"model": model,
|
| 151 |
-
"keywords": self._keywords(query),
|
| 152 |
-
"time": time.time(),
|
| 153 |
-
"hits": 0,
|
| 154 |
-
}
|
| 155 |
|
| 156 |
-
def stats(self)
|
| 157 |
-
|
| 158 |
-
return {
|
| 159 |
-
|
| 160 |
-
"hits": self.hits,
|
| 161 |
-
"misses": self.misses,
|
| 162 |
-
"hit_rate": f"{(self.hits/total*100):.1f}%" if total else "0%",
|
| 163 |
-
}
|
| 164 |
|
| 165 |
|
| 166 |
-
turbo_cache = TurboCache(
|
| 167 |
|
| 168 |
|
| 169 |
# ============================================================
|
| 170 |
-
# 2)
|
| 171 |
# ============================================================
|
| 172 |
|
| 173 |
-
|
| 174 |
-
"""
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
return False
|
| 182 |
-
return bool(re.search(self.pattern, text, re.IGNORECASE))
|
| 183 |
-
|
| 184 |
-
def execute(self, text: str) -> Optional[str]:
|
| 185 |
-
raise NotImplementedError
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
class CalculatorSkill(Skill):
|
| 189 |
-
"""🧮 حاسبة رياضية فورية"""
|
| 190 |
-
name = "calculator"
|
| 191 |
-
description = "حساب رياضي"
|
| 192 |
-
pattern = r"^[\s\d\+\-\*\/\(\)\.\^\%\s]+$|^(احسب|calculate|كم)\s.+"
|
| 193 |
-
|
| 194 |
-
def matches(self, text: str) -> bool:
|
| 195 |
-
# يجب أن يحتوي على أرقام وعملية
|
| 196 |
-
if not re.search(r"\d", text):
|
| 197 |
-
return False
|
| 198 |
-
# إزالة الكلمات
|
| 199 |
-
cleaned = re.sub(r"(احسب|calculate|كم|يساوي|\?|\؟)", "", text, flags=re.IGNORECASE).strip()
|
| 200 |
-
# تحقق من أنه تعبير رياضي صالح
|
| 201 |
-
if re.match(r"^[\d\s\+\-\*\/\(\)\.\^\%]+$", cleaned):
|
| 202 |
-
return True
|
| 203 |
-
return False
|
| 204 |
-
|
| 205 |
-
def execute(self, text: str) -> Optional[str]:
|
| 206 |
-
cleaned = re.sub(r"(احسب|calculate|كم|يساوي|\?|\؟)", "", text, flags=re.IGNORECASE).strip()
|
| 207 |
-
try:
|
| 208 |
-
# استبدل ^ بـ **
|
| 209 |
-
cleaned = cleaned.replace("^", "**")
|
| 210 |
-
# استبدل % بـ /100
|
| 211 |
-
cleaned = cleaned.replace("%", "/100")
|
| 212 |
-
# تقييم آمن - فقط أرقام وعمليات
|
| 213 |
-
if not re.match(r"^[\d\s\+\-\*\/\(\)\.]+$", cleaned):
|
| 214 |
return None
|
| 215 |
-
|
| 216 |
-
return f"🧮 **{text}** = **{result}**"
|
| 217 |
-
except Exception:
|
| 218 |
-
return None
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
class TimeSkill(Skill):
|
| 222 |
-
"""⏰ الوقت والتاريخ"""
|
| 223 |
-
name = "time"
|
| 224 |
-
pattern = r"(الوقت|time|الساعة|التاريخ|date|اليوم|today)"
|
| 225 |
-
|
| 226 |
-
def matches(self, text: str) -> bool:
|
| 227 |
-
return bool(re.search(self.pattern, text, re.IGNORECASE)) and len(text) < 30
|
| 228 |
-
|
| 229 |
-
def execute(self, text: str) -> Optional[str]:
|
| 230 |
-
from datetime import datetime, timezone, timedelta
|
| 231 |
-
# توقيت السعودية
|
| 232 |
-
tz = timezone(timedelta(hours=3))
|
| 233 |
-
now = datetime.now(tz)
|
| 234 |
-
days_ar = ["الإثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت", "الأحد"]
|
| 235 |
-
months_ar = ["يناير", "فبراير", "مارس", "أبريل", "مايو", "يونيو",
|
| 236 |
-
"يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر"]
|
| 237 |
-
day_name = days_ar[now.weekday()]
|
| 238 |
-
month_name = months_ar[now.month - 1]
|
| 239 |
-
return (
|
| 240 |
-
f"⏰ **التاريخ والوقت** (توقيت السعودية)\n\n"
|
| 241 |
-
f"📅 {day_name}، {now.day} {month_name} {now.year}\n"
|
| 242 |
-
f"🕐 {now.strftime('%H:%M:%S')}"
|
| 243 |
-
)
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
class CurrencyConverterSkill(Skill):
|
| 247 |
-
"""💱 محول عملات"""
|
| 248 |
-
name = "currency"
|
| 249 |
-
pattern = r"(دولار|ريال|يورو|dollar|riyal|eur|usd|sar|convert|حوّل|كم)\s.*"
|
| 250 |
-
|
| 251 |
-
# أسعار تقريبية ثابتة (تحديث يدوي)
|
| 252 |
-
RATES = {
|
| 253 |
-
"usd_sar": 3.75,
|
| 254 |
-
"sar_usd": 0.267,
|
| 255 |
-
"usd_eur": 0.92,
|
| 256 |
-
"eur_usd": 1.09,
|
| 257 |
-
"sar_eur": 0.245,
|
| 258 |
-
"eur_sar": 4.09,
|
| 259 |
-
}
|
| 260 |
-
|
| 261 |
-
def matches(self, text: str) -> bool:
|
| 262 |
-
text_l = text.lower()
|
| 263 |
-
has_amount = bool(re.search(r"\d+", text))
|
| 264 |
-
has_currency = any(k in text_l for k in ["دولار", "ريال", "يورو", "usd", "sar", "eur", "dollar", "riyal", "euro"])
|
| 265 |
-
return has_amount and has_currency and len(text) < 80
|
| 266 |
-
|
| 267 |
-
def execute(self, text: str) -> Optional[str]:
|
| 268 |
-
text_l = text.lower()
|
| 269 |
-
# استخراج المبلغ
|
| 270 |
-
amount_match = re.search(r"(\d+(?:\.\d+)?)", text)
|
| 271 |
-
if not amount_match:
|
| 272 |
-
return None
|
| 273 |
-
amount = float(amount_match.group(1))
|
| 274 |
-
|
| 275 |
-
# كشف العملات
|
| 276 |
-
from_curr = None
|
| 277 |
-
to_curr = None
|
| 278 |
-
if "usd" in text_l or "دولار" in text_l:
|
| 279 |
-
from_curr = "USD"
|
| 280 |
-
if "sar" in text_l or "ريال" in text_l:
|
| 281 |
-
from_curr = "SAR" if not from_curr else from_curr
|
| 282 |
-
to_curr = "SAR" if from_curr != "SAR" else to_curr
|
| 283 |
-
if "eur" in text_l or "يورو" in text_l:
|
| 284 |
-
to_curr = "EUR"
|
| 285 |
-
|
| 286 |
-
if not from_curr or not to_curr or from_curr == to_curr:
|
| 287 |
-
return None
|
| 288 |
-
|
| 289 |
-
key = f"{from_curr.lower()}_{to_curr.lower()}"
|
| 290 |
-
rate = self.RATES.get(key)
|
| 291 |
-
if not rate:
|
| 292 |
-
return None
|
| 293 |
-
|
| 294 |
-
result = amount * rate
|
| 295 |
-
symbols = {"USD": "$", "SAR": "ر.س", "EUR": "€"}
|
| 296 |
-
return (
|
| 297 |
-
f"💱 **تحويل العملة**\n\n"
|
| 298 |
-
f"{amount} {symbols[from_curr]} = **{result:.2f} {symbols[to_curr]}**\n"
|
| 299 |
-
f"_(سعر تقريبي)_"
|
| 300 |
-
)
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
class UnitConverterSkill(Skill):
|
| 304 |
-
"""📏 محول وحدات"""
|
| 305 |
-
name = "units"
|
| 306 |
-
pattern = r"(km|mile|cm|m|kg|lb|c|f|كيلو|متر|سنتي|ميل|كجم|رطل)"
|
| 307 |
-
|
| 308 |
-
def matches(self, text: str) -> bool:
|
| 309 |
-
return bool(re.search(r"\d+", text)) and bool(re.search(self.pattern, text, re.IGNORECASE)) and len(text) < 80
|
| 310 |
-
|
| 311 |
-
def execute(self, text: str) -> Optional[str]:
|
| 312 |
-
text_l = text.lower()
|
| 313 |
-
amount_match = re.search(r"(\d+(?:\.\d+)?)", text)
|
| 314 |
-
if not amount_match:
|
| 315 |
-
return None
|
| 316 |
-
amount = float(amount_match.group(1))
|
| 317 |
-
|
| 318 |
-
conversions = []
|
| 319 |
-
|
| 320 |
-
# حرارة
|
| 321 |
-
if "c" in text_l.split() or "celsius" in text_l or "مئوية" in text_l:
|
| 322 |
-
f = (amount * 9/5) + 32
|
| 323 |
-
conversions.append(f"{amount}°C = {f:.1f}°F")
|
| 324 |
-
if "f" in text_l.split() or "fahrenheit" in text_l or "فهرنهايت" in text_l:
|
| 325 |
-
c = (amount - 32) * 5/9
|
| 326 |
-
conversions.append(f"{amount}°F = {c:.1f}°C")
|
| 327 |
-
|
| 328 |
-
# مسافة
|
| 329 |
-
if "km" in text_l or "كيلو" in text_l:
|
| 330 |
-
miles = amount * 0.621
|
| 331 |
-
conversions.append(f"{amount} km = {miles:.2f} miles")
|
| 332 |
-
if "mile" in text_l or "ميل" in text_l:
|
| 333 |
-
km = amount * 1.609
|
| 334 |
-
conversions.append(f"{amount} miles = {km:.2f} km")
|
| 335 |
-
if "cm" in text_l or "سنتي" in text_l:
|
| 336 |
-
inches = amount / 2.54
|
| 337 |
-
conversions.append(f"{amount} cm = {inches:.2f} inches")
|
| 338 |
-
|
| 339 |
-
# وزن
|
| 340 |
-
if "kg" in text_l or "كجم" in text_l:
|
| 341 |
-
lbs = amount * 2.205
|
| 342 |
-
conversions.append(f"{amount} kg = {lbs:.2f} lbs")
|
| 343 |
-
if "lb" in text_l or "رطل" in text_l:
|
| 344 |
-
kg = amount * 0.453
|
| 345 |
-
conversions.append(f"{amount} lbs = {kg:.2f} kg")
|
| 346 |
-
|
| 347 |
-
if not conversions:
|
| 348 |
-
return None
|
| 349 |
-
return "📏 **تحويل الوحدات**\n\n" + "\n".join(conversions)
|
| 350 |
|
|
|
|
| 351 |
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
def matches(self, text: str) -> bool:
|
| 358 |
-
return bool(re.search(self.pattern, text, re.IGNORECASE)) and len(text) < 40
|
| 359 |
-
|
| 360 |
-
def execute(self, text: str) -> Optional[str]:
|
| 361 |
-
text_l = text.lower()
|
| 362 |
-
if "dice" in text_l or "نرد" in text_l:
|
| 363 |
-
return f"🎲 النرد: **{random.randint(1, 6)}**"
|
| 364 |
-
# استخراج النطاق
|
| 365 |
-
nums = re.findall(r"\d+", text)
|
| 366 |
-
if len(nums) >= 2:
|
| 367 |
-
a, b = int(nums[0]), int(nums[1])
|
| 368 |
-
if a > b:
|
| 369 |
-
a, b = b, a
|
| 370 |
-
return f"🎲 رقم عشوائي بين {a} و {b}: **{random.randint(a, b)}**"
|
| 371 |
-
return f"🎲 رقم عشوائي: **{random.randint(1, 100)}**"
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
class WordCounterSkill(Skill):
|
| 375 |
-
"""📝 عداد كلمات"""
|
| 376 |
-
name = "wordcount"
|
| 377 |
-
pattern = r"(عدد كلمات|count words|كم كلمة|عد الكلمات)"
|
| 378 |
|
| 379 |
-
|
| 380 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
if not match:
|
| 386 |
-
return None
|
| 387 |
-
target = match.group(1).strip()
|
| 388 |
-
words = len(target.split())
|
| 389 |
-
chars = len(target)
|
| 390 |
-
chars_no_space = len(target.replace(" ", ""))
|
| 391 |
-
return (
|
| 392 |
-
f"📝 **إحصائيات النص**\n\n"
|
| 393 |
-
f"• الكلمات: {words}\n"
|
| 394 |
-
f"• الأحرف: {chars}\n"
|
| 395 |
-
f"• الأحرف (بدون مسافات): {chars_no_space}"
|
| 396 |
-
)
|
| 397 |
|
|
|
|
| 398 |
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
pattern = r"(base64|encode|decode|تشفير|فك تشفير)"
|
| 403 |
|
| 404 |
-
def matches(self, text: str) -> bool:
|
| 405 |
-
return bool(re.search(self.pattern, text, re.IGNORECASE)) and len(text) < 200
|
| 406 |
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 413 |
return None
|
| 414 |
-
|
| 415 |
-
try:
|
| 416 |
-
if "decode" in text_l or "فك" in text_l:
|
| 417 |
-
decoded = base64.b64decode(target).decode("utf-8", errors="replace")
|
| 418 |
-
return f"🔐 **فك تشفير Base64**\n\n`{decoded}`"
|
| 419 |
-
else:
|
| 420 |
-
encoded = base64.b64encode(target.encode()).decode()
|
| 421 |
-
return f"🔐 **تشفير Base64**\n\n`{encoded}`"
|
| 422 |
-
except Exception as e:
|
| 423 |
-
return f"❌ خطأ: {e}"
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
# سجل المهارات
|
| 427 |
-
SKILLS = [
|
| 428 |
-
CalculatorSkill(),
|
| 429 |
-
TimeSkill(),
|
| 430 |
-
CurrencyConverterSkill(),
|
| 431 |
-
UnitConverterSkill(),
|
| 432 |
-
RandomSkill(),
|
| 433 |
-
WordCounterSkill(),
|
| 434 |
-
Base64Skill(),
|
| 435 |
-
]
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
def try_local_skills(text: str) -> Optional[str]:
|
| 439 |
-
"""جرّب المهارات المحلية أولاً - رد فوري"""
|
| 440 |
-
for skill in SKILLS:
|
| 441 |
-
try:
|
| 442 |
-
if skill.matches(text):
|
| 443 |
-
result = skill.execute(text)
|
| 444 |
-
if result:
|
| 445 |
-
LOG.append(f"[{time.strftime('%H:%M:%S')}] ⚡ skill: {skill.name}")
|
| 446 |
-
STATS["local_skills"] += 1
|
| 447 |
-
return result
|
| 448 |
-
except Exception as e:
|
| 449 |
-
logger.error(f"skill {skill.name} error: {e}")
|
| 450 |
-
return None
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
# ============================================================
|
| 454 |
-
# 3) CREWAI-STYLE MULTI-AGENT (8 agents)
|
| 455 |
-
# ============================================================
|
| 456 |
-
|
| 457 |
-
class Agent:
|
| 458 |
-
def __init__(self, name: str, role: str, system_prompt: str, models: List[str]):
|
| 459 |
-
self.name = name
|
| 460 |
-
self.role = role
|
| 461 |
-
self.system_prompt = system_prompt
|
| 462 |
-
self.models = models
|
| 463 |
-
|
| 464 |
-
def matches(self, text: str) -> int:
|
| 465 |
-
return 0
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
class CodeAgent(Agent):
|
| 469 |
-
def __init__(self):
|
| 470 |
-
super().__init__("code", "🐍 خبير البرمجة",
|
| 471 |
-
"أنت خبير برمجة عالمي. اكتب كوداً نظيفاً وعملياً. استخدم Markdown. اذكر اللغة. اشرح باختصار.",
|
| 472 |
-
["deepseek/deepseek-chat", "qwen/qwen3-coder-plus", "z-ai/glm-4.7-flash-free", "stepfun/step-3.7-flash-free"])
|
| 473 |
-
|
| 474 |
-
def matches(self, text: str) -> int:
|
| 475 |
-
text_l = text.lower()
|
| 476 |
-
score = 0
|
| 477 |
-
if any(k in text_l for k in ["كود", "code", "function", "دالة", "برنامج"]): score += 40
|
| 478 |
-
if any(k in text_l for k in ["python", "javascript", "java", "html", "css", "sql"]): score += 30
|
| 479 |
-
if any(k in text_l for k in ["bug", "خطأ", "debug", "fix"]): score += 30
|
| 480 |
-
return min(score, 100)
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
class SearchAgent(Agent):
|
| 484 |
-
def __init__(self):
|
| 485 |
-
super().__init__("search", "🔍 باحث خبير",
|
| 486 |
-
"أنت باحث خبير. قدم معلومات دقيقة وشاملة. نظّم بعناوين فرعية. اذكر المصادر.",
|
| 487 |
-
["z-ai/glm-4.7-flash-free", "stepfun/step-3.7-flash-free", "deepseek/deepseek-chat"])
|
| 488 |
-
|
| 489 |
-
def matches(self, text: str) -> int:
|
| 490 |
-
text_l = text.lower()
|
| 491 |
-
score = 0
|
| 492 |
-
if any(k in text_l for k in ["ما هو", "ما هي", "what is", "عرف", "define"]): score += 40
|
| 493 |
-
if any(k in text_l for k in ["اشرح", "explain", "اخبرني", "معلومات"]): score += 35
|
| 494 |
-
return min(score, 100)
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
class WriteAgent(Agent):
|
| 498 |
-
def __init__(self):
|
| 499 |
-
super().__init__("write", "✍️ كاتب محترف",
|
| 500 |
-
"أنت كاتب مبدع. اكتب محتوى جذاباً ومنظماً. استخدم عناوين ونقاط.",
|
| 501 |
-
["z-ai/glm-4.7-flash-free", "stepfun/step-3.7-flash-free", "deepseek/deepseek-chat"])
|
| 502 |
-
|
| 503 |
-
def matches(self, text: str) -> int:
|
| 504 |
-
text_l = text.lower()
|
| 505 |
-
score = 0
|
| 506 |
-
if any(k in text_l for k in ["اكتب", "write", "مقال", "article", "قصة", "story"]): score += 40
|
| 507 |
-
if any(k in text_l for k in ["poem", "قصيدة", "خطاب", "letter"]): score += 35
|
| 508 |
-
return min(score, 100)
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
class MathAgent(Agent):
|
| 512 |
-
def __init__(self):
|
| 513 |
-
super().__init__("math", "🧮 خبير رياضيات",
|
| 514 |
-
"أنت خبير رياضيات. اعرض الحل خطوة بخطوة. تحقق من النتيجة.",
|
| 515 |
-
["deepseek/deepseek-chat", "z-ai/glm-4.7-flash-free", "stepfun/step-3.7-flash-free"])
|
| 516 |
-
|
| 517 |
-
def matches(self, text: str) -> int:
|
| 518 |
-
text_l = text.lower()
|
| 519 |
-
score = 0
|
| 520 |
-
if any(k in text_l for k in ["احسب", "calculate", "math", "معادلة"]): score += 40
|
| 521 |
-
if any(k in text_l for k in ["نسبة", "percentage", "مساحة"]): score += 30
|
| 522 |
-
return min(score, 100)
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
class TranslateAgent(Agent):
|
| 526 |
-
def __init__(self):
|
| 527 |
-
super().__init__("translate", "🌐 مترجم",
|
| 528 |
-
"أنت مترجم محترف. ترجم بدقة مع الحفاظ على المعنى.",
|
| 529 |
-
["z-ai/glm-4.7-flash-free", "stepfun/step-3.7-flash-free"])
|
| 530 |
-
|
| 531 |
-
def matches(self, text: str) -> int:
|
| 532 |
-
text_l = text.lower()
|
| 533 |
-
if any(k in text_l for k in ["ترجم", "translate", "بالإنجليزية", "بالعربية"]): return 50
|
| 534 |
-
return 0
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
class ReasoningAgent(Agent):
|
| 538 |
-
def __init__(self):
|
| 539 |
-
super().__init__("reasoning", "🧠 محلل منطقي",
|
| 540 |
-
"أنت محلل منطقي خبير. فكر خطوة بخطوة. اعرض الاستدلال بوضوح.",
|
| 541 |
-
["deepseek/deepseek-reasoner", "deepseek/deepseek-chat", "z-ai/glm-4.7-flash-free"])
|
| 542 |
-
|
| 543 |
-
def matches(self, text: str) -> int:
|
| 544 |
-
text_l = text.lower()
|
| 545 |
-
score = 0
|
| 546 |
-
if any(k in text_l for k in ["لماذا", "why", "كيف", "how", "حلل", "analyze"]): score += 35
|
| 547 |
-
if any(k in text_l for k in ["قارن", "compare", "فرق", "difference"]): score += 35
|
| 548 |
-
return min(score, 100)
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
class CreativeAgent(Agent):
|
| 552 |
-
def __init__(self):
|
| 553 |
-
super().__init__("creative", "🎨 مبدع",
|
| 554 |
-
"أنت مبدع. ابتكر أفكاراً جديدة وملهمة. كن أصيلاً.",
|
| 555 |
-
["z-ai/glm-4.7-flash-free", "stepfun/step-3.7-flash-free", "deepseek/deepseek-chat"])
|
| 556 |
-
|
| 557 |
-
def matches(self, text: str) -> int:
|
| 558 |
-
text_l = text.lower()
|
| 559 |
-
score = 0
|
| 560 |
-
if any(k in text_l for k in ["اقترح", "suggest", "فكرة", "idea", "ابتكر"]): score += 35
|
| 561 |
-
if any(k in text_l for k in ["أسماء", "names", "عناوين", "titles"]): score += 30
|
| 562 |
-
return min(score, 100)
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
class GeneralAgent(Agent):
|
| 566 |
-
def __init__(self):
|
| 567 |
-
super().__init__("general", "💬 مساعد ذكي",
|
| 568 |
-
"أنت مساعد ذكي ومفيد. أجب بالعربية الفصحى المبسطة. كن دقيقاً ومباشراً.",
|
| 569 |
-
["z-ai/glm-4.7-flash-free", "stepfun/step-3.7-flash-free", "deepseek/deepseek-chat"])
|
| 570 |
-
|
| 571 |
-
def matches(self, text: str) -> int:
|
| 572 |
-
return 30
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
CREW = [CodeAgent(), MathAgent(), TranslateAgent(), WriteAgent(),
|
| 576 |
-
SearchAgent(), ReasoningAgent(), CreativeAgent(), GeneralAgent()]
|
| 577 |
|
|
|
|
|
|
|
|
|
|
| 578 |
|
| 579 |
-
def select_agent(text: str) -> Agent:
|
| 580 |
-
best = CREW[-1]
|
| 581 |
-
best_score = 0
|
| 582 |
-
for agent in CREW:
|
| 583 |
-
score = agent.matches(text)
|
| 584 |
-
if score > best_score:
|
| 585 |
-
best_score = score
|
| 586 |
-
best = agent
|
| 587 |
-
return best
|
| 588 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 589 |
|
| 590 |
-
# ============================================================
|
| 591 |
-
# 4) PREDEFINED RESPONSES (ردود جاهزة فورية)
|
| 592 |
-
# ============================================================
|
| 593 |
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
# شكر
|
| 605 |
-
"شكرا": "العفو! 🙏 سعيد بمساعدتك",
|
| 606 |
-
"شكراً": "العفو! 🙏",
|
| 607 |
-
"مشكور": "لا شكر على واجب!",
|
| 608 |
-
"thanks": "You're welcome! 😊",
|
| 609 |
-
"thank you": "My pleasure!",
|
| 610 |
-
# وداع
|
| 611 |
-
"باي": "إلى اللقاء! 👋",
|
| 612 |
-
"وداعا": "في أمان الله 🌟",
|
| 613 |
-
"bye": "Goodbye! 👋",
|
| 614 |
-
# أسئلة شائعة
|
| 615 |
-
"من انت": "🤖 أنا وكيل ذكي احترافي بـ 8 وكلاء متخصصين ومهارات محلية فورية!",
|
| 616 |
-
"من أنت": "🤖 أنا وكيل ذكي احترافي بـ 8 وكلاء متخصصين ومهارات محلية فورية!",
|
| 617 |
-
"what can you do": "🚀 أستطيع:\n• الإجابة على الأسئلة\n• كتابة الكود\n• الترجمة\n• الرياضيات\n• الكتابة الإبداعية\n• والكثير! أرسل /help",
|
| 618 |
-
"ماذا تستطيع": "🚀 أستطيع:\n• الإجابة على الأسئلة\n• كتابة الكود\n• الترجمة\n• الرياضيات\n• الكتابة الإبداعية\n• والكثير! أرسل /help",
|
| 619 |
-
}
|
| 620 |
|
| 621 |
|
| 622 |
-
def
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
if
|
| 626 |
-
return PREDEFINED[norm]
|
| 627 |
-
# تطابق مع بداية
|
| 628 |
-
for key, val in PREDEFINED.items():
|
| 629 |
-
if norm.startswith(key) and len(norm) < len(key) + 15:
|
| 630 |
-
return val
|
| 631 |
-
return None
|
| 632 |
|
| 633 |
|
| 634 |
# ============================================================
|
| 635 |
-
#
|
| 636 |
# ============================================================
|
| 637 |
|
| 638 |
HTTP_SESSION = None
|
|
@@ -642,10 +253,10 @@ async def get_http_session():
|
|
| 642 |
global HTTP_SESSION
|
| 643 |
if HTTP_SESSION is None or HTTP_SESSION.closed:
|
| 644 |
connector = aiohttp.TCPConnector(
|
| 645 |
-
limit=100, limit_per_host=
|
| 646 |
enable_cleanup_closed=True,
|
| 647 |
)
|
| 648 |
-
timeout = aiohttp.ClientTimeout(total=
|
| 649 |
HTTP_SESSION = aiohttp.ClientSession(timeout=timeout, connector=connector)
|
| 650 |
return HTTP_SESSION
|
| 651 |
|
|
@@ -654,81 +265,125 @@ async def try_zenmux(model: str, messages: list) -> Optional[str]:
|
|
| 654 |
if not ZENMUX_KEY:
|
| 655 |
return None
|
| 656 |
session = await get_http_session()
|
| 657 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 658 |
try:
|
| 659 |
async with session.post(
|
| 660 |
-
"https://
|
| 661 |
-
|
| 662 |
-
json={"model": model, "messages": messages, "max_tokens": 1500, "temperature": 0.7},
|
| 663 |
) as resp:
|
| 664 |
if resp.status == 200:
|
| 665 |
data = await resp.json()
|
| 666 |
content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
|
| 667 |
if content and content.strip():
|
| 668 |
return content.strip()
|
| 669 |
-
if attempt == 0:
|
| 670 |
-
await asyncio.sleep(0.5)
|
| 671 |
-
continue
|
| 672 |
-
elif resp.status == 429 and attempt == 0 and "-free" in model:
|
| 673 |
-
await asyncio.sleep(1.5)
|
| 674 |
-
continue
|
| 675 |
-
return None
|
| 676 |
except Exception:
|
| 677 |
-
|
| 678 |
-
await asyncio.sleep(0.5)
|
| 679 |
-
continue
|
| 680 |
-
return None
|
| 681 |
return None
|
| 682 |
|
| 683 |
|
| 684 |
-
async def
|
| 685 |
-
"""Pollinations
|
| 686 |
session = await get_http_session()
|
| 687 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 688 |
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 706 |
return None
|
| 707 |
|
| 708 |
|
| 709 |
-
async def
|
| 710 |
-
"""سباق كل المصادر بالتوازي"""
|
| 711 |
start = time.time()
|
| 712 |
tasks = {}
|
| 713 |
|
| 714 |
-
# ZenMux نماذج
|
| 715 |
all_models = agent_models.copy()
|
| 716 |
extras = [
|
| 717 |
-
"z-ai/glm-4.7-flash-free", "stepfun/step-3.7-flash-free",
|
| 718 |
-
"deepseek/deepseek-chat", "
|
| 719 |
-
"z-ai/glm-5.2", # GLM-5.2 المتقدم
|
| 720 |
-
"google/gemini-2.5-flash", "meta/llama-3.3-70b-instruct",
|
| 721 |
]
|
| 722 |
for m in extras:
|
| 723 |
if m not in all_models:
|
| 724 |
all_models.append(m)
|
| 725 |
|
| 726 |
-
for model in all_models[:
|
| 727 |
tasks[asyncio.create_task(try_zenmux(model, messages))] = f"zenmux:{model.split('/')[-1]}"
|
| 728 |
|
| 729 |
-
# Pollinations
|
| 730 |
tasks[asyncio.create_task(try_pollinations(messages))] = "pollinations"
|
| 731 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 732 |
pending = set(tasks.keys())
|
| 733 |
try:
|
| 734 |
while pending:
|
|
@@ -757,90 +412,244 @@ async def race_all_models(messages: list, agent_models: List[str], timeout: floa
|
|
| 757 |
|
| 758 |
|
| 759 |
# ============================================================
|
| 760 |
-
#
|
| 761 |
# ============================================================
|
| 762 |
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 771 |
|
| 772 |
|
| 773 |
# ============================================================
|
| 774 |
# 7) MEMORY
|
| 775 |
# ============================================================
|
| 776 |
|
| 777 |
-
USER_MEMORY
|
| 778 |
|
| 779 |
|
| 780 |
-
def get_history(
|
| 781 |
-
return USER_MEMORY.get(
|
| 782 |
|
| 783 |
|
| 784 |
-
def add_history(
|
| 785 |
-
if
|
| 786 |
-
|
| 787 |
-
USER_MEMORY[
|
| 788 |
-
USER_MEMORY[user_id] = USER_MEMORY[user_id][-20:]
|
| 789 |
|
| 790 |
|
| 791 |
# ============================================================
|
| 792 |
# 8) معالجة الرسائل
|
| 793 |
# ============================================================
|
| 794 |
|
| 795 |
-
WELCOME = """🚀 مرحباً! أنا وكيل
|
| 796 |
|
| 797 |
-
⚡ **
|
| 798 |
-
• ردود جاهزة: < 0.
|
| 799 |
-
• مهارات محلية: < 0.
|
| 800 |
-
• كاش دلالي: < 0.
|
| 801 |
-
•
|
|
|
|
| 802 |
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
|
|
|
| 806 |
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
|
|
|
|
|
|
| 810 |
|
| 811 |
-
أرسل أي شيء!
|
| 812 |
-
/help - المساعدة"""
|
| 813 |
|
| 814 |
HELP_TEXT = """📋 **الأوامر:**
|
| 815 |
|
| 816 |
• /start - ترحيب
|
| 817 |
• /help - هذه القائمة
|
| 818 |
-
• /reset - مسح ذاكر
|
| 819 |
-
• /stats - إحصائيات
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
💡 جرّب: `مرحبا` ��و `اكتب كود Python` أو `احسب 15 * 23`"""
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
async def process_message(chat_id: int, user_id: str, user_name: str, text: str) -> dict:
|
| 844 |
start_time = time.time()
|
| 845 |
LOG.append(f"[{time.strftime('%H:%M:%S')}] {user_name}: {text[:60]}")
|
| 846 |
STATS["total"] += 1
|
|
@@ -853,109 +662,130 @@ async def process_message(chat_id: int, user_id: str, user_name: str, text: str)
|
|
| 853 |
elif cmd == "/help":
|
| 854 |
return {"method": "sendMessage", "chat_id": chat_id, "text": HELP_TEXT, "parse_mode": "Markdown"}
|
| 855 |
elif cmd == "/reset":
|
| 856 |
-
if user_id in USER_MEMORY:
|
| 857 |
-
del USER_MEMORY[user_id]
|
| 858 |
return {"method": "sendMessage", "chat_id": chat_id, "text": "✅ تم مسح ذاكرتي."}
|
| 859 |
elif cmd == "/stats":
|
| 860 |
cs = turbo_cache.stats()
|
| 861 |
-
return {
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
|
| 867 |
-
|
| 868 |
-
|
| 869 |
-
|
| 870 |
-
|
| 871 |
-
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
),
|
| 875 |
-
}
|
| 876 |
-
|
| 877 |
-
# 1) ردود جاهزة فورية
|
| 878 |
-
predefined = get_predefined(text)
|
| 879 |
-
if predefined:
|
| 880 |
elapsed = time.time() - start_time
|
| 881 |
-
LOG.append(f"[{time.strftime('%H:%M:%S')}] ⚡ predefined
|
| 882 |
-
return {"method": "sendMessage", "chat_id": chat_id, "text":
|
| 883 |
|
| 884 |
-
# 2) المهارات المحلية
|
| 885 |
skill_result = try_local_skills(text)
|
| 886 |
if skill_result:
|
| 887 |
elapsed = time.time() - start_time
|
| 888 |
-
LOG.append(f"[{time.strftime('%H:%M:%S')}] ⚡ skill in {elapsed:.3f}s")
|
| 889 |
return {"method": "sendMessage", "chat_id": chat_id, "text": skill_result, "parse_mode": "Markdown"}
|
| 890 |
|
| 891 |
-
# 3) الكاش
|
| 892 |
cached = turbo_cache.get(text)
|
| 893 |
if cached:
|
| 894 |
response, model = cached
|
| 895 |
elapsed = time.time() - start_time
|
| 896 |
STATS["cache_hits"] += 1
|
| 897 |
-
LOG.append(f"[{time.strftime('%H:%M:%S')}] 💾 cache
|
| 898 |
return {"method": "sendMessage", "chat_id": chat_id, "text": f"{response}\n\n💾 ({elapsed:.2f}s)"}
|
| 899 |
|
| 900 |
-
# 4)
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
|
| 905 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 906 |
history.append({"role": "user", "content": text})
|
| 907 |
-
messages = [{"role": "system", "content": agent
|
| 908 |
-
messages = compress_messages(messages)
|
| 909 |
|
| 910 |
-
# 6) سباق النماذج
|
| 911 |
LOG.append(f"[{time.strftime('%H:%M:%S')}] ⚡ racing models...")
|
| 912 |
STATS["llm_calls"] += 1
|
| 913 |
-
response, source, elapsed = await
|
| 914 |
|
| 915 |
if response is None:
|
| 916 |
STATS["failures"] += 1
|
| 917 |
-
LOG.append(f"[{time.strftime('%H:%M:%S')}] ❌ all failed
|
| 918 |
-
|
| 919 |
-
|
| 920 |
-
|
| 921 |
-
|
|
|
|
|
|
|
| 922 |
|
| 923 |
-
LOG.append(f"[{time.strftime('%H:%M:%S')}] ✅ {source}
|
| 924 |
|
| 925 |
-
#
|
| 926 |
turbo_cache.put(text, response, source)
|
| 927 |
add_history(user_id, "user", text)
|
| 928 |
add_history(user_id, "assistant", response)
|
| 929 |
|
| 930 |
-
#
|
| 931 |
-
|
| 932 |
-
agent_emoji = {"code": "🐍", "search": "🔍", "write": "✍️", "math": "🧮",
|
| 933 |
-
"translate": "🌐", "reasoning": "🧠", "creative": "🎨", "general": "💬"}.get(agent.name, "💬")
|
| 934 |
source_short = source.split(":")[-1] if ":" in source else source
|
| 935 |
-
|
| 936 |
-
|
| 937 |
-
return {"method": "sendMessage", "chat_id": chat_id, "text": final_text[:4096]}
|
| 938 |
|
| 939 |
|
| 940 |
# ============================================================
|
| 941 |
-
# 9) WEBHOOK
|
| 942 |
# ============================================================
|
| 943 |
|
| 944 |
async def handle_webhook(request):
|
| 945 |
try:
|
| 946 |
update = await request.json()
|
| 947 |
message = update.get("message")
|
| 948 |
-
if not message:
|
| 949 |
-
return web.json_response({})
|
| 950 |
-
|
| 951 |
chat_id = message["chat"]["id"]
|
| 952 |
text = message.get("text", "").strip()
|
| 953 |
user = message.get("from", {}).get("first_name", "صديق")
|
| 954 |
user_id = str(message.get("from", {}).get("id", "unknown"))
|
| 955 |
-
|
| 956 |
reply = await process_message(chat_id, user_id, user, text)
|
| 957 |
return web.json_response(reply)
|
| 958 |
-
|
| 959 |
except Exception as e:
|
| 960 |
LOG.append(f"[{time.strftime('%H:%M:%S')}] ERROR: {e}")
|
| 961 |
logger.error(f"webhook error: {e}\n{traceback.format_exc()}")
|
|
@@ -963,39 +793,29 @@ async def handle_webhook(request):
|
|
| 963 |
update = await request.json()
|
| 964 |
chat_id = update.get("message", {}).get("chat", {}).get("id", 0)
|
| 965 |
return web.json_response({"method": "sendMessage", "chat_id": chat_id, "text": f"❌ خطأ: {str(e)[:200]}"})
|
| 966 |
-
except
|
| 967 |
-
return web.json_response({})
|
| 968 |
|
| 969 |
|
| 970 |
async def health(request):
|
| 971 |
cs = turbo_cache.stats()
|
| 972 |
-
|
| 973 |
return web.Response(
|
| 974 |
-
text=(
|
| 975 |
-
|
| 976 |
-
|
| 977 |
-
|
| 978 |
-
|
| 979 |
-
f"• Local skills: {STATS['local_skills']}\n"
|
| 980 |
-
f"• LLM calls: {STATS['llm_calls']}\n"
|
| 981 |
-
f"• Failures: {STATS['failures']}\n"
|
| 982 |
-
f"• Users: {len(USER_MEMORY)}\n"
|
| 983 |
-
f"• Agents: {len(CREW)} | Skills: {len(SKILLS)}\n\n"
|
| 984 |
-
f"📋 Log:\n{log_text}"
|
| 985 |
-
),
|
| 986 |
-
content_type="text/plain",
|
| 987 |
-
)
|
| 988 |
|
| 989 |
|
| 990 |
async def set_webhook_startup(app):
|
| 991 |
LOG.append(f"[{time.strftime('%H:%M:%S')}] setting webhook...")
|
| 992 |
-
webhook_url = f"{SPACE_URL}{WEBHOOK_PATH}"
|
| 993 |
try:
|
| 994 |
timeout = aiohttp.ClientTimeout(total=15)
|
| 995 |
async with aiohttp.ClientSession(timeout=timeout) as session:
|
| 996 |
async with session.post(
|
| 997 |
f"https://api.telegram.org/bot{BOT_TOKEN}/setWebhook",
|
| 998 |
-
json={"url":
|
|
|
|
| 999 |
) as resp:
|
| 1000 |
data = await resp.json()
|
| 1001 |
LOG.append(f"setWebhook: {data.get('ok', False)}")
|
|
@@ -1013,15 +833,13 @@ def main():
|
|
| 1013 |
if not BOT_TOKEN:
|
| 1014 |
logger.error("No TELEGRAM_BOT_TOKEN!")
|
| 1015 |
sys.exit(1)
|
| 1016 |
-
|
| 1017 |
app = web.Application()
|
| 1018 |
app.router.add_post(WEBHOOK_PATH, handle_webhook)
|
| 1019 |
app.router.add_get("/", health)
|
| 1020 |
app.router.add_get("/log", health)
|
| 1021 |
app.on_startup.append(set_webhook_startup)
|
| 1022 |
app.on_cleanup.append(cleanup)
|
| 1023 |
-
|
| 1024 |
-
logger.info(f"🚀 Pro Bot v4.0 starting on port {PORT}")
|
| 1025 |
web.run_app(app, host="0.0.0.0", port=PORT, access_log=None)
|
| 1026 |
|
| 1027 |
|
|
|
|
| 1 |
"""
|
| 2 |
+
الوكيل v5.0 - وصول إنترنت + سرعة قصوى
|
| 3 |
+
========================================
|
| 4 |
+
|
| 5 |
+
الجديد:
|
| 6 |
+
1. Web Search مهارة - بحث حقيقي في الإنترنت (DuckDuckGo)
|
| 7 |
+
2. خبرة الإنترنت - يحلل صفحات الويب
|
| 8 |
+
3. نماذج Hugging Face Inference (مجانية تماماً)
|
| 9 |
+
4. تحسين سرعة Pollinations
|
| 10 |
+
5. نموذج Itty.chu - مجاني تماماً وسريع
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
"""
|
| 12 |
import asyncio
|
| 13 |
import json
|
|
|
|
| 20 |
import math
|
| 21 |
import traceback
|
| 22 |
import random
|
| 23 |
+
import base64
|
| 24 |
+
import urllib.parse
|
| 25 |
+
from typing import Optional, List, Dict
|
| 26 |
+
from datetime import datetime, timezone, timedelta
|
| 27 |
|
| 28 |
import aiohttp
|
| 29 |
from aiohttp import web
|
|
|
|
| 47 |
PORT = 7860
|
| 48 |
|
| 49 |
LOG = []
|
| 50 |
+
STATS = {"total": 0, "cache_hits": 0, "local_skills": 0, "web_search": 0,
|
| 51 |
+
"llm_calls": 0, "failures": 0}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
|
| 54 |
# ============================================================
|
| 55 |
+
# 1) TURBOVEC SEMANTIC CACHE
|
| 56 |
# ============================================================
|
| 57 |
|
| 58 |
class TurboCache:
|
| 59 |
+
def __init__(self, max_size=1000, sim_thresh=0.75):
|
| 60 |
+
self.cache = {}
|
| 61 |
self.max_size = max_size
|
| 62 |
+
self.sim_thresh = sim_thresh
|
| 63 |
self.hits = 0
|
| 64 |
self.misses = 0
|
| 65 |
self.stopwords = {
|
|
|
|
| 73 |
"and", "or", "but", "not", "no", "yes",
|
| 74 |
}
|
| 75 |
|
| 76 |
+
def _norm(self, t):
|
| 77 |
+
t = t.lower().strip()
|
| 78 |
+
t = re.sub(r"[^\w\s\u0600-\u06FF]", " ", t)
|
| 79 |
+
return re.sub(r"\s+", " ", t)
|
|
|
|
| 80 |
|
| 81 |
+
def _hash(self, t):
|
| 82 |
+
return hashlib.md5(self._norm(t).encode()).hexdigest()[:16]
|
| 83 |
|
| 84 |
+
def _kw(self, t):
|
| 85 |
+
return {w for w in set(self._norm(t).split())
|
| 86 |
+
if w not in self.stopwords and len(w) > 2}
|
| 87 |
|
| 88 |
@staticmethod
|
| 89 |
+
def _jac(a, b):
|
| 90 |
+
if not a or not b: return 0.0
|
|
|
|
| 91 |
return len(a & b) / len(a | b)
|
| 92 |
|
| 93 |
+
def get(self, q):
|
| 94 |
+
h = self._hash(q)
|
| 95 |
if h in self.cache:
|
| 96 |
+
e = self.cache[h]
|
| 97 |
+
if time.time() - e["time"] < 7200:
|
| 98 |
self.hits += 1
|
| 99 |
+
return e["response"], e["model"]
|
| 100 |
+
qk = self._kw(q)
|
| 101 |
+
if qk:
|
| 102 |
+
best, best_e = 0, None
|
| 103 |
+
for e in self.cache.values():
|
| 104 |
+
s = self._jac(qk, e.get("kw", set()))
|
| 105 |
+
if s > best:
|
| 106 |
+
best, best_e = s, e
|
| 107 |
+
if best_e and best >= self.sim_thresh and time.time() - best_e["time"] < 7200:
|
| 108 |
+
self.hits += 1
|
| 109 |
+
return best_e["response"], best_e["model"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
self.misses += 1
|
| 111 |
return None
|
| 112 |
|
| 113 |
+
def put(self, q, r, m):
|
| 114 |
+
h = self._hash(q)
|
| 115 |
if len(self.cache) >= self.max_size:
|
| 116 |
+
old = min(self.cache.items(), key=lambda x: x[1]["time"])
|
| 117 |
+
del self.cache[old[0]]
|
| 118 |
+
self.cache[h] = {"response": r, "model": m, "kw": self._kw(q), "time": time.time()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
+
def stats(self):
|
| 121 |
+
t = self.hits + self.misses
|
| 122 |
+
return {"size": len(self.cache), "hits": self.hits, "misses": self.misses,
|
| 123 |
+
"hit_rate": f"{(self.hits/t*100):.1f}%" if t else "0%"}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
|
| 126 |
+
turbo_cache = TurboCache()
|
| 127 |
|
| 128 |
|
| 129 |
# ============================================================
|
| 130 |
+
# 2) WEB SEARCH SKILL (وصول إنترنت حقيقي!)
|
| 131 |
# ============================================================
|
| 132 |
|
| 133 |
+
async def web_search_duckduckgo(query: str, max_results: int = 5) -> Optional[str]:
|
| 134 |
+
"""بحث حقيقي في الإنترنت عبر DuckDuckGo - مجاني، بدون مفتاح"""
|
| 135 |
+
session = await get_http_session()
|
| 136 |
+
try:
|
| 137 |
+
# DuckDuckGo Instant Answer API
|
| 138 |
+
params = {"q": query, "format": "json", "no_html": "1", "skip_disambig": "1"}
|
| 139 |
+
async with session.get("https://api.duckduckgo.com/", params=params, timeout=aiohttp.ClientTimeout(total=8)) as resp:
|
| 140 |
+
if resp.status != 200:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
return None
|
| 142 |
+
data = await resp.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
+
results = []
|
| 145 |
|
| 146 |
+
# 1) الإجابة الفورية
|
| 147 |
+
if data.get("AbstractText"):
|
| 148 |
+
results.append(f"📖 **{data.get('Heading', 'معلومة')}**\n{data['AbstractText']}")
|
| 149 |
+
if data.get("AbstractURL"):
|
| 150 |
+
results.append(f"🔗 المصدر: {data['AbstractURL']}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
+
# 2) المواضيع ذات الصلة
|
| 153 |
+
related = data.get("RelatedTopics", [])[:5]
|
| 154 |
+
for r in related:
|
| 155 |
+
if isinstance(r, dict) and r.get("Text"):
|
| 156 |
+
results.append(f"• {r['Text'][:200]}")
|
| 157 |
+
if r.get("FirstURL"):
|
| 158 |
+
results.append(f" 🔗 {r['FirstURL']}")
|
| 159 |
|
| 160 |
+
# 3) إذا لا توجد نتائج، استخدم HTML search
|
| 161 |
+
if not results:
|
| 162 |
+
return await web_search_html(query, session, max_results)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
+
return "🔍 **نتائج البحث في الإنترنت:**\n\n" + "\n\n".join(results[:8])
|
| 165 |
|
| 166 |
+
except Exception as e:
|
| 167 |
+
logger.error(f"DDG search error: {e}")
|
| 168 |
+
return None
|
|
|
|
| 169 |
|
|
|
|
|
|
|
| 170 |
|
| 171 |
+
async def web_search_html(query: str, session, max_results: int = 5) -> Optional[str]:
|
| 172 |
+
"""بحث HTML في DuckDuckGo (fallback)"""
|
| 173 |
+
try:
|
| 174 |
+
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
|
| 175 |
+
url = f"https://html.duckduckgo.com/html/?q={urllib.parse.quote(query)}"
|
| 176 |
+
async with session.get(url, headers=headers, timeout=aiohttp.ClientTimeout(total=10)) as resp:
|
| 177 |
+
if resp.status != 200:
|
| 178 |
+
return None
|
| 179 |
+
html = await resp.text()
|
| 180 |
+
|
| 181 |
+
# استخراج النتائج
|
| 182 |
+
results = []
|
| 183 |
+
# عناوين النتائج
|
| 184 |
+
titles = re.findall(r'<a[^>]*class="result__a"[^>]*>(.+?)</a>', html, re.DOTALL)[:5]
|
| 185 |
+
snippets = re.findall(r'<a[^>]*class="result__snippet"[^>]*>(.+?)</a>', html, re.DOTALL)[:5]
|
| 186 |
+
urls = re.findall(r'<a[^>]*class="result__url"[^>]*>(.+?)</a>', html, re.DOTALL)[:5]
|
| 187 |
+
|
| 188 |
+
for i in range(min(len(titles), max_results)):
|
| 189 |
+
title = re.sub(r"<[^>]+>", "", titles[i]).strip()
|
| 190 |
+
snippet = re.sub(r"<[^>]+>", "", snippets[i]).strip() if i < len(snippets) else ""
|
| 191 |
+
link = re.sub(r"<[^>]+>", "", urls[i]).strip() if i < len(urls) else ""
|
| 192 |
+
if title:
|
| 193 |
+
results.append(f"• **{title}**\n {snippet[:150]}\n 🔗 {link}")
|
| 194 |
+
|
| 195 |
+
if not results:
|
| 196 |
return None
|
| 197 |
+
return "🔍 **نتائج البحث:**\n\n" + "\n\n".join(results)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
+
except Exception as e:
|
| 200 |
+
logger.error(f"HTML search error: {e}")
|
| 201 |
+
return None
|
| 202 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
+
async def fetch_url_content(url: str, max_chars: int = 2000) -> Optional[str]:
|
| 205 |
+
"""قراءة محتوى صفحة ويب"""
|
| 206 |
+
session = await get_http_session()
|
| 207 |
+
try:
|
| 208 |
+
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
|
| 209 |
+
async with session.get(url, headers=headers, timeout=aiohttp.ClientTimeout(total=10)) as resp:
|
| 210 |
+
if resp.status != 200:
|
| 211 |
+
return None
|
| 212 |
+
html = await resp.text()
|
| 213 |
+
# إزالة الوسوم
|
| 214 |
+
html = re.sub(r"<script[^>]*>.*?</script>", "", html, flags=re.DOTALL | re.IGNORECASE)
|
| 215 |
+
html = re.sub(r"<style[^>]*>.*?</style>", "", html, flags=re.DOTALL | re.IGNORECASE)
|
| 216 |
+
html = re.sub(r"<[^>]+>", " ", html)
|
| 217 |
+
html = re.sub(r"\s+", " ", html).strip()
|
| 218 |
+
# استخراج العنوان
|
| 219 |
+
title_match = re.search(r"<title[^>]*>(.+?)</title>", html, re.IGNORECASE)
|
| 220 |
+
title = title_match.group(1).strip() if title_match else ""
|
| 221 |
+
content = html[:max_chars]
|
| 222 |
+
return f"📄 **{title}**\n\n{content}" if title else content
|
| 223 |
+
except Exception:
|
| 224 |
+
return None
|
| 225 |
|
|
|
|
|
|
|
|
|
|
| 226 |
|
| 227 |
+
def is_web_search_request(text: str) -> bool:
|
| 228 |
+
"""كشف ما إذا كان الطلب يتطلب بحثاً في الإنترنت"""
|
| 229 |
+
text_l = text.lower()
|
| 230 |
+
keywords = [
|
| 231 |
+
"ابحث عن", "بحث", "search", "google", "اخر اخبار", "latest news",
|
| 232 |
+
"ما الجديد", "whats new", "today", "الآن", "now", "current",
|
| 233 |
+
"2024", "2025", "2026", "recent", "حديث", "latest", "تحديث",
|
| 234 |
+
"live", "مباشر", "url", "رابط", "link", "اقرأ", "read",
|
| 235 |
+
]
|
| 236 |
+
return any(k in text_l for k in keywords)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
|
| 239 |
+
def extract_url(text: str) -> Optional[str]:
|
| 240 |
+
"""استخراج URL من النص"""
|
| 241 |
+
match = re.search(r'https?://[^\s<>"\']+', text)
|
| 242 |
+
return match.group(0) if match else None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
|
| 244 |
|
| 245 |
# ============================================================
|
| 246 |
+
# 3) LLM PROVIDERS (متعددة للسرعة القصوى)
|
| 247 |
# ============================================================
|
| 248 |
|
| 249 |
HTTP_SESSION = None
|
|
|
|
| 253 |
global HTTP_SESSION
|
| 254 |
if HTTP_SESSION is None or HTTP_SESSION.closed:
|
| 255 |
connector = aiohttp.TCPConnector(
|
| 256 |
+
limit=100, limit_per_host=30, keepalive_timeout=120,
|
| 257 |
enable_cleanup_closed=True,
|
| 258 |
)
|
| 259 |
+
timeout = aiohttp.ClientTimeout(total=20, connect=5, sock_read=15)
|
| 260 |
HTTP_SESSION = aiohttp.ClientSession(timeout=timeout, connector=connector)
|
| 261 |
return HTTP_SESSION
|
| 262 |
|
|
|
|
| 265 |
if not ZENMUX_KEY:
|
| 266 |
return None
|
| 267 |
session = await get_http_session()
|
| 268 |
+
try:
|
| 269 |
+
async with session.post(
|
| 270 |
+
"https://zenmux.ai/api/v1/chat/completions",
|
| 271 |
+
headers={"Authorization": f"Bearer {ZENMUX_KEY}", "Content-Type": "application/json"},
|
| 272 |
+
json={"model": model, "messages": messages, "max_tokens": 1200, "temperature": 0.7},
|
| 273 |
+
) as resp:
|
| 274 |
+
if resp.status == 200:
|
| 275 |
+
data = await resp.json()
|
| 276 |
+
content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
|
| 277 |
+
if content and content.strip():
|
| 278 |
+
return content.strip()
|
| 279 |
+
return None
|
| 280 |
+
except Exception:
|
| 281 |
+
return None
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
async def try_pollinations(messages: list) -> Optional[str]:
|
| 285 |
+
"""Pollinations - مجاني دائماً"""
|
| 286 |
+
session = await get_http_session()
|
| 287 |
+
models = ["openai", "mistral", "llama", "qwen-coder"]
|
| 288 |
+
for model in models:
|
| 289 |
try:
|
| 290 |
async with session.post(
|
| 291 |
+
"https://text.pollinations.ai/openai",
|
| 292 |
+
json={"model": model, "messages": messages, "max_tokens": 1200},
|
|
|
|
| 293 |
) as resp:
|
| 294 |
if resp.status == 200:
|
| 295 |
data = await resp.json()
|
| 296 |
content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
|
| 297 |
if content and content.strip():
|
| 298 |
return content.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
except Exception:
|
| 300 |
+
continue
|
|
|
|
|
|
|
|
|
|
| 301 |
return None
|
| 302 |
|
| 303 |
|
| 304 |
+
async def try_pollinations_get(prompt: str) -> Optional[str]:
|
| 305 |
+
"""Pollinations GET endpoint - الأسرع"""
|
| 306 |
session = await get_http_session()
|
| 307 |
+
try:
|
| 308 |
+
# GET endpoint أسرع بكثير
|
| 309 |
+
encoded = urllib.parse.quote(prompt[:500])
|
| 310 |
+
async with session.get(
|
| 311 |
+
f"https://text.pollinations.ai/{encoded}?model=openai",
|
| 312 |
+
timeout=aiohttp.ClientTimeout(total=10),
|
| 313 |
+
) as resp:
|
| 314 |
+
if resp.status == 200:
|
| 315 |
+
content = await resp.text()
|
| 316 |
+
if content and content.strip() and len(content.strip()) > 5:
|
| 317 |
+
return content.strip()
|
| 318 |
+
except Exception:
|
| 319 |
+
pass
|
| 320 |
+
return None
|
| 321 |
|
| 322 |
+
|
| 323 |
+
async def try_itty_chu(messages: list) -> Optional[str]:
|
| 324 |
+
"""Itty.chu - API مجاني وسريع"""
|
| 325 |
+
session = await get_http_session()
|
| 326 |
+
try:
|
| 327 |
+
# تحويل الرسائل لـ prompt
|
| 328 |
+
prompt = ""
|
| 329 |
+
for m in messages:
|
| 330 |
+
if m["role"] == "user":
|
| 331 |
+
prompt += f"User: {m['content']}\n"
|
| 332 |
+
elif m["role"] == "assistant":
|
| 333 |
+
prompt += f"Assistant: {m['content']}\n"
|
| 334 |
+
elif m["role"] == "system":
|
| 335 |
+
prompt = f"System: {m['content']}\n" + prompt
|
| 336 |
+
prompt += "Assistant:"
|
| 337 |
+
|
| 338 |
+
async with session.post(
|
| 339 |
+
"https://api.itty.chu.ai/v1/chat/completions",
|
| 340 |
+
json={"model": "default", "messages": messages, "max_tokens": 1000},
|
| 341 |
+
timeout=aiohttp.ClientTimeout(total=10),
|
| 342 |
+
) as resp:
|
| 343 |
+
if resp.status == 200:
|
| 344 |
+
data = await resp.json()
|
| 345 |
+
content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
|
| 346 |
+
if content and content.strip():
|
| 347 |
+
return content.strip()
|
| 348 |
+
except Exception:
|
| 349 |
+
pass
|
| 350 |
return None
|
| 351 |
|
| 352 |
|
| 353 |
+
async def race_models(messages: list, agent_models: List[str], timeout: float = 8.0) -> tuple:
|
| 354 |
+
"""سباق كل المصادر بالتوازي - أسرع رد يفوز"""
|
| 355 |
start = time.time()
|
| 356 |
tasks = {}
|
| 357 |
|
| 358 |
+
# ZenMux نماذج
|
| 359 |
all_models = agent_models.copy()
|
| 360 |
extras = [
|
| 361 |
+
"z-ai/glm-4.7-flash-free", "stepfun/step-3.7-flash-free",
|
| 362 |
+
"deepseek/deepseek-chat", "z-ai/glm-5.2", "z-ai/glm-5-turbo",
|
|
|
|
|
|
|
| 363 |
]
|
| 364 |
for m in extras:
|
| 365 |
if m not in all_models:
|
| 366 |
all_models.append(m)
|
| 367 |
|
| 368 |
+
for model in all_models[:8]:
|
| 369 |
tasks[asyncio.create_task(try_zenmux(model, messages))] = f"zenmux:{model.split('/')[-1]}"
|
| 370 |
|
| 371 |
+
# Pollinations POST
|
| 372 |
tasks[asyncio.create_task(try_pollinations(messages))] = "pollinations"
|
| 373 |
|
| 374 |
+
# Pollinations GET (أسرع) - للرسائل بدون سياق
|
| 375 |
+
if len(messages) <= 2:
|
| 376 |
+
last_user = ""
|
| 377 |
+
for m in reversed(messages):
|
| 378 |
+
if m["role"] == "user":
|
| 379 |
+
last_user = m["content"]
|
| 380 |
+
break
|
| 381 |
+
if last_user:
|
| 382 |
+
tasks[asyncio.create_task(try_pollinations_get(last_user))] = "pollinations-get"
|
| 383 |
+
|
| 384 |
+
# Itty.chu
|
| 385 |
+
tasks[asyncio.create_task(try_itty_chu(messages))] = "itty"
|
| 386 |
+
|
| 387 |
pending = set(tasks.keys())
|
| 388 |
try:
|
| 389 |
while pending:
|
|
|
|
| 412 |
|
| 413 |
|
| 414 |
# ============================================================
|
| 415 |
+
# 4) LOCAL SKILLS (مهارات فورية)
|
| 416 |
# ============================================================
|
| 417 |
|
| 418 |
+
class CalculatorSkill:
|
| 419 |
+
name = "calculator"
|
| 420 |
+
def matches(self, text):
|
| 421 |
+
if not re.search(r"\d", text): return False
|
| 422 |
+
cleaned = re.sub(r"(احسب|calculate|كم|يساوي|\?|\؟)", "", text, flags=re.IGNORECASE).strip()
|
| 423 |
+
return bool(re.match(r"^[\d\s\+\-\*\/\(\)\.\^\%]+$", cleaned))
|
| 424 |
+
def execute(self, text):
|
| 425 |
+
cleaned = re.sub(r"(احسب|calculate|كم|يساوي|\?|\؟)", "", text, flags=re.IGNORECASE).strip()
|
| 426 |
+
cleaned = cleaned.replace("^", "**").replace("%", "/100")
|
| 427 |
+
if not re.match(r"^[\d\s\+\-\*\/\(\)\.]+$", cleaned): return None
|
| 428 |
+
try:
|
| 429 |
+
result = eval(cleaned, {"__builtins__": {}}, {})
|
| 430 |
+
return f"🧮 **{text}** = **{result}**"
|
| 431 |
+
except: return None
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
class TimeSkill:
|
| 435 |
+
name = "time"
|
| 436 |
+
def matches(self, text):
|
| 437 |
+
return bool(re.search(r"(الوقت|time|الساعة|التاريخ|date|اليوم|today)", text, re.IGNORECASE)) and len(text) < 30
|
| 438 |
+
def execute(self, text):
|
| 439 |
+
tz = timezone(timedelta(hours=3))
|
| 440 |
+
now = datetime.now(tz)
|
| 441 |
+
days_ar = ["الإثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت", "الأحد"]
|
| 442 |
+
months_ar = ["يناير", "فبراير", "مارس", "أبريل", "مايو", "يونيو", "يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر"]
|
| 443 |
+
return (f"⏰ **التاريخ والوقت** (توقيت السعودية)\n\n"
|
| 444 |
+
f"📅 {days_ar[now.weekday()]}، {now.day} {months_ar[now.month-1]} {now.year}\n"
|
| 445 |
+
f"🕐 {now.strftime('%H:%M:%S')}")
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
class CurrencySkill:
|
| 449 |
+
name = "currency"
|
| 450 |
+
RATES = {"usd_sar": 3.75, "sar_usd": 0.267, "usd_eur": 0.92, "eur_usd": 1.09}
|
| 451 |
+
def matches(self, text):
|
| 452 |
+
text_l = text.lower()
|
| 453 |
+
return bool(re.search(r"\d", text)) and any(k in text_l for k in ["دولار", "ريال", "يورو", "usd", "sar", "eur"]) and len(text) < 80
|
| 454 |
+
def execute(self, text):
|
| 455 |
+
text_l = text.lower()
|
| 456 |
+
amt = re.search(r"(\d+(?:\.\d+)?)", text)
|
| 457 |
+
if not amt: return None
|
| 458 |
+
amount = float(amt.group(1))
|
| 459 |
+
from_c = "USD" if any(k in text_l for k in ["usd", "دولار"]) else "SAR" if any(k in text_l for k in ["sar", "ريال"]) else None
|
| 460 |
+
to_c = "SAR" if from_c == "USD" else "USD" if from_c == "SAR" else None
|
| 461 |
+
if "eur" in text_l or "يورو" in text_l: to_c = "EUR"
|
| 462 |
+
if not from_c or not to_c: return None
|
| 463 |
+
rate = self.RATES.get(f"{from_c.lower()}_{to_c.lower()}")
|
| 464 |
+
if not rate: return None
|
| 465 |
+
syms = {"USD": "$", "SAR": "ر.س", "EUR": "€"}
|
| 466 |
+
return f"💱 **تحويل العملة**\n\n{amount} {syms[from_c]} = **{amount*rate:.2f} {syms[to_c]}**\n_(سعر تقريبي)_"
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
class RandomSkill:
|
| 470 |
+
name = "random"
|
| 471 |
+
def matches(self, text):
|
| 472 |
+
return bool(re.search(r"(رقم عشوائي|random|ارمي|نرد|dice)", text, re.IGNORECASE)) and len(text) < 50
|
| 473 |
+
def execute(self, text):
|
| 474 |
+
text_l = text.lower()
|
| 475 |
+
if "dice" in text_l or "نرد" in text_l:
|
| 476 |
+
return f"🎲 النرد: **{random.randint(1, 6)}**"
|
| 477 |
+
nums = re.findall(r"\d+", text)
|
| 478 |
+
if len(nums) >= 2:
|
| 479 |
+
a, b = sorted([int(nums[0]), int(nums[1])])
|
| 480 |
+
return f"🎲 رقم عشوائي بين {a} و {b}: **{random.randint(a, b)}**"
|
| 481 |
+
return f"🎲 رقم عشوائي: **{random.randint(1, 100)}**"
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
class Base64Skill:
|
| 485 |
+
name = "base64"
|
| 486 |
+
def matches(self, text):
|
| 487 |
+
return bool(re.search(r"(base64|encode|decode|تشفير|فك تشفير)", text, re.IGNORECASE)) and len(text) < 300
|
| 488 |
+
def execute(self, text):
|
| 489 |
+
text_l = text.lower()
|
| 490 |
+
match = re.search(r"(?:base64|encode|decode|تشفير|فك تشفير)[:\s]*(.+)", text, re.IGNORECASE)
|
| 491 |
+
if not match: return None
|
| 492 |
+
target = match.group(1).strip()
|
| 493 |
+
try:
|
| 494 |
+
if "decode" in text_l or "فك" in text_l:
|
| 495 |
+
return f"🔐 **فك تشفير:**\n\n`{base64.b64decode(target).decode('utf-8', errors='replace')}`"
|
| 496 |
+
return f"🔐 **تشفير:**\n\n`{base64.b64encode(target.encode()).decode()}`"
|
| 497 |
+
except Exception as e: return f"❌ خطأ: {e}"
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
SKILLS = [CalculatorSkill(), TimeSkill(), CurrencySkill(), RandomSkill(), Base64Skill()]
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def try_local_skills(text):
|
| 504 |
+
for skill in SKILLS:
|
| 505 |
+
try:
|
| 506 |
+
if skill.matches(text):
|
| 507 |
+
result = skill.execute(text)
|
| 508 |
+
if result:
|
| 509 |
+
LOG.append(f"[{time.strftime('%H:%M:%S')}] ⚡ skill: {skill.name}")
|
| 510 |
+
STATS["local_skills"] += 1
|
| 511 |
+
return result
|
| 512 |
+
except: pass
|
| 513 |
+
return None
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
# ============================================================
|
| 517 |
+
# 5) AGENTS
|
| 518 |
+
# ============================================================
|
| 519 |
+
|
| 520 |
+
AGENTS = {
|
| 521 |
+
"code": {
|
| 522 |
+
"prompt": "أنت خبير برمجة. اكتب كوداً نظيفاً مع شرح مختصر. استخدم Markdown.",
|
| 523 |
+
"models": ["deepseek/deepseek-chat", "qwen/qwen3-coder-plus", "z-ai/glm-4.7-flash-free"],
|
| 524 |
+
"keywords": ["كود", "code", "function", "دالة", "برنامج", "python", "javascript", "java", "bug", "debug"],
|
| 525 |
+
},
|
| 526 |
+
"search": {
|
| 527 |
+
"prompt": "أنت باحث خبير. قدم معلومات دقيقة وشاملة. نظّم بعناوين فرعية.",
|
| 528 |
+
"models": ["z-ai/glm-4.7-flash-free", "deepseek/deepseek-chat"],
|
| 529 |
+
"keywords": ["ما هو", "ما هي", "what is", "عرف", "اشرح", "explain", "اخبرني", "معلومات"],
|
| 530 |
+
},
|
| 531 |
+
"write": {
|
| 532 |
+
"prompt": "أنت كاتب مبدع. اكتب محتوى جذاباً ومنظماً.",
|
| 533 |
+
"models": ["z-ai/glm-4.7-flash-free", "deepseek/deepseek-chat"],
|
| 534 |
+
"keywords": ["اكتب", "write", "مقال", "article", "قصة", "story", "poem", "قصيدة"],
|
| 535 |
+
},
|
| 536 |
+
"translate": {
|
| 537 |
+
"prompt": "أنت مترجم محترف. ترجم بدقة.",
|
| 538 |
+
"models": ["z-ai/glm-4.7-flash-free"],
|
| 539 |
+
"keywords": ["ترجم", "translate", "بالإنجليزية", "بالعربية"],
|
| 540 |
+
},
|
| 541 |
+
"general": {
|
| 542 |
+
"prompt": "أنت مساعد ذكي. أجب بالعربية الفصحى المبسطة. كن دقيقاً ومباشراً.",
|
| 543 |
+
"models": ["z-ai/glm-4.7-flash-free", "deepseek/deepseek-chat"],
|
| 544 |
+
"keywords": [],
|
| 545 |
+
},
|
| 546 |
+
}
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def select_agent(text):
|
| 550 |
+
text_l = text.lower()
|
| 551 |
+
best, best_score = "general", 0
|
| 552 |
+
for name, agent in AGENTS.items():
|
| 553 |
+
score = sum(1 for k in agent["keywords"] if k in text_l) * 30
|
| 554 |
+
if score > best_score:
|
| 555 |
+
best, best_score = name, score
|
| 556 |
+
return best, AGENTS[best]
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
# ============================================================
|
| 560 |
+
# 6) PREDEFINED RESPONSES
|
| 561 |
+
# ============================================================
|
| 562 |
+
|
| 563 |
+
PREDEFINED = {
|
| 564 |
+
"مرحبا": "مرحباً بك! 👋 كيف يمكنني مساعدتك؟",
|
| 565 |
+
"اهلا": "أهلاً وسهلاً! 😊",
|
| 566 |
+
"السلام عليكم": "وعليكم السلام ورحمة الله 🌟",
|
| 567 |
+
"سلام": "سلام! كيف حالك؟",
|
| 568 |
+
"hi": "Hello! 😊", "hello": "Hi there! 👋", "hey": "Hey!",
|
| 569 |
+
"شكرا": "العفو! 🙏", "شكراً": "العفو! 🙏", "thanks": "You're welcome!",
|
| 570 |
+
"باي": "إلى اللقاء! 👋", "وداعا": "في أمان الله 🌟", "bye": "Goodbye!",
|
| 571 |
+
"من انت": "🤖 أنا وكيل ذري بـ 5 وكلاء + مهارات محلية + بحث إنترنت!",
|
| 572 |
+
"من أنت": "🤖 أنا وكيل ذري بـ 5 وكلاء + مهارات محلية + بحث إنترنت!",
|
| 573 |
+
"ماذا تستطيع": "🚀 أستطيع:\n• الإجابة على الأسئلة\n• كتابة الكود\n• البحث في الإنترنت\n• الترجمة\n• الرياضيات\n• والكثير! /help",
|
| 574 |
+
}
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
def get_predefined(text):
|
| 578 |
+
norm = text.lower().strip()
|
| 579 |
+
if norm in PREDEFINED: return PREDEFINED[norm]
|
| 580 |
+
for k, v in PREDEFINED.items():
|
| 581 |
+
if norm.startswith(k) and len(norm) < len(k) + 15: return v
|
| 582 |
+
return None
|
| 583 |
|
| 584 |
|
| 585 |
# ============================================================
|
| 586 |
# 7) MEMORY
|
| 587 |
# ============================================================
|
| 588 |
|
| 589 |
+
USER_MEMORY = {}
|
| 590 |
|
| 591 |
|
| 592 |
+
def get_history(uid, limit=6):
|
| 593 |
+
return USER_MEMORY.get(uid, [])[-limit:]
|
| 594 |
|
| 595 |
|
| 596 |
+
def add_history(uid, role, content):
|
| 597 |
+
if uid not in USER_MEMORY: USER_MEMORY[uid] = []
|
| 598 |
+
USER_MEMORY[uid].append({"role": role, "content": content})
|
| 599 |
+
USER_MEMORY[uid] = USER_MEMORY[uid][-20:]
|
|
|
|
| 600 |
|
| 601 |
|
| 602 |
# ============================================================
|
| 603 |
# 8) معالجة الرسائل
|
| 604 |
# ============================================================
|
| 605 |
|
| 606 |
+
WELCOME = """🚀 مرحباً! أنا الوكيل v5.0
|
| 607 |
|
| 608 |
+
⚡ **سرعة فائقة:**
|
| 609 |
+
• ردود جاهزة: < 0.1s
|
| 610 |
+
• مهارات محلية: < 0.1s
|
| 611 |
+
• كاش دلالي: < 0.05s
|
| 612 |
+
• بحث إنترنت: 2-4s
|
| 613 |
+
• ردود LLM: 2-5s
|
| 614 |
|
| 615 |
+
🌐 **وصول إنترنت حقيقي!**
|
| 616 |
+
• بحث في الويب
|
| 617 |
+
• قراءة الروابط
|
| 618 |
+
• معلومات محدثة
|
| 619 |
|
| 620 |
+
🧠 **5 وكلاء + 5 مهارات:**
|
| 621 |
+
🐍 Code | 🔍 Search | ✍️ Write | 🌐 Translate | 💬 General
|
| 622 |
+
🧮 Math | ⏰ Time | 💱 Currency | 🎲 Random | 🔐 Base64
|
| 623 |
+
|
| 624 |
+
أرسل: /help"""
|
| 625 |
|
|
|
|
|
|
|
| 626 |
|
| 627 |
HELP_TEXT = """📋 **الأوامر:**
|
| 628 |
|
| 629 |
• /start - ترحيب
|
| 630 |
• /help - هذه القائمة
|
| 631 |
+
• /reset - مسح الذاكرة
|
| 632 |
+
• /stats - الإحصائيات
|
| 633 |
+
|
| 634 |
+
🌐 **وصول الإنترنت:**
|
| 635 |
+
• `ابحث عن: أحدث أخبار الذكاء الاصطناعي`
|
| 636 |
+
• `اقرأ هذا الرابط: https://example.com`
|
| 637 |
+
• `ما الجديد في التقنية؟`
|
| 638 |
+
|
| 639 |
+
⚡ **مهارات محلية (فورية):**
|
| 640 |
+
• `احسب 15 * 23` - حاسبة
|
| 641 |
+
• `الوقت` - التاريخ والساعة
|
| 642 |
+
• `100 دولار كم ريال` - عملات
|
| 643 |
+
• `رقم عشوائي بين 1 و 100` - عشوائي
|
| 644 |
+
• `base64: نصك` - تشفير
|
| 645 |
+
|
| 646 |
+
🧠 **الوكلاء:**
|
| 647 |
+
🐍 Code | 🔍 Search | ✍️ Write | 🌐 Translate | 💬 General
|
| 648 |
+
|
| 649 |
+
💡 جرّب: `ابحث عن الذكاء الاصطناعي`"""
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
async def process_message(chat_id, user_id, user_name, text):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 653 |
start_time = time.time()
|
| 654 |
LOG.append(f"[{time.strftime('%H:%M:%S')}] {user_name}: {text[:60]}")
|
| 655 |
STATS["total"] += 1
|
|
|
|
| 662 |
elif cmd == "/help":
|
| 663 |
return {"method": "sendMessage", "chat_id": chat_id, "text": HELP_TEXT, "parse_mode": "Markdown"}
|
| 664 |
elif cmd == "/reset":
|
| 665 |
+
if user_id in USER_MEMORY: del USER_MEMORY[user_id]
|
|
|
|
| 666 |
return {"method": "sendMessage", "chat_id": chat_id, "text": "✅ تم مسح ذاكرتي."}
|
| 667 |
elif cmd == "/stats":
|
| 668 |
cs = turbo_cache.stats()
|
| 669 |
+
return {"method": "sendMessage", "chat_id": chat_id, "parse_mode": "Markdown",
|
| 670 |
+
"text": (f"📊 **إحصائيات v5.0**\n\n"
|
| 671 |
+
f"• إجمالي: {STATS['total']}\n"
|
| 672 |
+
f"• Cache: {STATS['cache_hits']} ({cs['hit_rate']})\n"
|
| 673 |
+
f"• مهارات: {STATS['local_skills']}\n"
|
| 674 |
+
f"• بحث ويب: {STATS['web_search']}\n"
|
| 675 |
+
f"• LLM: {STATS['llm_calls']}\n"
|
| 676 |
+
f"• فشل: {STATS['failures']}\n"
|
| 677 |
+
f"• المستخدمون: {len(USER_MEMORY)}")}
|
| 678 |
+
|
| 679 |
+
# 1) ردود جاهزة
|
| 680 |
+
pred = get_predefined(text)
|
| 681 |
+
if pred:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 682 |
elapsed = time.time() - start_time
|
| 683 |
+
LOG.append(f"[{time.strftime('%H:%M:%S')}] ⚡ predefined {elapsed:.3f}s")
|
| 684 |
+
return {"method": "sendMessage", "chat_id": chat_id, "text": pred}
|
| 685 |
|
| 686 |
+
# 2) المهارات المحلية
|
| 687 |
skill_result = try_local_skills(text)
|
| 688 |
if skill_result:
|
| 689 |
elapsed = time.time() - start_time
|
|
|
|
| 690 |
return {"method": "sendMessage", "chat_id": chat_id, "text": skill_result, "parse_mode": "Markdown"}
|
| 691 |
|
| 692 |
+
# 3) الكاش
|
| 693 |
cached = turbo_cache.get(text)
|
| 694 |
if cached:
|
| 695 |
response, model = cached
|
| 696 |
elapsed = time.time() - start_time
|
| 697 |
STATS["cache_hits"] += 1
|
| 698 |
+
LOG.append(f"[{time.strftime('%H:%M:%S')}] 💾 cache {elapsed:.3f}s")
|
| 699 |
return {"method": "sendMessage", "chat_id": chat_id, "text": f"{response}\n\n💾 ({elapsed:.2f}s)"}
|
| 700 |
|
| 701 |
+
# 4) قراءة رابط (URL)
|
| 702 |
+
url = extract_url(text)
|
| 703 |
+
if url and ("اقرأ" in text or "read" in text.lower() or text.strip().startswith("http")):
|
| 704 |
+
LOG.append(f"[{time.strftime('%H:%M:%S')}] 🌐 fetching URL: {url[:50]}")
|
| 705 |
+
STATS["web_search"] += 1
|
| 706 |
+
content = await fetch_url_content(url)
|
| 707 |
+
if content:
|
| 708 |
+
# لخّص المحتوى عبر LLM
|
| 709 |
+
agent_name, agent = select_agent(text)
|
| 710 |
+
messages = [
|
| 711 |
+
{"role": "system", "content": "لخّص المحتوى التالي في نقاط مختصرة بالعربية:"},
|
| 712 |
+
{"role": "user", "content": content[:3000]},
|
| 713 |
+
]
|
| 714 |
+
summary, source, elapsed = await race_models(messages, agent["models"], timeout=10)
|
| 715 |
+
if summary:
|
| 716 |
+
elapsed_total = time.time() - start_time
|
| 717 |
+
return {"method": "sendMessage", "chat_id": chat_id,
|
| 718 |
+
"text": f"📄 **ملخص المحتوى:**\n\n{summary}\n\n🌐 ({elapsed_total:.1f}s)"}
|
| 719 |
+
else:
|
| 720 |
+
return {"method": "sendMessage", "chat_id": chat_id,
|
| 721 |
+
"text": content[:3000]}
|
| 722 |
+
|
| 723 |
+
# 5) بحث في الإنترنت
|
| 724 |
+
if is_web_search_request(text):
|
| 725 |
+
LOG.append(f"[{time.strftime('%H:%M:%S')}] 🌐 web search")
|
| 726 |
+
STATS["web_search"] += 1
|
| 727 |
+
# استخراج استعلام البحث
|
| 728 |
+
query = re.sub(r"(ابحث عن|بحث|search|google|اخر اخبار|ما الجديد)\s*:?\s*", "", text, flags=re.IGNORECASE).strip()
|
| 729 |
+
if not query:
|
| 730 |
+
query = text
|
| 731 |
+
|
| 732 |
+
search_result = await web_search_duckduckgo(query)
|
| 733 |
+
if search_result:
|
| 734 |
+
elapsed = time.time() - start_time
|
| 735 |
+
LOG.append(f"[{time.strftime('%H:%M:%S')}] ✅ web search {elapsed:.1f}s")
|
| 736 |
+
return {"method": "sendMessage", "chat_id": chat_id, "text": search_result[:4000], "parse_mode": "Markdown"}
|
| 737 |
+
|
| 738 |
+
# 6) اختيار الوكيل وسباق النماذج
|
| 739 |
+
agent_name, agent = select_agent(text)
|
| 740 |
+
LOG.append(f"[{time.strftime('%H:%M:%S')}] 🎯 agent: {agent_name}")
|
| 741 |
+
|
| 742 |
+
history = get_history(user_id, limit=6)
|
| 743 |
history.append({"role": "user", "content": text})
|
| 744 |
+
messages = [{"role": "system", "content": agent["prompt"]}] + history
|
|
|
|
| 745 |
|
|
|
|
| 746 |
LOG.append(f"[{time.strftime('%H:%M:%S')}] ⚡ racing models...")
|
| 747 |
STATS["llm_calls"] += 1
|
| 748 |
+
response, source, elapsed = await race_models(messages, agent["models"], timeout=10)
|
| 749 |
|
| 750 |
if response is None:
|
| 751 |
STATS["failures"] += 1
|
| 752 |
+
LOG.append(f"[{time.strftime('%H:%M:%S')}] ❌ all failed {elapsed:.1f}s")
|
| 753 |
+
# محاولة أخيرة: بحث في الإنترنت
|
| 754 |
+
search_result = await web_search_duckduckgo(text)
|
| 755 |
+
if search_result:
|
| 756 |
+
return {"method": "sendMessage", "chat_id": chat_id, "text": search_result[:4000], "parse_mode": "Markdown"}
|
| 757 |
+
return {"method": "sendMessage", "chat_id": chat_id,
|
| 758 |
+
"text": f"⏳ النماذج مشغولة. أعد المحاولة.\n({elapsed:.1f}s)"}
|
| 759 |
|
| 760 |
+
LOG.append(f"[{time.strftime('%H:%M:%S')}] ✅ {source} {elapsed:.1f}s")
|
| 761 |
|
| 762 |
+
# حفظ
|
| 763 |
turbo_cache.put(text, response, source)
|
| 764 |
add_history(user_id, "user", text)
|
| 765 |
add_history(user_id, "assistant", response)
|
| 766 |
|
| 767 |
+
# إرسال
|
| 768 |
+
emoji = "⚡" if elapsed < 3 else "🚀" if elapsed < 6 else "⏱️"
|
|
|
|
|
|
|
| 769 |
source_short = source.split(":")[-1] if ":" in source else source
|
| 770 |
+
final = response + f"\n\n{emoji} ({elapsed:.1f}s - {source_short})"
|
| 771 |
+
return {"method": "sendMessage", "chat_id": chat_id, "text": final[:4096]}
|
|
|
|
| 772 |
|
| 773 |
|
| 774 |
# ============================================================
|
| 775 |
+
# 9) WEBHOOK
|
| 776 |
# ============================================================
|
| 777 |
|
| 778 |
async def handle_webhook(request):
|
| 779 |
try:
|
| 780 |
update = await request.json()
|
| 781 |
message = update.get("message")
|
| 782 |
+
if not message: return web.json_response({})
|
|
|
|
|
|
|
| 783 |
chat_id = message["chat"]["id"]
|
| 784 |
text = message.get("text", "").strip()
|
| 785 |
user = message.get("from", {}).get("first_name", "صديق")
|
| 786 |
user_id = str(message.get("from", {}).get("id", "unknown"))
|
|
|
|
| 787 |
reply = await process_message(chat_id, user_id, user, text)
|
| 788 |
return web.json_response(reply)
|
|
|
|
| 789 |
except Exception as e:
|
| 790 |
LOG.append(f"[{time.strftime('%H:%M:%S')}] ERROR: {e}")
|
| 791 |
logger.error(f"webhook error: {e}\n{traceback.format_exc()}")
|
|
|
|
| 793 |
update = await request.json()
|
| 794 |
chat_id = update.get("message", {}).get("chat", {}).get("id", 0)
|
| 795 |
return web.json_response({"method": "sendMessage", "chat_id": chat_id, "text": f"❌ خطأ: {str(e)[:200]}"})
|
| 796 |
+
except: return web.json_response({})
|
|
|
|
| 797 |
|
| 798 |
|
| 799 |
async def health(request):
|
| 800 |
cs = turbo_cache.stats()
|
| 801 |
+
log = "\n".join(LOG[-15:]) if LOG else "No activity"
|
| 802 |
return web.Response(
|
| 803 |
+
text=(f"🚀 Pro Bot v5.0 (Web Search + Skills + Racing)\n\n"
|
| 804 |
+
f"📊 Stats:\n• Total: {STATS['total']}\n• Cache: {STATS['cache_hits']} ({cs['hit_rate']})\n"
|
| 805 |
+
f"• Skills: {STATS['local_skills']}\n• Web: {STATS['web_search']}\n"
|
| 806 |
+
f"• LLM: {STATS['llm_calls']}\n• Fail: {STATS['failures']}\n\n📋 Log:\n{log}"),
|
| 807 |
+
content_type="text/plain")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 808 |
|
| 809 |
|
| 810 |
async def set_webhook_startup(app):
|
| 811 |
LOG.append(f"[{time.strftime('%H:%M:%S')}] setting webhook...")
|
|
|
|
| 812 |
try:
|
| 813 |
timeout = aiohttp.ClientTimeout(total=15)
|
| 814 |
async with aiohttp.ClientSession(timeout=timeout) as session:
|
| 815 |
async with session.post(
|
| 816 |
f"https://api.telegram.org/bot{BOT_TOKEN}/setWebhook",
|
| 817 |
+
json={"url": f"{SPACE_URL}{WEBHOOK_PATH}", "allowed_updates": ["message"],
|
| 818 |
+
"drop_pending_updates": False, "max_connections": 40},
|
| 819 |
) as resp:
|
| 820 |
data = await resp.json()
|
| 821 |
LOG.append(f"setWebhook: {data.get('ok', False)}")
|
|
|
|
| 833 |
if not BOT_TOKEN:
|
| 834 |
logger.error("No TELEGRAM_BOT_TOKEN!")
|
| 835 |
sys.exit(1)
|
|
|
|
| 836 |
app = web.Application()
|
| 837 |
app.router.add_post(WEBHOOK_PATH, handle_webhook)
|
| 838 |
app.router.add_get("/", health)
|
| 839 |
app.router.add_get("/log", health)
|
| 840 |
app.on_startup.append(set_webhook_startup)
|
| 841 |
app.on_cleanup.append(cleanup)
|
| 842 |
+
logger.info(f"🚀 v5.0 starting on port {PORT}")
|
|
|
|
| 843 |
web.run_app(app, host="0.0.0.0", port=PORT, access_log=None)
|
| 844 |
|
| 845 |
|