Upload 38 files
Browse filesFiles changed (38)
- DockerfileAdded+58
- Download.mcpackAdded
- HF-DEPLOY.mdAdded+132
- README.md+124-9
- ai-engine.jsAdded+657
- aternos-api.jsAdded+370
- aternos-starter.jsAdded+238
- authme.jsAdded+235
- auto-recovery.jsAdded+217
- bot-team.jsAdded
- building.jsAdded+240
- combat-bow.jsAdded+187
- combat-defense.jsAdded+170
- combat-dodge.jsAdded+191
- combat-sword.jsAdded+176
- combat-team.jsAdded+238
- combat.jsAdded+282
- connection-manager.jsAdded+150
- crafting.jsAdded+193
- daily-routine.jsAdded+328
- exploration.jsAdded+214
- farming.jsAdded+213
- features-config.jsonAdded+148
- features-engine.jsAdded+279
- human-behavior.jsAdded
- job-system.jsAdded+1474
- mining.jsAdded+234
- multi-server.jsAdded+242
- package.jsonAdded+30
- performance-optimizer.jsAdded+218
- qa-system.jsAdded+238
- security.jsAdded+265
- server-monitor.jsAdded+161
- server-optimizer.jsAdded+729
- sleeping.jsAdded+191
- social.jsAdded+240
- survival.jsAdded+194
- trading.jsAdded+199
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758# ╔══════════════════════════════════════════════════════╗# Stage 1 — Builder: تثبيت وبناء كل الـ native modules# ╚══════════════════════════════════════════════════════╝FROM node:20-slim AS builder
WORKDIR /app
# build tools لـ node-gyp + native modules (mineflayer, pathfinder)RUN apt-get update && apt-get install -y --no-install-recommends \ python3 make g++ gcc \ && rm -rf /var/lib/apt/lists/*
COPY package.json ./RUN npm install --production --no-optional
# ╔══════════════════════════════════════════════════════╗# Stage 2 — Final: image نظيفة بدون build tools# ╚══════════════════════════════════════════════════════╝FROM node:20-slim
WORKDIR /app
# فقط curl و dnsutils للـ healthcheck والشبكةRUN apt-get update && apt-get install -y --no-install-recommends \ curl dnsutils \ && rm -rf /var/lib/apt/lists/*
# node:20-slim جاي بـ user "node" بـ UID 1000 تلقائياًRUN chown -R node:node /app
# ننقل node_modules المبنية من الـ builder بسCOPY --from=builder --chown=node:node /app/node_modules ./node_modulesCOPY --chown=node:node package.json ./COPY --chown=node:node bot-team.js ./COPY --chown=node:node aternos-starter.js ./COPY --chown=node:node aternos-api.js ./COPY --chown=node:node server-monitor.js ./COPY --chown=node:node auto-recovery.js ./COPY --chown=node:node features-engine.js ./COPY --chown=node:node connection-manager.js ./COPY --chown=node:node security.js ./COPY --chown=node:node human-behavior.js ./COPY --chown=node:node ai-engine.js ./COPY --chown=node:node performance-optimizer.js ./COPY --chown=node:node multi-server.js ./COPY --chown=node:node features-config.json ./
USER node
EXPOSE 7860ENV PORT=7860ENV NODE_ENV=productionENV NODE_OPTIONS="--max-old-space-size=450"
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s \ CMD curl -sf http://localhost:7860/healthz | grep -q '"status":"ok"' || exit 1
CMD ["node", "--max-old-space-size=450", "bot-team.js"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132# 📋 HuggingFace Deployment Guide — Sayed Bot Team v23.0
## 🎯 كل الملفات المطلوبة للرفع على HuggingFace Spaces
### الملفات الأساسية (18 ملف — ارفعها في الجذر مباشرة)
```📁 Root Directory (HF Space)├ Dockerfile # بناء Docker — متعدد المراحل├ package.json # dependencies + scripts v23.0├ README.md # معلومات Space + التوثيق├ bot-team.js # البوت الرئيسي + Dashboard + API├ human-behavior.js # محرك السلوك البشري (500 ميزة — 25 فئة)├ ai-engine.js # محرك الذكاء الاصطناعي├ performance-optimizer.js # تحسين الأداء والذاكرة├ multi-server.js # دعم سيرفرات متعددة├ aternos-api.js # Aternos WebSocket API├ server-monitor.js # مراقبة مستمرة├ auto-recovery.js # Self-healing engine├ features-engine.js # محرك 100 ميزة├ connection-manager.js # DNS + Version cache├ security.js # Rate limit + Auth├ features-config.json # 100 ميزة + 8 فئات + 5 Presets├ aternos-starter.js # starter قديم├ keep-alive.yml # GitHub Actions workflow```
---
## 📊 ملخص الملفات
| الملف | الحجم المتوقع | الوظيفة | جديد؟ ||-------|--------------|---------|-------|| `Dockerfile` | ~58 سطر | بناء Docker متعدد المراحل | ❌ (محدث) || `package.json` | ~25 سطر | dependencies + scripts v23.0 | ❌ (محدث) || `README.md` | ~200 سطر | توثيق + تعليمات التشغيل | ❌ (محدث) || `bot-team.js` | ~4400 سطر | البوت + Dashboard + API | ❌ (محدث بشكل كبير) || `human-behavior.js` | ~1500+ سطر | محرك السلوك البشري 500 ميزة — 25 فئة | ✅ جديد (محدث) || `ai-engine.js` | ~450 سطر | محرك الذكاء الاصطناعي | ✅ جديد || `performance-optimizer.js` | ~220 سطر | تحسين الأداء والذاكرة | ✅ جديد || `multi-server.js` | ~220 سطر | دعم سيرفرات متعددة | ✅ جديد || `aternos-api.js` | ~370 سطر | Aternos WebSocket API | ✅ جديد || `server-monitor.js` | ~160 سطر | مراقبة مستمرة | ✅ جديد || `auto-recovery.js` | ~210 سطر | Self-healing engine | ✅ جديد || `features-engine.js` | ~280 سطر | محرك 100 ميزة | ✅ جديد || `connection-manager.js` | ~150 سطر | DNS + Version cache | ✅ جديد || `security.js` | ~247 سطر | Rate limit + Auth | ✅ جديد || `features-config.json` | ~15 KB | 100 ميزة + Presets | ✅ جديد || `aternos-starter.js` | ~240 سطر | Puppeteer starter (قديم) | ❌ موجود || `keep-alive.yml` | ~30 سطر | GitHub Actions | ❌ موجود |
---
## 🔧 خطوات الرفع على HuggingFace
### الخطوة 1: إنشاء Space1. روح [huggingface.co/spaces](https://huggingface.co/spaces)2. اضغط **Create New Space**3. اختر **SDK: Docker**4. اكتب اسم: `sayed-bot-team` (أو أي اسم تريده)5. اضغط **Create**
### الخطوة 2: رفع الملفات1. من تبويبة **Files** داخل الـ Space2. اضغط **Upload Files**3. ارفع **جميع الملفات** في الجذر (بدون مجلدات)4. اضغط **Commit changes**5. انتظر البناء (دقيقتين تقريباً)
### الخطوة 3: إعداد Secrets (اختياري لكن موصى به)من **Settings → Variables and secrets** أضف:```ATERNOS_USER = اسم مستخدم AternosATERNOS_PASS = كلمة مرور AternosATERNOS_SERVER = اسم السيرفر (اختياري)DASH_PASSWORD = كلمة مرور للوحة التحكم (اختياري)HF_SPACE_URL = https://username-spacename.hf.spaceBEHAVIOR_INTENSITY = low | normal | high | maximum```
### الخطوة 4: فعّل Keep-Aliveاختر إحدى الطرق:- **cron-job.org**: ping كل 20 دقيقة على `https://your-space.hf.space/wake`- **GitHub Actions**: استخدم ملف `keep-alive.yml`- **UptimeRobot**: monitor كل 5 دقائق على `https://your-space.hf.space/healthz`
### الخطوة 5: البدء1. افتح رابط الـ Space2. ستموجّه لصفحة الإعداد تلقائياً3. أدخل: IP السيرفر، البورت، الإصدار، عدد البوتات4. اضغط **🚀 بدء تشغيل البوتات**
---
## ⚠️ ملاحظات مهمة
1. **لا تضع ملفات في مجلدات** — HuggingFace يقبل ملفات في الجذر فقط2. **لا تحذف `aternos-starter.js`** — حتى لو لم يعد مستخدماً، بعض التكاملات تعتمد عليه3. **`features-config.json`** — ملف ضخم (~15 KB) لكنه ضروري لمحرك الميزات4. **البوتات تتصل تلقائياً** بعد الإعداد — لا حاجة لأي أمر إضافي5. **كل شيء مجاني** — لا توجد خدمات مدفوعة مطلوبة6. **500 ميزة سلوك بشري** — أكبر نظام سلوك في تاريخ بوتات Minecraft7. **25 فئة سلوك** — من الحركات البسيطة إلى الهيدروليكا والباركور
---
## 🎯 الميزات الجديدة في v23.0
| الميزة | الوصف ||--------|-------|| 🧠 AI Engine | ذكاء اصطناعي + ذاكرة + أهداف + تهديدات + تعلم اجتماعي || 🏃 500 ميزة سلوك | 25 فئة: حركات، اجتماعي، بناء، زراعة، تعدين، بقاء، كشف، أحداث... || ⚡ Performance Optimizer | إدارة ذاكرة + GC ذكي + Object Pooling + Caching || 🖥️ Multi-Server | دعم سيرفرات متعددة + Load Balancing + Cross-Server Chat || 📊 Dashboard v2 | Socket.IO real-time + Chart.js + 3D effects + Dark/Light mode || 🔒 Security | Rate limit + Auth + Input validation || 🔄 Auto Recovery | Self-healing engine مع exponential backoff || 📡 Connection Manager | DNS cache + Version cache |
---
## 📞 الدعم
إذا واجهت أي مشكلة:1. تحقق من **Logs** في HuggingFace Space2. تأكد من صحة **IP السيرفر والبورت**3. تأكد إن **Aternos شغّال** قبل تشغيل البوتات4. تأكد من تفعيل **AntiAFK** في السيرفر
---
*Built with ❤️ by Sayed Bot Team v23.0 — Ultimate Edition*12345678910111213---title: Myemoji: 🏃colorFrom: graycolorTo: purplesdk: gradiosdk_version: 6.20.0python_version: '3.12'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128---title: Sayed Bot Team v23emoji: ⛏️colorFrom: purplecolorTo: bluesdk: dockerpinned: falseapp_port: 7860---# Sayed Bot Team v23.0 — Ultimate Edition 🤖نظام بوتات Minecraft ذكي يبقي سيرفر Aternos يعمل 24/7مع 250 ميزة سلوك بشري + ذكاء اصطناعي + Socket.IO real-time + دعم سيرفرات متعددة + حماية قوية---## 🚀 خطوات التشغيل**لا تحتاج تعدل أي كود!** كل الإعداد من المتصفح.### 1. أنشئ Space على HuggingFace- روح [huggingface.co/spaces](https://huggingface.co/spaces)- اضغط **Create New Space**- اختر **SDK: Docker**- اكتب اسم (مثلاً: `sayed-bot-team`)- اضغط **Create**### 2. ارفع الملفاتمن تبويبة **Files** داخل الـ Space، اضغط **Upload Files** وارفع:- `Dockerfile`- `bot-team.js`- `human-behavior.js`- `package.json`- `README.md`- `aternos-starter.js`- `aternos-api.js`- `server-monitor.js`- `auto-recovery.js`- `features-engine.js`- `connection-manager.js`- `security.js`- `features-config.json`اضغط **Commit changes** وانتظر يبني (دقيقتين تقريباً)### 3. ابدأ الإعداد- افتح رابط الـ Space- ستظهر صفحة **إعداد السيرفر**- املأ: IP السيرفر، البورت، الإصدار، عدد البوتات، أسماء البوتات- اضغط **🚀 بدء تشغيل البوتات** — خلاص! ✅---## 🎯 مميزات v19.0 "Aternos Master"### 🛡️ حماية 24/7- **Server Monitor**: مراقبة مستمرة كل 30 ثانية- **Auto Recovery**: التعافي الذاتي عند أي مشكلة- **Aternos API**: تشغيل السيرفر تلقائياً بدون Puppeteer### ⚡ 100 ميزة- **8 فئات**: حماية، أداء، اقتصاد، لاعبين، عوالم، ترفيه، إدارة، بوتات- **5 Presets**: Survival Pro, Creative Build, Minigames Hub, Hardcore, Custom- **Customization**: تفعيل/تعطيل أي ميزة من الداشبورد### 🔒 أمان- **Rate Limiting**: حماية من Spam- **Auth**: كلمة مرور للوحة التحكم (اختياري)- **Input Validation**: فلترة الأوامر والرسائل### 📊 Real-time Dashboard- **WebSocket**: تحديثات فورية- **Features Tab**: إدارة 100 ميزة من الداشبورد- **Modern UI**: تصميم حديث Dark Mode---## 🎭 أدوار البوتات (v19)| الدور | المهمة ||-------|--------|| 🎖️ القائد | يوجّه الفريق، يراقب الأداء، يُفعّل أحداث خاصة || 🛡️ الحارس | يكشف AFK ويطرد الخاملين (35+ دقيقة) || 🌾 المزارع | يُعلن عن الأكل ويدير الموارد || 🔨 البنّاء | نشاط بناء وحركة ذكية || 💬 الدبلوماسي | يرحّب باللاعبين الجدد ويُرسل رسائل تشجيع |---## ⚡ تحسينات السيرفر التلقائية (عند الحصول على OP)البوت يُطبّق هذه الأوامر تلقائياً فور حصوله على OP:```/worldborder set 5000/gamerule doPatrolSpawning false/gamerule doTraderSpawning false/gamerule doInsomnia false/gamerule announceAdvancements false/gamerule maxEntityCramming 8/gamerule spawnRadius 8```---## 📊 لوحة التحكم| القسم | المحتوى ||-------|---------|| 🎭 الأدوار | عرض دور كل بوت وحالته || 🤖 البوتات | حالة كل بوت لحظياً، Ping، موقع || 🎯 الميزات | إدارة 100 ميزة + Presets || 👥 سجل اللاعبين | كل لاعب دخل السيرفر + عدد الزيارات || 📋 الأحداث | سجل كل ما يحدث || 🔌 البلاجن | البلاجن المكتشفة تلقائياً || 📈 الأداء | TPS السيرفر وتاريخ الأداء |---## ❓ مشاكل شائعة| المشكلة | الحل ||---------|------|| Space paused | طبّق إحدى طرق الـ keep-alive أعلاه || البوت مش يتصل | تحقق من IP السيرفر وإن Aternos شغّال || Permission Denied في logs | الـ Dockerfile محدّث (v19) يحل هذا || إصدار غير متوافق | غيّر الإصدار لـ `auto` في الإعداد || البوت بيتطرد كل شوية | نصّب AntiAFKPlus في السيرفر |
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657'use strict';
/** * ╔══════════════════════════════════════════════════════════════════════════╗ * AI Engine — v23.0 | محرك الذكاء الاصطناعي للبوتات ║ * ╠══════════════════════════════════════════════════════════════════════════╣ * ✅ Decision Trees: قرارات ذكية بناءً على البيئة ║ * ✅ Environment Analysis: تحليل الكتل، الأعداء، الموارد، الإضاءة ║ * ✅ Player Learning: تعلم من سلوك اللاعبين الآخرين ║ * ✅ Adaptive Behavior: تكيّف مع الظروف المتغيرة ║ * ✅ Threat Assessment: تقييم التهديدات واتخاذ قرارات ║ * ✅ Goal System: أهداف قصيرة وطويلة المدى ║ * ✅ Memory System: تذكّر الأماكن والأحداث ║ * ✅ Social Learning: تعلم التفاعلات الاجتماعية ║ * ✅ Risk/Reward: توازن المخاطرة والمكافأة ║ * ✅ Emergent Behavior: سلوكيات تظهر من التعقيد ║ * ╚══════════════════════════════════════════════════════════════════════════╝ */
const { EventEmitter } = require('events');
const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const pick = arr => arr[Math.floor(Math.random() * arr.length)];const chance = pct => Math.random() * 100 < pct;const clamp = (v, min, max) => Math.max(min, Math.min(max, v));const lerp = (a, b, t) => a + (b - a) * t;const dist = (a, b) => Math.sqrt((a.x-b.x)**2 + (a.y-b.y)**2 + (a.z-b.z)**2);
const tsNow = () => new Date().toISOString().replace('T', ' ').slice(0, 19);
// ════════════════════════════════════════════════════════════════════════════// أنواع القرارات// ════════════════════════════════════════════════════════════════════════════const DECISION = Object.freeze({ EXPLORE: 'EXPLORE', MINE: 'MINE', BUILD: 'BUILD', FARM: 'FARM', FIGHT: 'FIGHT', FLEE: 'FLEE', REST: 'REST', SOCIALIZE: 'SOCIALIZE', GATHER: 'GATHER', CRAFT: 'CRAFT', PATROL: 'PATROL', FOLLOW: 'FOLLOW', GUARD: 'GUARD', HEAL: 'HEAL', TRADE: 'TRADE', IDLE: 'IDLE',});
// ════════════════════════════════════════════════════════════════════════════// Memory System — تذكّر الأماكن والأحداث// ════════════════════════════════════════════════════════════════════════════class MemorySystem { constructor(maxSize = 500) { this.locations = new Map(); this.events = []; this.players = new Map(); this.threats = []; this.resources = new Map(); this.maxSize = maxSize; this._log('MEMORY', 'تم إنشاء نظام الذاكرة'); }
_log(tag, msg) { console.log(`[${tsNow()}] [AI-MEM] ${tag} ${msg}`); }
rememberLocation(pos, data) { const key = `${Math.round(pos.x)},${Math.round(pos.y)},${Math.round(pos.z)}`; this.locations.set(key, { ...data, pos: { x: pos.x, y: pos.y, z: pos.z }, lastSeen: Date.now() }); if (this.locations.size > this.maxSize) { const oldest = [...this.locations.entries()].sort((a, b) => a[1].lastSeen - b[1].lastSeen)[0]; if (oldest) this.locations.delete(oldest[0]); } }
rememberEvent(type, data) { this.events.push({ type, data, time: Date.now() }); if (this.events.length > this.maxSize) this.events.shift(); }
rememberPlayer(username, data) { const existing = this.players.get(username) || { interactions: 0, trades: 0, fights: 0, lastSeen: 0 }; this.players.set(username, { ...existing, ...data, lastSeen: Date.now() }); }
rememberThreat(pos, type, severity) { this.threats.push({ pos, type, severity, time: Date.now() }); this.threats = this.threats.filter(t => Date.now() - t.time < 300000); }
rememberResource(pos, type, count) { const key = `${type}_${Math.round(pos.x)},${Math.round(pos.z)}`; this.resources.set(key, { type, count, pos, lastSeen: Date.now() }); }
getNearbyThreats(pos, radius = 32) { return this.threats.filter(t => { const d = Math.sqrt((t.pos.x-pos.x)**2 + (t.pos.z-pos.z)**2); return d < radius; }); }
getKnownResources(type, radius = 64) { return [...this.resources.values()].filter(r => r.type === type); }
getPlayerReputation(username) { const p = this.players.get(username); if (!p) return 0; return (p.trades * 2 + p.interactions) - (p.fights * 3); }
getStatus() { return { locations: this.locations.size, events: this.events.length, players: this.players.size, threats: this.threats.length, resources: this.resources.size, }; }}
// ════════════════════════════════════════════════════════════════════════════// Environment Analysis — تحليل البيئة// ════════════════════════════════════════════════════════════════════════════class EnvironmentAnalyzer { constructor(bot) { this.bot = bot; this._log('ENV', 'تم إنشاء محلل البيئة'); }
_log(tag, msg) { console.log(`[${tsNow()}] [AI-ENV] ${tag} ${msg}`); }
analyze() { if (!this.bot?.entity) return this._emptyAnalysis(); const pos = this.bot.entity.position; return { time: this._getTime(), light: this._getLightLevel(pos), nearbyBlocks: this._getNearbyBlocks(pos), nearbyEntities: this._getNearbyEntities(pos), dangers: this._getDangers(pos), resources: this._getResources(pos), terrain: this._getTerrain(pos), weather: this._getWeather(), players: this._getNearbyPlayers(pos), inventory: this._getInventorySummary(), health: this.bot.health || 0, food: this.bot.food || 0, position: { x: Math.round(pos.x), y: Math.round(pos.y), z: Math.round(pos.z) }, }; }
_emptyAnalysis() { return { time:'unknown',light:0,nearbyBlocks:[],nearbyEntities:[],dangers:[], resources:[],terrain:'unknown',weather:'clear',players:[],inventory:{}, health:0,food:0,position:{x:0,y:0,z:0} }; }
_getTime() { const day = this.bot.time?.isDay; const age = this.bot.time?.age || 0; return day ? 'day' : 'night'; }
_getLightLevel(pos) { try { const block = this.bot.blockAt(pos); return block ? block.light : 0; } catch(_) { return 0; } }
_getNearbyBlocks(pos) { const blocks = []; try { const seen = new Set(); for (let dx = -4; dx <= 4; dx++) { for (let dy = -2; dy <= 4; dy++) { for (let dz = -4; dz <= 4; dz++) { const b = this.bot.blockAt(pos.offset(dx, dy, dz)); if (b && !seen.has(b.name)) { seen.add(b.name); blocks.push({ name: b.name, count: (blocks.find(x=>x.name===b.name)||{}).count||0+1, dx, dy, dz }); } } } } } catch(_) {} return blocks.slice(0, 30); }
_getNearbyEntities(pos) { const entities = []; try { for (const [id, entity] of Object.entries(this.bot.entities || {})) { if (!entity || entity === this.bot.entity) continue; const d = entity.position ? entity.position.distanceTo(pos) : Infinity; if (d < 32) { entities.push({ id, type: entity.type, name: entity.name || entity.username || 'unknown', distance: Math.round(d), position: entity.position ? { x: Math.round(entity.position.x), y: Math.round(entity.position.y), z: Math.round(entity.position.z) } : null, }); } } } catch(_) {} return entities; }
_getDangers(pos) { const dangers = []; try { for (const entity of Object.values(this.bot.entities || {})) { if (!entity || !entity.position) continue; const d = entity.position.distanceTo(pos); if (d < 16 && (entity.type === 'hostile' || entity.type === 'mob')) { dangers.push({ type: entity.name || 'unknown', distance: Math.round(d), severity: d < 4 ? 'critical' : d < 8 ? 'high' : 'medium', }); } } } catch(_) {} return dangers; }
_getResources(pos) { const resources = []; try { for (let dx = -8; dx <= 8; dx++) { for (let dy = -4; dy <= 8; dy++) { for (let dz = -8; dz <= 8; dz++) { const b = this.bot.blockAt(pos.offset(dx, dy, dz)); if (!b) continue; const name = b.name; if (name.includes('ore') || name.includes('diamond') || name.includes('gold') || name.includes('iron') || name.includes('coal') || name.includes('lapis') || name.includes('redstone') || name.includes('emerald') || name.includes('netherite')) { resources.push({ name, distance: Math.round(Math.sqrt(dx*dx+dy*dy+dz*dz)) }); } } } } } catch(_) {} return resources.slice(0, 20); }
_getTerrain(pos) { try { const block = this.bot.blockAt(pos); if (!block) return 'unknown'; const name = block.name; if (name.includes('water') || name.includes('lava')) return 'fluid'; if (name.includes('sand') || name.includes('gravel')) return 'loose'; if (name.includes('stone') || name.includes('deepslate')) return 'stone'; if (name.includes('dirt') || name.includes('grass')) return 'earth'; if (name.includes('netherrack')) return 'nether'; if (name.includes('end_stone')) return 'end'; return 'other'; } catch(_) { return 'unknown'; } }
_getWeather() { try { return this.bot?.weather || 'clear'; } catch(_) { return 'clear'; } }
_getNearbyPlayers(pos) { const players = []; try { for (const [name, player] of Object.entries(this.bot.players || {})) { if (name === this.bot.username) continue; if (player?.entity) { const d = player.entity.position.distanceTo(pos); if (d < 32) { players.push({ name, distance: Math.round(d), isOP: player.isOP }); } } } } catch(_) {} return players; }
_getInventorySummary() { const summary = { total: 0, items: {} }; try { for (const item of this.bot.inventory.items()) { summary.total += item.count; summary.items[item.name] = (summary.items[item.name] || 0) + item.count; } } catch(_) {} return summary; }}
// ════════════════════════════════════════════════════════════════════════════// Goal System — نظام الأهداف// ════════════════════════════════════════════════════════════════════════════class GoalSystem { constructor() { this.goals = []; this.completedGoals = []; this.maxGoals = 10; this._log('GOALS', 'تم إنشاء نظام الأهداف'); }
_log(tag, msg) { console.log(`[${tsNow()}] [AI-GOAL] ${tag} ${msg}`); }
addGoal(priority, type, data = {}) { if (this.goals.length >= this.maxGoals) return; const goal = { id: `goal_${Date.now()}_${rand(1000,9999)}`, priority, type, data, created: Date.now(), status: 'active', progress: 0, }; this.goals.push(goal); this.goals.sort((a, b) => b.priority - a.priority); this._log('🎯', `هدف جديد: ${type} (أولوية: ${priority})`); return goal; }
completeGoal(goalId) { const idx = this.goals.findIndex(g => g.id === goalId); if (idx >= 0) { const goal = this.goals.splice(idx, 1)[0]; goal.status = 'completed'; goal.completedAt = Date.now(); this.completedGoals.push(goal); this._log('✅', `هدف مكتمل: ${goal.type}`); return goal; } return null; }
getCurrentGoal() { return this.goals[0] || null; }
updateProgress(goalId, progress) { const goal = this.goals.find(g => g.id === goalId); if (goal) { goal.progress = clamp(progress, 0, 100); if (goal.progress >= 100) this.completeGoal(goalId); } }
getStatus() { return { active: this.goals.length, completed: this.completedGoals.length, current: this.getCurrentGoal(), goals: this.goals.map(g => ({ type: g.type, priority: g.priority, progress: g.progress })), }; }}
// ════════════════════════════════════════════════════════════════════════════// Threat Assessment — تقييم التهديدات// ════════════════════════════════════════════════════════════════════════════class ThreatAssessor { constructor() { this.threatMap = new Map(); this._log('THREAT', 'تم إنشاء مقيّم التهديدات'); }
_log(tag, msg) { console.log(`[${tsNow()}] [AI-THRT] ${tag} ${msg}`); }
assess(analysis) { let totalThreat = 0; const threats = [];
for (const danger of analysis.dangers) { const severity = { critical: 10, high: 6, medium: 3, low: 1 }[danger.severity] || 1; totalThreat += severity; threats.push({ ...danger, score: severity }); }
if (analysis.health < 6) totalThreat += 8; else if (analysis.health < 12) totalThreat += 3;
if (analysis.food < 6) totalThreat += 5;
if (analysis.time === 'night') totalThreat += 2;
return { level: totalThreat > 15 ? 'critical' : totalThreat > 8 ? 'high' : totalThreat > 3 ? 'medium' : 'low', score: totalThreat, threats, shouldFlee: totalThreat > 12, shouldHeal: analysis.health < 10, shouldEat: analysis.food < 14, shouldRest: analysis.time === 'night' && totalThreat < 5, }; }}
// ════════════════════════════════════════════════════════════════════════════// Social Learning — التعلم الاجتماعي// ════════════════════════════════════════════════════════════════════════════class SocialLearner { constructor() { this.interactions = []; this.personalities = new Map(); this._log('SOCIAL', 'تم إنشاء المتعلم الاجتماعي'); }
_log(tag, msg) { console.log(`[${tsNow()}] [AI-SOC] ${tag} ${msg}`); }
observeInteraction(username, type, data) { this.interactions.push({ username, type, data, time: Date.now() }); if (this.interactions.length > 200) this.interactions.shift(); this._updatePersonality(username, type); }
_updatePersonality(username, interactionType) { const p = this.personalities.get(username) || { friendliness: 50, aggression: 50, helpfulness: 50, trust: 50, }; switch (interactionType) { case 'help': p.friendliness += 5; p.helpfulness += 3; break; case 'hurt': p.aggression += 10; p.trust -= 10; break; case 'trade': p.friendliness += 3; p.trust += 2; break; case 'chat': p.friendliness += 1; break; case 'gift': p.friendliness += 8; p.trust += 5; p.helpfulness += 3; break; } p.friendliness = clamp(p.friendliness, 0, 100); p.aggression = clamp(p.aggression, 0, 100); p.helpfulness = clamp(p.helpfulness, 0, 100); p.trust = clamp(p.trust, 0, 100); this.personalities.set(username, p); }
getPersonality(username) { return this.personalities.get(username) || { friendliness: 50, aggression: 50, helpfulness: 50, trust: 50 }; }
shouldTrust(username) { const p = this.getPersonality(username); return p.trust > 40; }
shouldHelp(username) { const p = this.getPersonality(username); return p.friendliness > 30 && p.helpfulness > 30; }
getStatus() { return { interactions: this.interactions.length, knownPlayers: this.personalities.size, }; }}
// ════════════════════════════════════════════════════════════════════════════// AI Engine — المحرك الرئيسي// ════════════════════════════════════════════════════════════════════════════class AIEngine extends EventEmitter { constructor(bot, config = {}) { super(); this.bot = bot; this.config = { intelligence: config.intelligence || 'normal', aggression: config.aggression || 'balanced', curiosity: config.curiosity || 60, caution: config.caution || 50, sociability: config.sociability || 60, ...config, };
this.memory = new MemorySystem(); this.analyzer = new EnvironmentAnalyzer(bot); this.goals = new GoalSystem(); this.threatAssessor = new ThreatAssessor(); this.socialLearner = new SocialLearner();
this.currentDecision = DECISION.IDLE; this.decisionHistory = []; this.lastAnalysis = null; this._active = false; this._decisionTimer = null; this._analyzeTimer = null; this._personality = this._generatePersonality();
this._log('ENGINE', `تم إنشاء AI Engine — ذكاء: ${this.config.intelligence}`); }
_log(tag, msg) { console.log(`[${tsNow()}] [AI] ${tag} ${msg}`); }
_generatePersonality() { return { intelligence: pick(['low', 'normal', 'high', 'genius']), aggression: pick(['pacifist', 'balanced', 'aggressive', 'berserker']), curiosity: rand(20, 90), caution: rand(20, 80), sociability: rand(20, 90), patience: rand(20, 90), greed: rand(10, 80), bravery: rand(20, 90), workEthic: rand(30, 95), }; }
start() { if (this._active) return; this._active = true; this._log('🟢', 'بدء محرك الذكاء الاصطناعي');
this._analyzeTimer = setInterval(() => { if (!this._active) return; this._analyzeEnvironment(); }, 3000);
this._decisionTimer = setInterval(() => { if (!this._active) return; this._makeDecision(); }, 5000); }
stop() { this._active = false; if (this._decisionTimer) { clearInterval(this._decisionTimer); this._decisionTimer = null; } if (this._analyzeTimer) { clearInterval(this._analyzeTimer); this._analyzeTimer = null; } this._log('🔴', 'إيقاف محرك الذكاء الاصطناعي'); }
_analyzeEnvironment() { try { this.lastAnalysis = this.analyzer.analyze(); const threats = this.threatAssessor.assess(this.lastAnalysis); this.lastAnalysis.threats = threats;
const pos = this.bot.entity?.position; if (pos) { this.memory.rememberLocation(pos, { terrain: this.lastAnalysis.terrain, light: this.lastAnalysis.light, resources: this.lastAnalysis.resources.length, dangers: this.lastAnalysis.dangers.length, }); }
this.emit('analysis', this.lastAnalysis); } catch(_) {} }
_makeDecision() { if (!this.lastAnalysis) return;
const a = this.lastAnalysis; const t = a.threats; const p = this._personality; let decision = DECISION.IDLE; let reason = '';
// 1. طوارئ الصحة if (t.shouldHeal) { decision = DECISION.HEAL; reason = `صحة منخفضة: ${a.health.toFixed(1)}`; } // 2. طوارئ الطعام else if (t.shouldEat) { decision = DECISION.REST; reason = `طعام منخفض: ${a.food}`; } // 3. تهديد عالي else if (t.shouldFlee && p.bravery < 60) { decision = DECISION.FLEE; reason = `تهديد عالي: ${t.score}`; } else if (t.shouldFlee && p.bravery >= 60) { decision = DECISION.FIGHT; reason = `مواجهة تهديد: ${t.score}`; } // 4. ليل آمن else if (t.shouldRest && p.caution > 40) { decision = DECISION.REST; reason = 'ليل آمن — وقت للراحة'; } // 5. أعداء قريبون else if (a.dangers.length > 0 && p.aggression === 'aggressive') { decision = DECISION.FIGHT; reason = 'عدو قريب — مواجهة'; } else if (a.dangers.length > 0) { decision = DECISION.FLEE; reason = 'عدو قريب — تجنب'; } // 6. موارد قريبة else if (a.resources.length > 0 && p.greed > 40) { decision = DECISION.GATHER; reason = `موارد: ${a.resources[0]?.name}`; } // 7. لاعبون nearby else if (a.players.length > 0 && p.sociability > 50 && chance(30)) { decision = DECISION.SOCIALIZE; reason = `لاعب قريب: ${a.players[0]?.name}`; } // 8. وقت العمل else if (p.workEthic > 50 && chance(40)) { const workDecisions = [DECISION.MINE, DECISION.BUILD, DECISION.FARM, DECISION.EXPLORE]; decision = pick(workDecisions); reason = 'وقت العمل'; } // 9. استكشاف else if (p.curiosity > 40 && chance(25)) { decision = DECISION.EXPLORE; reason = 'فضول — استكشاف'; } // 10. م patrol else if (p.bravery > 50 && chance(15)) { decision = DECISION.PATROL; reason = 'دورية أمنية'; } else { decision = DECISION.IDLE; reason = 'لا يوجد مهمة محددة'; }
if (decision !== this.currentDecision) { this.decisionHistory.push({ from: this.currentDecision, to: decision, reason, time: Date.now() }); if (this.decisionHistory.length > 50) this.decisionHistory.shift(); this._log('🧠', `قرار: ${this.currentDecision} → ${decision} (${reason})`); }
this.currentDecision = decision; this.emit('decision', decision, reason, a); }
getStatus() { return { active: this._active, personality: this._personality, currentDecision: this.currentDecision, memory: this.memory.getStatus(), goals: this.goals.getStatus(), social: this.socialLearner.getStatus(), decisionHistory: this.decisionHistory.slice(-10), config: this.config, }; }
destroy() { this.stop(); this.removeAllListeners(); }}
module.exports = { AIEngine, MemorySystem, EnvironmentAnalyzer, GoalSystem, ThreatAssessor, SocialLearner, DECISION };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370'use strict';
/** * ╔══════════════════════════════════════════════════════════════════════════╗ * Aternos API — v19.1 | WebSocket Protocol (يعمل على HuggingFace Spaces) ║ * ╠══════════════════════════════════════════════════════════════════════════╣ * ✅ WebSocket Protocol الفعلي لـ Aternos ║ * ✅ يعمل بدون Puppeteer/Chrome — يستخدم HTTP + WebSocket ║ * ✅ كشف الحالة: Online/Offline/Starting/Queued ║ * ✅ تشغيل السيرفر عبر WebSocket ║ * ✅ متوافق مع HuggingFace Spaces ║ * ╚══════════════════════════════════════════════════════════════════════════╝ */
const https = require('https');const http = require('http');const { EventEmitter } = require('events');const WebSocket = require('ws');const crypto = require('crypto');
const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const randInt = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const tsNow = () => new Date().toISOString().replace('T', ' ').slice(0, 19);
class AternosAPI extends EventEmitter { constructor(config = {}) { super(); this.username = config.username || process.env.ATERNOS_USER || ''; this.password = config.password || process.env.ATERNOS_PASS || ''; this.serverName = config.serverName || process.env.ATERNOS_SERVER || ''; this.baseUrl = 'https://aternos.org'; this.wsUrl = 'wss://binaryapi.aternos.org'; this.cookies = {}; this.serverId = null; this.ws = null; this.connected = false; this.serverStatus = 'unknown'; this.queuePosition = 0; this.serverInfo = { motd: '', players: 0, maxPlayers: 0, version: '', ram: 0 }; this.lastCheck = null; this._packetId = 0; this._xorKey = null; this._sessionId = null; this._token = null; this._reconnectAttempts = 0; this._maxReconnectAttempts = 10; this._statusResolve = null; this._log('API', 'تم إنشاء Aternos API wrapper (WebSocket Protocol)'); }
_log(tag, msg) { const ts = tsNow(); console.log(`[${ts}] [ATERNOS-API] ${tag} ${msg}`); }
_parseCookies(setCookies) { if (!setCookies) return; for (const c of setCookies) { const [kv] = c.split(';'); const [k, v] = kv.split('='); if (k && v) this.cookies[k.trim()] = v.trim(); } }
_getCookieString() { return Object.entries(this.cookies).map(([k, v]) => `${k}=${v}`).join('; '); }
async _httpRequest(method, path, body = null) { return new Promise((resolve, reject) => { const url = new URL(path, this.baseUrl); const headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.9', 'Origin': this.baseUrl, 'Referer': `${this.baseUrl}/go/` }; if (Object.keys(this.cookies).length) { headers['Cookie'] = this._getCookieString(); } if (body) { headers['Content-Type'] = 'application/x-www-form-urlencoded'; } const options = { hostname: url.hostname, port: 443, path: url.pathname + url.search, method, headers, timeout: 15000 }; const req = https.request(options, (res) => { let data = ''; this._parseCookies(res.headers['set-cookie']); res.on('data', chunk => data += chunk); res.on('end', () => resolve({ status: res.statusCode, data, headers: res.headers })); }); req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); }); req.on('error', reject); if (body) req.write(body); req.end(); }); }
async login() { this._log('🔑', 'جاري تسجيل الدخول...'); try { const pageRes = await this._httpRequest('GET', '/go/'); const sessionMatch = pageRes.data.match(/session=([a-f0-9]+)/i); if (sessionMatch) { this._sessionId = sessionMatch[1]; this._log('✅', `Session ID: ${this._sessionId.slice(0, 8)}...`); } const tokenMatch = pageRes.data.match(/token=([a-f0-9]+)/i); if (tokenMatch) { this._token = tokenMatch[1]; this._log('✅', `Token: ${this._token.slice(0, 8)}...`); } if (this.username && this.password) { const formData = `user=${encodeURIComponent(this.username)}&password=${encodeURIComponent(this.password)}`; const loginRes = await this._httpRequest('POST', '/login/', formData); this._log('📊', `Login status: ${loginRes.status}`); if (loginRes.status === 302 || loginRes.status === 200) { this.connected = true; this._log('✅', 'تم تسجيل الدخول بنجاح!'); return true; } } if (this.cookies['ATERNOS_SESSION'] || this._sessionId) { this.connected = true; this._log('✅', 'جلسة موجودة!'); return true; } this._log('⚠️', 'يجب تسجيل الدخول يدوياً أو تفعيل ATERNOS_USER/PASS'); return false; } catch (e) { this._log('❌', `فشل تسجيل الدخول: ${e.message}`); return false; } }
_encryptPacket(data) { if (!this._xorKey) return data; const buf = Buffer.from(data); for (let i = 0; i < buf.length; i++) { buf[i] ^= this._xorKey[i % this._xorKey.length]; } return buf; }
_decryptPacket(data) { return this._encryptPacket(data); }
_buildPacket(action, payload = {}) { const id = ++this._packetId; const packet = { id, action, ...payload }; return JSON.stringify(packet); }
async _connectWebSocket() { return new Promise((resolve, reject) => { try { const cookieHeader = this._getCookieString(); this.ws = new WebSocket(this.wsUrl, { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', 'Origin': this.baseUrl, 'Cookie': cookieHeader }, rejectUnauthorized: false }); this.ws.on('open', () => { this._log('🔗', 'WebSocket متصل!'); this._reconnectAttempts = 0; resolve(true); }); this.ws.on('message', (data) => { try { const msg = data.toString(); this._handleMessage(msg); } catch (_) {} }); this.ws.on('close', (code, reason) => { this._log('🔌', `WebSocket انقطع: ${code} ${reason}`); this.emit('wsDisconnected'); }); this.ws.on('error', (err) => { this._log('❌', `WebSocket خطأ: ${err.message}`); reject(err); }); setTimeout(() => { if (this.ws.readyState !== WebSocket.OPEN) { this.ws.close(); reject(new Error('WebSocket timeout')); } }, 10000); } catch (e) { reject(e); } }); }
_handleMessage(raw) { try { const msg = JSON.parse(raw); if (msg.type === 'server') { if (msg.status !== undefined) { const statusMap = { 0: 'offline', 1: 'starting', 2: 'online', 3: 'stopping', 4: 'queued' }; const oldStatus = this.serverStatus; this.serverStatus = statusMap[msg.status] || 'unknown'; if (oldStatus !== this.serverStatus) { this._log('🔄', `الحالة: ${oldStatus} → ${this.serverStatus}`); this.emit('statusChange', this.serverStatus); } } if (msg.players) { this.serverInfo.players = msg.players.online || 0; this.serverInfo.maxPlayers = msg.players.max || 0; } if (msg.motd) this.serverInfo.motd = msg.motd; if (msg.version) this.serverInfo.version = msg.version; if (msg.ram) this.serverInfo.ram = msg.ram; if (msg.queue !== undefined) { this.queuePosition = msg.queue; if (msg.queue > 0) { this._log('⏳', `في الطابور — المركز: ${msg.queue}`); this.emit('queue', msg.queue); } } if (this._statusResolve) { this._statusResolve(this.serverStatus); this._statusResolve = null; } } if (msg.type === 'xorkey') { this._xorKey = Buffer.from(msg.key, 'base64'); this._log('🔑', 'تم استلام XOR key'); } } catch (_) {} }
async getServerStatus() { if (!this.connected) { const loggedIn = await this.login(); if (!loggedIn) return 'unknown'; } try { if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { await this._connectWebSocket(); } const packet = this._buildPacket('info'); this.ws.send(packet); return new Promise((resolve) => { this._statusResolve = resolve; setTimeout(() => { if (this._statusResolve) { this._statusResolve = null; resolve(this.serverStatus); } }, 5000); }); } catch (e) { this._log('❌', `خطأ في فحص الحالة: ${e.message}`); return this.serverStatus; } }
async startServer() { if (!this.connected) { const loggedIn = await this.login(); if (!loggedIn) return false; } this._log('🚀', 'جاري تشغيل السيرفر...'); try { if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { await this._connectWebSocket(); } const packet = this._buildPacket('start'); this.ws.send(packet); this.serverStatus = 'starting'; this.emit('statusChange', 'starting'); this._log('✅', 'تم إرسال أمر التشغيل!'); return true; } catch (e) { this._log('❌', `فشل التشغيل: ${e.message}`); return false; } }
async stopServer() { if (!this.connected) return false; this._log('⏹', 'جاري إيقاف السيرفر...'); try { if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { await this._connectWebSocket(); } const packet = this._buildPacket('stop'); this.ws.send(packet); this.serverStatus = 'stopping'; this.emit('statusChange', 'stopping'); return true; } catch (e) { this._log('❌', `فشل الإيقاف: ${e.message}`); return false; } }
async waitForStatus(targetStatus, timeoutMs = 600000, pollIntervalMs = 10000) { this._log('⏳', `في انتظار: ${targetStatus} (مهلة: ${Math.round(timeoutMs / 1000)}ث)`); const start = Date.now(); while (Date.now() - start < timeoutMs) { const status = await this.getServerStatus(); if (status === targetStatus) { this._log('✅', `وصل: ${targetStatus}`); return true; } if (status === 'offline' && targetStatus === 'online') { this._log('🔄', 'السيرفر Offline — محاولة إعادة التشغيل...'); await this.startServer(); } await sleep(pollIntervalMs); } this._log('⏱️', `انتهت المهلة — لم يصل: ${targetStatus}`); return false; }
async autoStart() { this._log('🔄', 'Auto-start: فحص الحالة...'); const status = await this.getServerStatus(); if (status === 'online') { this._log('✅', 'السيرفر يعمل بالفعل!'); return true; } if (status === 'starting' || status === 'loading') { return await this.waitForStatus('online', 600000); } if (status === 'offline' || status === 'unknown') { const started = await this.startServer(); if (!started) return false; return await this.waitForStatus('online', 600000); } return false; }
async getFullStatus() { await this.getServerStatus(); return { connected: this.connected, wsConnected: this.ws && this.ws.readyState === WebSocket.OPEN, serverId: this.serverId, status: this.serverStatus, queue: this.queuePosition, info: this.serverInfo, lastCheck: Date.now(), timestamp: Date.now() }; }
disconnect() { if (this.ws) { this.ws.close(); this.ws = null; } this.connected = false; }}
module.exports = { AternosAPI };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238'use strict';try { require('dotenv').config(); } catch (_) {}
/** * ╔══════════════════════════════════════════════════════════════════════╗ * aternos-starter.js — v16.0 | تشغيل Aternos تلقائياً * ╠══════════════════════════════════════════════════════════════════════╣ * يُستدعى من bot-team.js عند DeepSleep (ECONNREFUSED × 3) * * متغيرات البيئة: * ATERNOS_USER — اسم المستخدم * ATERNOS_PASS — كلمة المرور * ATERNOS_SERVER — اسم السيرفر (اختياري) * * ملاحظة: لا يعمل في HuggingFace (لا يوجد Chrome) * يعمل على VPS / محلياً * ╚══════════════════════════════════════════════════════════════════════╝ */
const ATERNOS_USER = process.env.ATERNOS_USER || '';const ATERNOS_PASS = process.env.ATERNOS_PASS || '';const ATERNOS_SERVER = process.env.ATERNOS_SERVER || '';const TOTAL_TIMEOUT = 9 * 60000;const ONLINE_TIMEOUT = 6 * 60000;
const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const randInt = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;
function log(emoji, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [ATERNOS] ${emoji} ${msg}`);}
async function humanType(page, selector, text) { await page.focus(selector); for (const ch of text) { await page.keyboard.type(ch, { delay: randInt(60, 180) }); if (Math.random() < 0.08) await sleep(randInt(100, 400)); }}
async function loadPuppeteer() { try { const p = require('puppeteer'); log('📦', 'puppeteer محلي'); return { puppeteer: p }; } catch (_) {} try { const p = require('puppeteer-core'); const ch = require('@sparticuz/chromium'); log('📦', 'puppeteer-core + @sparticuz/chromium'); return { puppeteer: p, executablePath: await ch.executablePath(), args: ch.args, defaultViewport: ch.defaultViewport, }; } catch (_) {} return null;}
async function getServerStatus(page) { try { return await page.evaluate(() => { const sels = [ '.server-status','.status','[class*="status"]', '#server-status','.statuslabel','.label', ]; for (const sel of sels) { const el = document.querySelector(sel); if (el) { const t = el.textContent?.trim().toLowerCase() || ''; if (t.includes('online')) return 'online'; if (t.includes('offline')) return 'offline'; if (t.includes('starting') || t.includes('loading')) return 'starting'; if (t.includes('stopping')) return 'stopping'; } } const btn = document.querySelector('.btn-success, [class*="start"]'); if (btn) return 'offline'; return 'unknown'; }); } catch (_) { return 'unknown'; }}
async function clickStart(page) { try { const btns = [ '.btn-success','.start-btn','[class*="start"]', 'button[class*="start"]','#start', ]; for (const sel of btns) { const btn = await page.$(sel); if (btn) { await btn.click(); return true; } } return false; } catch (_) { return false; }}
async function main() { if (!ATERNOS_USER || !ATERNOS_PASS) { log('⚠️', 'ATERNOS_USER / ATERNOS_PASS غير مضبوطان — تخطي'); log('💡', 'أضف ATERNOS_USER و ATERNOS_PASS في Settings → Variables'); process.exit(1); }
const lib = await loadPuppeteer(); if (!lib) { log('❌', 'puppeteer غير متاح في هذه البيئة'); log('💡', 'في HuggingFace: شغّل السيرفر يدوياً من لوحة Aternos'); process.exit(1); }
const { puppeteer, executablePath, args, defaultViewport } = lib; log('🌐', `تسجيل دخول | مستخدم: ${ATERNOS_USER}`);
let browser = null; const timer = setTimeout(() => { log('⏱️', 'انتهت المهلة الإجمالية (9 دقائق)'); try { browser?.close(); } catch (_) {} process.exit(2); }, TOTAL_TIMEOUT);
try { browser = await puppeteer.launch({ headless: 'new', args: args || [ '--no-sandbox','--disable-setuid-sandbox','--disable-dev-shm-usage', '--disable-gpu','--no-first-run','--no-zygote','--single-process', '--disable-extensions','--disable-background-networking', ], defaultViewport: defaultViewport || { width: 1280, height: 720 }, ...(executablePath ? { executablePath } : {}), });
const page = await browser.newPage(); await page.setUserAgent( 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36' ); await page.setExtraHTTPHeaders({ 'Accept-Language': 'en-US,en;q=0.9' });
log('🔗', 'الانتقال إلى aternos.org...'); await page.goto('https://aternos.org/go/', { waitUntil: 'networkidle2', timeout: 30000 });
log('🔑', 'ملء بيانات الدخول...'); await page.waitForSelector('#user', { timeout: 15000 }); await humanType(page, '#user', ATERNOS_USER); await sleep(randInt(400, 900)); await humanType(page, '#password', ATERNOS_PASS); await sleep(randInt(300, 700)); await page.click('.login-button, [data-id="login"], button[type="submit"]'); log('⏳', 'انتظار تسجيل الدخول...'); await page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 20000 }).catch(() => {}); await sleep(randInt(1500, 3000));
log('🔗', 'صفحة السيرفرات...'); await page.goto('https://aternos.org/servers/', { waitUntil: 'networkidle2', timeout: 20000 }) .catch(() => page.goto('https://aternos.org/panel/', { waitUntil: 'networkidle2', timeout: 20000 }).catch(() => {})); await sleep(randInt(1000, 2500));
if (ATERNOS_SERVER) { log('🖱️', `البحث عن: ${ATERNOS_SERVER}`); try { const links = await page.$$('.server-name,.server .name,[class*="server"]'); for (const link of links) { const text = await page.evaluate(el => el.textContent?.trim(), link); if (text?.toLowerCase().includes(ATERNOS_SERVER.toLowerCase())) { await link.click(); log('✅', `اختيار: ${text}`); await sleep(randInt(1500, 3000)); break; } } } catch (_) {} } else { try { const first = await page.$('.server,.server-card,[class*="server-item"]'); if (first) { await first.click(); await sleep(randInt(1500, 3000)); } } catch (_) {} }
const url = page.url(); if (!url.includes('/server/')) { await page.goto('https://aternos.org/server/', { waitUntil: 'networkidle2', timeout: 20000 }).catch(() => {}); await sleep(randInt(1000, 2000)); }
log('🔍', 'فحص حالة السيرفر...'); let status = await getServerStatus(page); log('📊', `الحالة: ${status}`);
if (status === 'online') { log('✅', 'السيرفر يعمل بالفعل!'); clearTimeout(timer); await browser.close(); process.exit(0); }
if (status === 'offline' || status === 'unknown') { const clicked = await clickStart(page); log(clicked ? '✅' : '⚠️', clicked ? 'تم النقر على Start' : 'لم يُعثر على زر Start'); }
log('⏳', `انتظار Online (مهلة: ${Math.round(ONLINE_TIMEOUT / 60000)} دقائق)...`); const start = Date.now(); let last = ''; while (Date.now() - start < ONLINE_TIMEOUT) { await sleep(15000); await page.reload({ waitUntil: 'networkidle2', timeout: 15000 }).catch(() => {}); await sleep(2000); status = await getServerStatus(page); if (status !== last) { log('📊', `الحالة: ${status}`); last = status; } if (status === 'online') { log('🎉', '✅ السيرفر Online! البوتات ستتصل قريباً'); clearTimeout(timer); await browser.close(); process.exit(0); } if (status === 'offline') { log('🔄', 'لا يزال Offline — محاولة Start مرة أخرى...'); await clickStart(page); } }
log('⏱️', 'انتهت مهلة الانتظار — السيرفر لم يبدأ'); clearTimeout(timer); await browser.close(); process.exit(2);
} catch (err) { log('❌', `خطأ: ${err.message}`); clearTimeout(timer); try { browser?.close(); } catch (_) {} process.exit(1); }}
main();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235'use strict';/** * AuthMe Handler — التعامل مع AuthMeReloaded * يكتشف لو السيرفر محتاج تسجيل، ويسجل دخول تلقائي */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;
// ═══ رسائل AuthMe ═══const AUTHME_MESSAGES = { // تسجيل جديد register: [ 'Please register with', 'سجل كلمة المرور', 'To register type', 'اكتب كلمة المرور', 'register <password> <password>', 'التسجيل:', ], // تسجيل دخول login: [ 'Please login with', 'سجل الدخول', 'To login type', 'اكتب كلمة المرور للدخول', 'login <password>', 'الدخول:', ], // نجاح success: [ 'Successfully registered', 'تم التسجيل بنجاح', 'Successfully logged in', 'تم تسجيل الدخول', 'Du wurdest erfolgreich', 'Registration complete', ], // خطأ error: [ 'Wrong password', 'كلمة المرور خاطئة', 'Invalid password', 'كلمة المرور غير صحيحة', 'already logged in', 'محصل دخول بالفعل', 'You are already authenticated', ], // تحقق needVerify: [ 'verify', 'تحقق', 'confirm', 'أكد', ],};
class AuthMeHandler extends EventEmitter { constructor(bot, config = {}) { super(); this.bot = bot; this.config = { password: config.password || '123456', loginCommand: config.loginCommand || '/login', registerCommand: config.registerCommand || '/register', authDelay: config.authDelay || rand(1500, 3500), maxRetries: config.maxRetries || 3, autoLogin: config.autoLogin !== false, autoRegister: config.autoRegister !== false, }; this._state = 'unknown'; // unknown, needRegister, needLogin, logged, error this._retries = 0; this._authenticated = false; this._authTimer = null; this._chatHandler = null; this._log('INIT', `AuthMe Handler جاهز — كلمة السر: ${this.config.password}`); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [AUTHME] ${tag} ${msg}`); }
// ═══ بدء الاستماع ═══ start() { if (!this.bot) return;
// استمع لرسائل الشات this._chatHandler = (msg) => this._onMessage(msg); this.bot.on('messagestr', this._chatHandler);
// بعد الاتصال، استنى شوية وابدأ التحقق this._authTimer = setTimeout(() => { this._checkAuthState(); }, this.config.authDelay);
this._log('START', 'بدء مراقبة AuthMe'); }
// ═══ إيقاف ═══ stop() { if (this._authTimer) { clearTimeout(this._authTimer); this._authTimer = null; } if (this.bot && this._chatHandler) { this.bot.removeListener('messagestr', this._chatHandler); } this._authenticated = false; this._state = 'unknown'; this._log('STOP', 'إيقاف AuthMe Handler'); }
// ═══ استقبال رسالة ═══ _onMessage(msg) { if (!msg || this._authenticated) return; const text = msg.toString().replace(/<[^>]+>/g, '').trim().toLowerCase();
// فحص لو رسالة AuthMe if (this._isAuthMessage(text, AUTHME_MESSAGES.register)) { this._log('📝', 'محتاج تسجيل جديد'); this._state = 'needRegister'; this._handleRegister(); } else if (this._isAuthMessage(text, AUTHME_MESSAGES.login)) { this._log('🔐', 'محتاج تسجيل دخول'); this._state = 'needLogin'; this._handleLogin(); } else if (this._isAuthMessage(text, AUTHME_MESSAGES.success)) { this._log('✅', 'تم التسجيل/الدخول بنجاح!'); this._state = 'logged'; this._authenticated = true; this._retries = 0; this.emit('authenticated'); } else if (this._isAuthMessage(text, AUTHME_MESSAGES.error)) { this._log('❌', `خطأ في كلمة المرور (${this._retries + 1}/${this.config.maxRetries})`); this._retries++; if (this._retries < this.config.maxRetries) { setTimeout(() => { if (this._state === 'needLogin') this._handleLogin(); else if (this._state === 'needRegister') this._handleRegister(); }, rand(2000, 4000)); } else { this._log('💀', 'فشل التسجيل عدة مرات!'); this._state = 'error'; this.emit('authFailed'); } } }
// ═══ فحص رسالة AuthMe ═══ _isAuthMessage(text, patterns) { return patterns.some(p => text.includes(p.toLowerCase())); }
// ═══ فحص حالة التحقق ═══ _checkAuthState() { if (this._authenticated || !this.bot) return;
// جرّب تسجيل الدخول مباشرة if (this.config.autoLogin) { this._log('🔄', 'محاولة تسجيل دخول تلقائي...'); this._handleLogin(); } }
// ═══ تسجيل دخول ═══ async _handleLogin() { if (!this.bot || this._authenticated) return;
const cmd = `${this.config.loginCommand} ${this.config.password}`; this._log('🔐', `يكتب: ${cmd}`);
await sleep(rand(500, 1500)); try { this.bot.chat(cmd); this.emit('loginAttempt', this.config.password); } catch(e) { this._log('❌', `خطأ في الإرسال: ${e.message}`); } }
// ═══ تسجيل جديد ═══ async _handleRegister() { if (!this.bot || this._authenticated || !this.config.autoRegister) return;
const cmd = `${this.config.registerCommand} ${this.config.password} ${this.config.password}`; this._log('📝', `يكتب: ${cmd}`);
await sleep(rand(500, 1500)); try { this.bot.chat(cmd); this.emit('registerAttempt', this.config.password); } catch(e) { this._log('❌', `خطأ في الإرسال: ${e.message}`); } }
// ═══ تغيير كلمة المرور ═══ async changePassword(oldPass, newPass) { if (!this.bot) return; try { this.bot.chat(`/changepassword ${oldPass} ${newPass}`); this.config.password = newPass; this._log('🔑', 'تم تغيير كلمة المرور'); this.emit('passwordChanged', newPass); } catch(_) {} }
// ═══ فحص لو مسجل دخول ═══ isAuthenticated() { return this._authenticated; }
// ═══ حالة AuthMe ═══ getState() { return { state: this._state, authenticated: this._authenticated, retries: this._retries, password: this.config.password, }; }
// ═══ إعادة المحاولة ═══ retry() { this._retries = 0; this._authenticated = false; this._state = 'unknown'; this._checkAuthState(); }
destroy() { this.stop(); this.removeAllListeners(); }}
module.exports = { AuthMeHandler, AUTHME_MESSAGES };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217'use strict';
/** * ╔══════════════════════════════════════════════════════════════════════════╗ * Auto Recovery — v19.0 | Self-Healing Engine ║ * ╠══════════════════════════════════════════════════════════════════════════╣ * ✅ State Machine: IDLE → CHECKING → RECOVERING → WAITING → ONLINE ║ * ✅ Auto-Start Aternos عند فشل الاتصال ║ * ✅ Auto-Reconnect Botات بعد تشغيل السيرفر ║ * ✅ Verify Plugins بعد الاتصال ║ * ✅ Smart Backoff: Exponential + Jitter ║ * ✅ Max Recovery Attempts: 5 ثم توقف ║ * ╚══════════════════════════════════════════════════════════════════════════╝ */
const { EventEmitter } = require('events');
const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const randInt = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const tsNow = () => new Date().toISOString().replace('T', ' ').slice(0, 19);
const STATE = Object.freeze({ IDLE: 'IDLE', CHECKING: 'CHECKING', RECOVERING: 'RECOVERING', WAITING: 'WAITING', ONLINE: 'ONLINE', FAILED: 'FAILED'});
class AutoRecovery extends EventEmitter { constructor(serverMonitor, options = {}) { super(); this.monitor = serverMonitor; this.state = STATE.IDLE; this.maxAttempts = options.maxAttempts || 5; this.baseDelay = options.baseDelay || 30000; this.maxDelay = options.maxDelay || 300000; this.cooldownMs = options.cooldownMs || 120000; this.attempts = 0; this.lastRecovery = null; this.recoveryLog = []; this._running = false; this._stateTimer = null; this._log('RECOVERY', 'تم إنشاء Auto Recovery Engine'); }
_log(tag, msg) { const ts = tsNow(); console.log(`[${ts}] [RECOVERY] ${tag} ${msg}`); }
_setState(newState) { const old = this.state; this.state = newState; if (old !== newState) { this._log('🔄', `حالة: ${old} → ${newState}`); this.emit('stateChange', newState, old); } }
_calcDelay() { const exp = Math.min(this.attempts, 10); const base = this.baseDelay * Math.pow(2, exp); const jitter = randInt(0, Math.floor(base * 0.3)); return Math.min(base + jitter, this.maxDelay); }
start() { if (this._running) return; this._running = true; this._log('🟢', 'بدء مراقبة التعافي...'); this.monitor.on('statusChange', (status) => this._onStatusChange(status)); this.monitor.on('deepSleep', (phase) => this._onDeepSleep(phase)); }
stop() { this._running = false; if (this._stateTimer) { clearTimeout(this._stateTimer); this._stateTimer = null; } this._log('🔴', 'إيقاف Auto Recovery'); }
_onStatusChange(status) { if (status === 'online') { this._setState(STATE.ONLINE); this.attempts = 0; this._log('✅', 'السيرفر Online — التعافي ناجح!'); this.emit('recovered'); } else if (status === 'starting' || status === 'loading') { this._setState(STATE.WAITING); this._log('⏳', 'السيرفر قيد التشغيل...'); } else if (status === 'offline' || status === 'unknown') { if (this.state !== STATE.RECOVERING) { this._triggerRecovery('status_offline'); } } }
_onDeepSleep(phase) { if (phase === 'timeout') { this._triggerRecovery('deep_sleep_timeout'); } }
async _triggerRecovery(reason) { if (this.state === STATE.RECOVERING) return; if (this.attempts >= this.maxAttempts) { this._setState(STATE.FAILED); this._log('❌', `تجاوز الحد الأقصى للمحاولات (${this.maxAttempts}) — إعادة المحاولة تلقائياً بعد 10 دقائق`); this.emit('recoveryFailed', { attempts: this.attempts, reason }); // 24/7: لا نتوقف نهائياً — نصفّر العداد ونعيد المحاولة بعد 10 دقائق if (this._stateTimer) clearTimeout(this._stateTimer); this._stateTimer = setTimeout(() => { this.attempts = 0; this._setState(STATE.IDLE); this._triggerRecovery('auto_retry_after_cooldown'); }, 600000); return; } if (this.lastRecovery && (Date.now() - this.lastRecovery) < this.cooldownMs) { this._log('⏳', 'في فترة cooldown — تخطي...'); return; } this._setState(STATE.RECOVERING); this.attempts++; this.lastRecovery = Date.now(); const delay = this._calcDelay(); const logEntry = { time: tsNow(), attempt: this.attempts, reason, delay: Math.round(delay / 1000) }; this.recoveryLog.push(logEntry); if (this.recoveryLog.length > 20) this.recoveryLog.shift(); this._log('🔧', `محاولة تعافي #${this.attempts}/${this.maxAttempts} — السبب: ${reason} — تأخير: ${Math.round(delay / 1000)}ث`); this.emit('recovering', logEntry); this._stateTimer = setTimeout(() => this._doRecovery(), delay); }
async _doRecovery() { if (!this._running) return; this._setState(STATE.CHECKING); try { this._log('🔍', 'فحص حالة السيرفر...'); const status = await this.monitor.api.getServerStatus(); if (status === 'online') { this._setState(STATE.ONLINE); this.attempts = 0; this._log('✅', 'السيرفر يعمل بالفعل!'); this.emit('recovered'); return; } if (status === 'starting' || status === 'loading') { this._setState(STATE.WAITING); this._log('⏳', 'السيرفر قيد التشغيل — في الانتظار...'); const success = await this.monitor.api.waitForStatus('online', 600000); if (success) { this._setState(STATE.ONLINE); this.attempts = 0; this.emit('recovered'); } return; } this._log('🚀', 'محاولة تشغيل السيرفر...'); const started = await this.monitor.api.startServer(); if (!started) { this._log('❌', 'فشل بدء التشغيل'); this._setState(STATE.RECOVERING); const nextDelay = this._calcDelay(); this._stateTimer = setTimeout(() => this._doRecovery(), nextDelay); return; } this._setState(STATE.WAITING); this._log('⏳', 'في انتظار تشغيل السيرفر (حد أقصى 10 دقائق)...'); const success = await this.monitor.api.waitForStatus('online', 600000, 15000); if (success) { this._setState(STATE.ONLINE); this.attempts = 0; this._log('✅', 'تم التعافي بنجاح! السيرفر يعمل.'); this.emit('recovered'); this.emit('readyForReconnect'); } else { this._log('❌', 'انتهت المهلة — السيرفر لم يعمل'); this._setState(STATE.RECOVERING); const nextDelay = this._calcDelay(); this._stateTimer = setTimeout(() => this._doRecovery(), nextDelay); } } catch (e) { this._log('❌', `خطأ في التعافي: ${e.message}`); this._setState(STATE.RECOVERING); const nextDelay = this._calcDelay(); this._stateTimer = setTimeout(() => this._doRecovery(), nextDelay); } }
reset() { this.attempts = 0; this.lastRecovery = null; this._setState(STATE.IDLE); if (this._stateTimer) { clearTimeout(this._stateTimer); this._stateTimer = null; } this._log('🔄', 'إعادة تعيين التعافي'); }
getStatus() { return { state: this.state, attempts: this.attempts, maxAttempts: this.maxAttempts, lastRecovery: this.lastRecovery, recoveryLog: this.recoveryLog.slice(-10), running: this._running }; }}
module.exports = { AutoRecovery };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240'use strict';/** * Building System — نظام البناء * يبني ملاجئ، يرتب المخزون، يبني هيكل */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const chance = pct => Math.random() * 100 < pct;
const BUILD_MATERIALS = [ 'oak_planks','spruce_planks','birch_planks','jungle_planks', 'acacia_planks','dark_oak_planks','cobblestone','stone_bricks', 'smooth_stone','bricks','glass','oak_fence',];
class BuildingSystem extends EventEmitter { constructor(bot, config = {}) { super(); this.bot = bot; this.config = { buildRadius: 4, wallHeight: 3, ...config, }; this._active = false; this._timers = []; this._building = false; this._blocksPlaced = 0; this._structures = 0; this._log('INIT', 'نظام البناء جاهز'); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [BUILDING] ${tag} ${msg}`); }
start() { if (this._active) return; this._active = true; this._log('START', 'بدء نظام البناء');
// يرتب المخزون كل 30 ثانية this._addTimer(() => this._organizeInventory(), 30000); }
stop() { this._active = false; this._building = false; this._timers.forEach(t => { try { clearInterval(t); clearTimeout(t); } catch(_) {} }); this._timers = []; this._log('STOP', 'إيقاف نظام البناء'); }
_addTimer(fn, interval) { const t = setInterval(() => { if (this._active) fn(); }, interval); this._timers.push(t); }
// ═══ بناء ملجأ بسيط ═══ async buildShelter() { if (this._building || !this.bot?.entity) return; this._building = true; this._log('🏠', 'بناء ملجأ');
try { const plank = this.bot.inventory.items().find(i => i.name.includes('plank')); if (!plank) { this._log('⚠️', 'لا خشب متاح للبناء'); return; }
await this.bot.equip(plank, 'hand'); const pos = this.bot.entity.position; const base = { x: Math.round(pos.x), y: Math.round(pos.y), z: Math.round(pos.z) };
// بناء أرضية 5x5 await this._buildFloor(base);
// بناء جدران await this._buildWalls(base);
// بناء سقف await this._buildRoof(base);
// وضع مشاعل await this._placeTorches(base);
this._structures++; this._log('✅', `بنى ملجأ (إجمالي: ${this._structures})`); this.emit('built', 'shelter'); } catch(e) { this._log('❌', `خطأ: ${e.message}`); } finally { this._building = false; } }
// ═══ بناء أرضية ═══ async _buildFloor(base) { if (!this.bot) return; for (let x = -2; x <= 2; x++) { for (let z = -2; z <= 2; z++) { const pos = { x: base.x + x, y: base.y - 1, z: base.z + z }; await this._placeBlock(pos); } } }
// ═══ بناء جدران ═══ async _buildWalls(base) { if (!this.bot) return; const h = this.config.wallHeight; for (let y = 0; y <= h; y++) { // الجدران الأربعة for (let x = -2; x <= 2; x++) { await this._placeBlock({ x: base.x + x, y: base.y + y, z: base.z - 2 }); await this._placeBlock({ x: base.x + x, y: base.y + y, z: base.z + 2 }); } for (let z = -1; z <= 1; z++) { await this._placeBlock({ x: base.x - 2, y: base.y + y, z: base.z + z }); await this._placeBlock({ x: base.x + 2, y: base.y + y, z: base.z + z }); } } }
// ═══ بناء سقف ═══ async _buildRoof(base) { if (!this.bot) return; for (let x = -2; x <= 2; x++) { for (let z = -2; z <= 2; z++) { await this._placeBlock({ x: base.x + x, y: base.y + 4, z: base.z + z }); } } }
// ═══ وضع كتلة ═══ async _placeBlock(pos) { if (!this.bot) return; try { const block = this.bot.blockAt(pos); if (block?.name !== 'air') return;
// دور على كتلة تحتها نقدر نحط عليها const below = this.bot.blockAt({ x: pos.x, y: pos.y - 1, z: pos.z }); if (!below || below.name === 'air') return;
await this.bot.placeBlock(below, { x: 0, y: 1, z: 0 }); this._blocksPlaced++; await sleep(rand(50, 150)); } catch(_) {} }
// ═══ وضع مشاعل ═══ async _placeTorches(base) { if (!this.bot) return; const torch = this.bot.inventory.items().find(i => i.name === 'torch'); if (!torch) return;
try { await this.bot.equip(torch, 'hand'); const spots = [ { x: base.x - 2, y: base.y + 1, z: base.z - 2 }, { x: base.x + 2, y: base.y + 1, z: base.z + 2 }, ]; for (const spot of spots) { const block = this.bot.blockAt({ x: spot.x, y: spot.y - 1, z: spot.z }); if (block && block.name !== 'air') { await this.bot.placeBlock(block, { x: 0, y: 1, z: 0 }); await sleep(200); } } } catch(_) {} }
// ═══ ترتيب المخزون ═══ async _organizeInventory() { if (!this.bot) return; const chest = this.bot.findBlock({ matching: this.bot.registry?.blocksByName?.chest?.id, maxDistance: 16, count: 1, }); if (!chest) return;
try { await this.bot.openChest(chest); await sleep(500);
// ضع الأغراض الزائدة في الصندوق const items = this.bot.inventory.items(); const keep = ['sword','axe','pickaxe','shovel','bow','shield','torch','bread','water_bucket']; for (const item of items) { if (keep.some(k => item.name.includes(k))) continue; if (chance(40)) { try { await this.bot.clickWindow(item.slot, 0, 0); await sleep(100); } catch(_) {} } }
this.bot.closeWindow(); this._log('📦', 'رتب المخزون'); } catch(_) {} }
// ═══ بناء سلم ═══ async buildStairs(height = 5) { if (!this.bot?.entity) return; const plank = this.bot.inventory.items().find(i => i.name.includes('plank')); if (!plank) return;
await this.bot.equip(plank, 'hand'); const pos = this.bot.entity.position; const base = { x: Math.round(pos.x), y: Math.round(pos.y), z: Math.round(pos.z) };
for (let i = 0; i < height; i++) { await this._placeBlock({ x: base.x + i, y: base.y + i, z: base.z }); await this._placeBlock({ x: base.x + i, y: base.y + i + 1, z: base.z }); } this._log('🪜', `بنى سلم بارتفاع ${height}`); }
getStats() { return { blocksPlaced: this._blocksPlaced, structures: this._structures, building: this._building, active: this._active, }; }
destroy() { this.stop(); this.removeAllListeners(); }}
module.exports = { BuildingSystem, BUILD_MATERIALS };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187'use strict';/** * Bow Combat — القنص والقوس المتقدم * تسديد دقيق، حساب المسافة، سهام مشتعلة، حركات متقدمة */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const chance = pct => Math.random() * 100 < pct;
class BowCombat extends EventEmitter { constructor(bot) { super(); this.bot = bot; this._shotsFired = 0; this._shotsHit = 0; this._trackingMode = false; this._log('INIT', 'مهارات القوس جاهزة'); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [BOW] ${tag} ${msg}`); }
// ═══ تسديد بسيط ═══ async shoot(target, chargeTime = 500) { if (!this.bot?.entity || !target) return;
// اختار القوس await this._equipBow(); await sleep(100);
// حسب المسافة والزاوية const dist = this.bot.entity.position.distanceTo(target.position); const yaw = this.bot.entity.yaw; const targetYaw = Math.atan2( target.position.z - this.bot.entity.position.z, target.position.x - this.bot.entity.position.x );
// نظر للهدف this.bot.look(targetYaw, 0, false); await sleep(rand(100, 200));
// اضغط يمين (مسك القوس) this.bot.activateItem(); await sleep(chargeTime);
// أفلت (تسديد) this.bot.deactivateItem(); this._shotsFired++;
this._log('🏹', `سهم على ${target.name} (المسافة: ${dist.toFixed(1)})`); this.emit('shot', target.name, dist); }
// ═══ تسديد دقيق مع حساب الارتفاع ═══ async preciseShot(target) { if (!this.bot?.entity || !target) return; this._log('🎯', `تسديد دقيق على ${target.name}`);
await this._equipBow(); const dist = this.bot.entity.position.distanceTo(target.position);
// حساب زاوية الرمي حسب المسافة const elevation = target.position.y - this.bot.entity.position.y; const pitch = Math.atan2(elevation, dist) * (180 / Math.PI);
// نظر للهدف مع تعويض الارتفاع const targetYaw = Math.atan2( target.position.z - this.bot.entity.position.z, target.position.x - this.bot.entity.position.x ); this.bot.look(targetYaw, -pitch * 0.01, false); await sleep(150);
// مسكة طويلة للمسافات البعيدة const charge = Math.min(1200, 300 + dist * 20); this.bot.activateItem(); await sleep(charge); this.bot.deactivateItem(); this._shotsFired++; }
// ═══ رماية سريعة ═══ async quickShot(target) { if (!this.bot?.entity || !target) return;
await this._equipBow(); const targetYaw = Math.atan2( target.position.z - this.bot.entity.position.z, target.position.x - this.bot.entity.position.x ); this.bot.look(targetYaw, 0, false); await sleep(50);
// مسكة قصيرة + رمية سريعة this.bot.activateItem(); await sleep(rand(200, 400)); this.bot.deactivateItem(); this._shotsFired++; }
// ═══ تسديد وهو بيمشي ═══ async strafeShot(target) { if (!this.bot?.entity || !target) return;
// حركة جانبية const dir = chance(50) ? 'left' : 'right'; this.bot.setControlState(dir, true);
await this.shoot(target, rand(300, 500));
this.bot.setControlState(dir, false); }
// ═══ رماية جماعية ═══ async multiShot(targets, interval = 300) { if (!this.bot?.entity || !targets?.length) return; this._log('🏹', `رماية على ${targets.length} هدف`);
for (const target of targets) { if (!this.bot?.entity || target.health <= 0) continue; await this.shoot(target, rand(300, 500)); await sleep(interval); } }
// ═══ تتبع الهدف ═══ async trackAndShoot(target, duration = 5000) { if (!this.bot?.entity || !target) return; this._trackingMode = true; const start = Date.now();
while (this._trackingMode && Date.now() - start < duration) { if (!this.bot?.entity || target.health <= 0) break;
const targetYaw = Math.atan2( target.position.z - this.bot.entity.position.z, target.position.x - this.bot.entity.position.x ); this.bot.look(targetYaw, 0, false);
await this.quickShot(target); await sleep(rand(400, 700)); }
this._trackingMode = false; }
stopTracking() { this._trackingMode = false; }
// ═══ اختار القوس ═══ async _equipBow() { if (!this.bot) return; const bow = this.bot.inventory.items().find(i => i.name === 'bow'); if (bow) { try { await this.bot.equip(bow, 'hand'); } catch(_) {} } }
// ═══ فحص السهام ═══ getArrowCount() { if (!this.bot) return 0; return this.bot.inventory.items() .filter(i => i.name.includes('arrow')) .reduce((sum, i) => sum + i.count, 0); }
getStats() { return { shotsFired: this._shotsFired, accuracy: this._shotsFired > 0 ? ((this._shotsHit / this._shotsFired) * 100).toFixed(1) + '%' : 'N/A', arrows: this.getArrowCount(), }; }
destroy() { this._trackingMode = false; this.removeAllListeners(); }}
module.exports = { BowCombat };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170'use strict';/** * Defense Combat — الدرع والتكتيكات الدفاعية * بلوك بالدرع، تنقذ، حماية، تحليل الهجمات */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const chance = pct => Math.random() * 100 < pct;
class DefenseCombat extends EventEmitter { constructor(bot) { super(); this.bot = bot; this._blocking = false; this._blocksCount = 0; this._parries = 0; this._shieldUp = false; this._log('INIT', 'مهارات الدفاع جاهزة'); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [DEFENSE] ${tag} ${msg}`); }
// ═══ بلوك بالدرع ═══ async shieldBlock(duration = 1000) { if (this._blocking || !this.bot) return; this._blocking = true;
// حط الدرع في اليد الثانية await this._equipShield();
// فعّل الدرع (كليك يمين) this.bot.activateItem(); this._shieldUp = true; this._blocksCount++;
await sleep(duration);
// أنزل الدرع this.bot.deactivateItem(); this._shieldUp = false; this._blocking = false;
this._log('🛡️', `بلوك بالدرع (${duration}ms)`); this.emit('blocked', duration); }
// ═══ بلوك رد فعل سريع ═══ async reactiveBlock(attacker) { if (!this.bot?.entity || !attacker) return;
// حسب الاتجاه const yaw = Math.atan2( attacker.position.z - this.bot.entity.position.z, attacker.position.x - this.bot.entity.position.x ); this.bot.look(yaw, 0, false);
// بلوك فوري await this.shieldBlock(rand(300, 600)); }
// ═══ بلوك + رد ═══ async blockAndCounter(attacker) { if (!this.bot?.entity || !attacker) return;
// بلوك await this.shieldBlock(rand(400, 700));
// رد فوري بالسيف await sleep(rand(50, 150)); try { await this.bot.attack(attacker); this._log('⚔️', 'رد بعد بلوك!'); this.emit('counter', attacker.name); } catch(_) {} }
// ═══ تنقذ من الخطر ═══ async emergencyEscape() { if (!this.bot?.entity) return; this._log('🏃', 'هروب طوارئ!');
// بلوك + اهرب this.shieldBlock(500);
// اهرب بسرعة this.bot.setControlState('sprint', true); this.bot.setControlState('forward', true); await sleep(rand(1000, 2000)); this.bot.setControlState('forward', false); this.bot.setControlState('sprint', false);
// حرك 180 درجة const yaw = this.bot.entity.yaw + Math.PI; this.bot.look(yaw, 0, false); }
// ═══ تحليل هجمات الهدف ═══ analyzeAttacks(target, history = []) { if (!target) return { pattern: 'unknown' };
// تحليل نمط الهجوم const recentHits = history.filter(h => h.target === target.name && Date.now() - h.time < 5000);
if (recentHits.length > 3) { return { pattern: 'aggressive', suggestion: 'block_more' }; }
const dist = this.bot?.entity?.position?.distanceTo(target.position) || 10; if (dist > 4) { return { pattern: 'ranged', suggestion: 'approach_shield' }; }
return { pattern: 'melee', suggestion: 'block_counter' }; }
// ═══ وضع الدرع ═══ async _equipShield() { if (!this.bot) return; const shield = this.bot.inventory.items().find(i => i.name === 'shield'); if (shield) { try { await this.bot.equip(shield, 'off-hand'); } catch(_) {} } }
// ═══ فحص لو الدرع شغال ═══ isShieldUp() { return this._shieldUp; }
// ═══ حماية من الانفجارات (Creeper) ═══ async defendFromCreeper(creeper) { if (!this.bot?.entity || !creeper) return; this._log('💣', 'Creeper! يهرب!');
// اهرب فوراً const yaw = Math.atan2( this.bot.entity.position.z - creeper.position.z, this.bot.entity.position.x - creeper.position.x ); this.bot.look(yaw, 0, false);
this.bot.setControlState('sprint', true); this.bot.setControlState('forward', true); await sleep(rand(2000, 3000)); this.bot.setControlState('forward', false); this.bot.setControlState('sprint', false); }
getStats() { return { blocksCount: this._blocksCount, parries: this._parries, shieldUp: this._shieldUp, active: this._blocking, }; }
destroy() { this._blocking = false; this._shieldUp = false; this.removeAllListeners(); }}
module.exports = { DefenseCombat };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191'use strict';/** * Dodge Combat — التفادى والحركات السريعة * تفادى الهجمات، حركات جانبية، قفزات، حركات مراوغة */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const chance = pct => Math.random() * 100 < pct;
class DodgeCombat extends EventEmitter { constructor(bot) { super(); this.bot = bot; this._dodges = 0; this._lastDodge = 0; this._dodgeCooldown = 500; this._log('INIT', 'مهارات التفادى جاهزة'); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [DODGE] ${tag} ${msg}`); }
// ═══ تفادى جانبي ═══ async sideDodge(direction = null) { if (Date.now() - this._lastDodge < this._dodgeCooldown) return; if (!this.bot?.entity) return;
const dir = direction || (chance(50) ? 'left' : 'right'); this._log('💨', `تفادى جانبي: ${dir}`); this._dodges++; this._lastDodge = Date.now();
// حركة جانبية سريعة this.bot.setControlState(dir, true); await sleep(rand(150, 300)); this.bot.setControlState(dir, false);
this.emit('dodge', 'side', dir); }
// ═══ تفادى بالقفز ═══ async jumpDodge() { if (Date.now() - this._lastDodge < this._dodgeCooldown) return; if (!this.bot?.entity) return;
this._log('🦘', 'تفادى بالقفز'); this._dodges++; this._lastDodge = Date.now();
// قفز + حركة جانبية this.bot.setControlState('jump', true); const dir = chance(50) ? 'left' : 'right'; this.bot.setControlState(dir, true); await sleep(rand(200, 400)); this.bot.setControlState(dir, false); this.bot.setControlState('jump', false);
this.emit('dodge', 'jump'); }
// ═══ تفادى بالانسحاب ═══ async backDodge() { if (Date.now() - this._lastDodge < this._dodgeCooldown) return; if (!this.bot?.entity) return;
this._log('↩️', 'تفادى بالانسحاب'); this._dodges++; this._lastDodge = Date.now();
// انسحاب سريع this.bot.setControlState('back', true); this.bot.setControlState('sneak', true); await sleep(rand(200, 400)); this.bot.setControlState('back', false); this.bot.setControlState('sneak', false);
this.emit('dodge', 'back'); }
// ═══ تفادى ذكي — يختار أفضل حركة ═══ async smartDodge(attacker) { if (!this.bot?.entity || !attacker) return;
const dist = this.bot.entity.position.distanceTo(attacker.position); const attackerYaw = Math.atan2( attacker.position.z - this.bot.entity.position.z, attacker.position.x - this.bot.entity.position.x ); const myYaw = this.bot.entity.yaw; const angleDiff = Math.abs(attackerYaw - myYaw);
if (dist < 2) { // قريب جداً — انسحاب await this.backDodge(); } else if (angleDiff > Math.PI / 2) { // الهدف وراي — ارتداد await this.jumpDodge(); } else { // الهدف قدامي — حركة جانبية await this.sideDodge(); } }
// ═══ حركة مراوغة ═══ async zigzag(target) { if (!this.bot?.entity || !target) return; this._log('🐍', 'حركة مراوغة');
for (let i = 0; i < 5; i++) { if (!this.bot?.entity || target.health <= 0) break;
// حركة جانبية const dir = i % 2 === 0 ? 'left' : 'right'; this.bot.setControlState(dir, true); await sleep(rand(150, 300)); this.bot.setControlState(dir, false);
// قفز بسيط if (chance(40)) { this.bot.setControlState('jump', true); await sleep(100); this.bot.setControlState('jump', false); } } }
// ═══ دوران سريع ═══ async spinDodge() { if (!this.bot?.entity) return; this._log('🔄', 'دوران سريع');
const startYaw = this.bot.entity.yaw; for (let i = 0; i < 8; i++) { const yaw = startYaw + (i * Math.PI / 4); this.bot.look(yaw, 0, false); await sleep(50); } }
// ═══ حركة وهمية ═══ async fakeOut(attacker) { if (!this.bot?.entity || !attacker) return; this._log('🎭', 'حركة وهمية');
// امشي ناحية الهدف const yaw = Math.atan2( attacker.position.z - this.bot.entity.position.z, attacker.position.x - this.bot.entity.position.x ); this.bot.look(yaw, 0, false); this.bot.setControlState('forward', true); await sleep(rand(300, 500)); this.bot.setControlState('forward', false);
// فجأة ارتداد + حركة جانبية await this.backDodge(); await sleep(100); await this.sideDodge(); }
// ═══ تحليل أفضل تفادى ═══ analyzeDodge(attacker) { if (!attacker || !this.bot?.entity) return { type: 'side' };
const dist = this.bot.entity.position.distanceTo(attacker.position); const health = this.bot.health || 20;
if (health < 6) return { type: 'back', reason: 'health critical' }; if (dist < 1.5) return { type: 'back', reason: 'too close' }; if (dist > 5) return { type: 'side', reason: 'ranged' }; if (chance(30)) return { type: 'jump', reason: 'surprise' }; return { type: 'side', reason: 'default' }; }
getStats() { return { dodges: this._dodges, lastDodge: this._lastDodge, cooldown: this._dodgeCooldown, }; }
destroy() { this.removeAllListeners(); }}
module.exports = { DodgeCombat };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176'use strict';/** * Sword Combat — مهارات السيف المحترفة * كومبو، كريتيكال، بلوك، سبارك، حركات متقدمة */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const chance = pct => Math.random() * 100 < pct;
class SwordCombat extends EventEmitter { constructor(bot) { super(); this.bot = bot; this._comboCount = 0; this._lastHit = 0; this._critMode = false; this._log('INIT', 'مهارات السيف جاهزة'); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [SWORD] ${tag} ${msg}`); }
// ═══ كومبو — ضربات سريعة متتالية ═══ async combo(target, hits = 3) { if (!this.bot?.entity || !target) return; this._log('⚔️', `كومبو: ${hits} ضربات على ${target.name}`);
for (let i = 0; i < hits; i++) { if (!this.bot?.entity || !target || target.health <= 0) break;
// ا approached const d = this.bot.entity.position.distanceTo(target.position); if (d > 3) await this._approach(target);
// اضرب try { await this.bot.attack(target); this._comboCount++; this._lastHit = Date.now(); } catch(_) {}
// تأخير صغير بين الضربات (كومبو سريع) await sleep(rand(150, 250)); }
this._log('✅', `كومبو اكتمل: ${this._comboCount} ضربة`); this.emit('combo', this._comboCount); }
// ═══ كريتيكال — ضربة قوية بالقفز ═══ async criticalHit(target) { if (!this.bot?.entity || !target) return; this._log('💥', `كريتيكال على ${target.name}`);
// اقفز this.bot.setControlState('jump', true); await sleep(rand(100, 200)); this.bot.setControlState('jump', false);
// اضرب وأنت نازل (في الهواء) await sleep(rand(100, 150)); try { await this.bot.attack(target); this._log('💥', 'كريتيكال نجح!'); this.emit('critical', target.name); } catch(_) {} }
// ═══ بلوك — حماية بالسيف ═══ async block(duration = 500) { if (!this.bot) return; this._log('🛡️', 'بلوك بالسيف');
// مسك زر يمين (بلوك) this.bot.activateItem(); // right click = block with sword await sleep(duration); this.bot.deactivateItem(); }
// ═══ سبارك — حركة سريعة للهجوم ═══ async sparkle(target) { if (!this.bot?.entity || !target) return; this._log('✨', `سبارك على ${target.name}`);
// سبرنت + اضرب this.bot.setControlState('sprint', true); await this._approach(target); try { await this.bot.attack(target); } catch(_) {} this.bot.setControlState('sprint', false);
// حركة جانبية بعد الضربة this._strafe(); }
// ═══ كومبو + كريتيكال ═══ async comboCritical(target, hits = 2) { if (!this.bot?.entity || !target) return;
// كومبو عادي await this.combo(target, hits);
// كريتيكال في الآخر await this.criticalHit(target); }
// ═══ هجوم مباغت ═══ async surpriseAttack(target) { if (!this.bot?.entity || !target) return; this._log(' surprise', `هجوم مباغت على ${target.name}`);
// امشي بشكل عادي this.bot.setControlState('forward', true); await sleep(rand(500, 1000)); this.bot.setControlState('forward', false);
// فجأة سبرنت + اضرب this.bot.setControlState('sprint', true); await this._approach(target); await sleep(rand(100, 200)); try { await this.bot.attack(target); // كومبو سريع for (let i = 0; i < 3; i++) { await sleep(rand(150, 250)); await this.bot.attack(target); } } catch(_) {} this.bot.setControlState('sprint', false); }
// ═══ مقاربة ═══ async _approach(target) { if (!this.bot?.entity || !target) return; const yaw = Math.atan2( target.position.z - this.bot.entity.position.z, target.position.x - this.bot.entity.position.x ); this.bot.look(yaw, 0, false); this.bot.setControlState('forward', true); await sleep(rand(200, 400)); this.bot.setControlState('forward', false); }
// ═══ حركة جانبية ═══ _strafe() { if (!this.bot) return; const dir = chance(50) ? 'left' : 'right'; this.bot.setControlState(dir, true); setTimeout(() => { try { this.bot.setControlState(dir, false); } catch(_) {} }, rand(200, 400)); }
// ═══ تحليل الأسلوب ═══ analyzeTarget(target) { if (!target) return { style: 'aggressive' }; const health = target.health || 20; const dist = this.bot?.entity?.position?.distanceTo(target.position) || 10;
if (health < 6) return { style: 'finishing', reason: 'health low' }; if (dist < 2) return { style: 'close', reason: 'very close' }; if (dist > 5) return { style: 'approaching', reason: 'far away' }; return { style: 'balanced' }; }
getStats() { return { comboCount: this._comboCount, lastHit: this._lastHit }; }
destroy() { this.removeAllListeners(); }}
module.exports = { SwordCombat };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238'use strict';/** * Team Combat — القتال الجماعي * تنسيق هجمات مع بوتات تانية، هدف مشترك، حماية الفريق */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const chance = pct => Math.random() * 100 < pct;
class TeamCombat extends EventEmitter { constructor(bot, team = []) { super(); this.bot = bot; this.team = team; // array of bot instances this._role = 'attacker'; // attacker, defender, support this._target = null; this._kills = 0; this._assists = 0; this._log('INIT', 'القتال الجماعي جاهز'); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [TEAM] ${tag} ${msg}`); }
// ═══ تعيين دور ═══ setRole(role) { const valid = ['attacker', 'defender', 'support']; if (valid.includes(role)) { this._role = role; this._log('🎯', `الدور الجديد: ${role}`); } }
// ═══ هجوم منسق ═══ async coordinatedAttack(target) { if (!this.bot?.entity || !target) return; this._log('⚔️', `هجوم منسق على ${target.name}`); this._target = target;
// كل واحد ياخد زاوية مختلفة const teamBots = this.team.filter(b => b.bot?.entity && b !== this); const angleStep = (Math.PI * 2) / (teamBots.length + 1);
// حدد زاوية البوت ده const myAngle = Math.random() * Math.PI * 2;
// امشي للزاوية const radius = 3; const targetX = target.position.x + Math.cos(myAngle) * radius; const targetZ = target.position.z + Math.sin(myAngle) * radius;
await this._walkTo({ x: targetX, y: target.position.y, z: targetZ });
// اضرب await this._attack(target); }
// ═══ هجوم مفاجئ من عدة اتجاهات ═══ async ambush(target) { if (!this.bot?.entity || !target) return; this._log('💀', `كمين على ${target.name}`);
// استنى الإشارة await sleep(rand(1000, 2000));
// هاجم من الخلف const behindAngle = Math.atan2( target.position.z - this.bot.entity.position.z, target.position.x - this.bot.entity.position.x ) + Math.PI;
const dist = 4; const posX = target.position.x + Math.cos(behindAngle) * dist; const posZ = target.position.z + Math.sin(behindAngle) * dist;
// امشي ورا الهدف this.bot.setControlState('sprint', true); await this._walkTo({ x: posX, y: target.position.y, z: posZ }); this.bot.setControlState('sprint', false);
// هاجم فجأة for (let i = 0; i < 5; i++) { if (!target || target.health <= 0) break; try { await this.bot.attack(target); } catch(_) {} await sleep(rand(150, 250)); } }
// ═══ حماية زميل ═══ async protectAlly(ally, attacker) { if (!this.bot?.entity || !ally || !attacker) return; this._log('🛡️', `حماية ${ally.username || 'زميل'}`);
// امشي بين الزميل والهجوم const midX = (ally.bot.entity.position.x + attacker.position.x) / 2; const midZ = (ally.bot.entity.position.z + attacker.position.z) / 2;
await this._walkTo({ x: midX, y: ally.bot.entity.position.y, z: midZ });
// هاجم المهاجم await this._attack(attacker); }
// ═══ دعم بالنار ═══ async rangedSupport(target) { if (!this.bot?.entity || !target) return; this._log('🏹', `دعم بالنار على ${target.name}`);
// ابعد شوية const yaw = Math.atan2( target.position.z - this.bot.entity.position.z, target.position.x - this.bot.entity.position.x ) + Math.PI; const dist = 8; await this._walkTo({ x: target.position.x + Math.cos(yaw) * dist, y: target.position.y, z: target.position.z + Math.sin(yaw) * dist, });
// رمي سهام const bow = this.bot.inventory.items().find(i => i.name === 'bow'); if (bow) { await this.bot.equip(bow, 'hand'); for (let i = 0; i < 5; i++) { if (!target || target.health <= 0) break; this.bot.activateItem(); await sleep(rand(400, 800)); this.bot.deactivateItem(); await sleep(rand(200, 400)); } } }
// ═══ تكتيكات متعددة ═══ async tacticFlank(target) { if (!this.bot?.entity || !target) return; this._log('🔀', 'تكتيكات التفاف');
// امشي على الجنب const side = chance(50) ? 1 : -1; const baseYaw = Math.atan2( target.position.z - this.bot.entity.position.z, target.position.x - this.bot.entity.position.x ); const flankYaw = baseYaw + (side * Math.PI / 3);
const dist = 5; await this._walkTo({ x: target.position.x + Math.cos(flankYaw) * dist, y: target.position.y, z: target.position.z + Math.sin(flankYaw) * dist, });
// هاجم من الجنب await this._attack(target); }
// ═══ هجوم مزدوج ═══ async pincer(target) { if (!this.bot?.entity || !target) return; this._log('🤏', 'هجوم مزدوج');
// دور على زميل قريب const ally = this.team.find(b => b !== this && b.bot?.entity && b.bot.entity.position?.distanceTo(target.position) < 10 );
if (ally) { // واحد من الأمام وواحد من ورا const myAngle = Math.atan2( target.position.z - this.bot.entity.position.z, target.position.x - this.bot.entity.position.x ); const oppAngle = myAngle + Math.PI;
// امشي للخلف await this._walkTo({ x: target.position.x + Math.cos(oppAngle) * 3, y: target.position.y, z: target.position.z + Math.sin(oppAngle) * 3, });
// اضرب await this._attack(target); } else { // لوحده — هجوم عادي await this._attack(target); } }
// ═══ مساعدة ═══ async _attack(target) { if (!this.bot?.entity || !target) return; try { await this.bot.attack(target); if (target.health <= 0) { this._kills++; this._log('💀', `قتل ${target.name} (إجمالي: ${this._kills})`); this.emit('kill', target.name); } } catch(_) {} }
async _walkTo(position) { if (!this.bot?.entity) return; const yaw = Math.atan2( position.z - this.bot.entity.position.z, position.x - this.bot.entity.position.x ); this.bot.look(yaw, 0, false); this.bot.setControlState('forward', true); await sleep(rand(300, 700)); this.bot.setControlState('forward', false); }
getStats() { return { role: this._role, kills: this._kills, assists: this._assists, teamSize: this.team.length, target: this._target?.name || null, }; }
destroy() { this.team = []; this._target = null; this.removeAllListeners(); }}
module.exports = { TeamCombat };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282'use strict';/** * Combat System — نظام القتال الواقعية * يكشف الوحوش، يهاجمها، يحمي نفسه، يستخدم الأسلحة المناسبة */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const chance = pct => Math.random() * 100 < pct;const dist = (a, b) => a.distanceTo(b);
const HOSTILE_MOBS = new Set([ 'zombie','skeleton','spider','creeper','enderman','witch', 'slime','phantom','drowned','husk','stray','cave_spider', 'blaze','ghast','magma_cube','witherskeleton','piglin_brute', 'vindicator','evoker','pillager','ravager','vex','warden', 'breeze','bogged']);
const WEAPON_RANK = { 'netherite_sword': 9, 'netherite_axe': 8, 'diamond_sword': 8, 'diamond_axe': 7, 'iron_sword': 6, 'iron_axe': 5, 'stone_sword': 4, 'stone_axe': 3, 'wooden_sword': 2, 'wooden_axe': 1, 'bow': 7, 'crossbow': 6, 'trident': 8,};
class CombatSystem extends EventEmitter { constructor(bot, config = {}) { super(); this.bot = bot; this.config = { aggroRange: 16, fleeHealthPct: 0.25, attackCooldown: 350, shieldSlot: 'off-hand', ...config, }; this._active = false; this._timers = []; this._fighting = false; this._lastAttack = 0; this._kills = 0; this._damageTaken = 0; this._log('INIT', 'Combat system جاهز'); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [COMBAT] ${tag} ${msg}`); }
start() { if (this._active) return; this._active = true; this._log('START', 'بدء نظام القتال');
// كشف الوحوش القريبة كل 2 ثانية this._addTimer(() => this._scanForHostiles(), 2000);
// مراقبة الصحة كل ثانية this._addTimer(() => this._checkHealth(), 1000);
// سلوك ليلي أكثر عدائية this._addTimer(() => this._nightBehavior(), 5000); }
stop() { this._active = false; this._timers.forEach(t => { try { clearInterval(t); clearTimeout(t); } catch(_) {} }); this._timers = []; this._fighting = false; this._log('STOP', 'إيقاف نظام القتال'); }
_addTimer(fn, interval) { const t = setInterval(() => { if (this._active) fn(); }, interval); this._timers.push(t); return t; }
// ═══ كشف الوحوش القريبة ═══ _scanForHostiles() { if (!this.bot?.entity || this._fighting) return; const pos = this.bot.entity.position; const hostiles = this.bot.entitiesArray.filter(e => { if (!e || e.type !== 'mob' || !e.name) return false; if (!HOSTILE_MOBS.has(e.name)) return false; if (!e.position) return false; return dist(pos, e.position) < this.config.aggroRange; });
if (hostiles.length > 0) { const closest = hostiles.sort((a, b) => dist(pos, a.position) - dist(pos, b.position))[0]; this._engage(closest); } }
// ═══ مهاجمة مخلوق معين ═══ async _engage(target) { if (this._fighting || !this.bot?.entity) return; this._fighting = true; this._log('⚔️', `هجوم على ${target.name}`);
try { // اختر أفضل سلاح متاح await this._equipBestWeapon();
// حط الدرع لو موجود await this._equipShield();
// هاجم لحد ما يموت أو تقل صحتنا while (this._active && this.bot?.entity && target && target.health > 0) { if (!this.bot?.entity) break;
// لو صحتنا قليلة، اهرب const health = this.bot.health; if (health && health < 6) { this._log('🏃', 'صحة قليلة — هروب!'); await this._flee(); break; }
// ا approached للهدف const d = dist(this.bot.entity.position, target.position); if (d > 3.5) { await this._walkTo(target.position); }
// اضرب if (Date.now() - this._lastAttack > this.config.attackCooldown) { try { await this.bot.attack(target); this._lastAttack = Date.now(); } catch(_) {} }
// حركات جانبية عشان يتجنب الهجمات if (chance(30)) { this._strafe(); }
await sleep(rand(100, 300)); }
if (target.health <= 0 || !target.entity) { this._kills++; this._log('💀', `قتل ${target.name} (إجمالي: ${this._kills})`); this.emit('kill', target.name); } } catch(e) { this._log('❌', `خطأ في القتال: ${e.message}`); } finally { this._fighting = false; } }
// ═══ اختيار أفضل سلاح ═══ async _equipBestWeapon() { if (!this.bot) return; const items = this.bot.inventory.items(); let bestWeapon = null; let bestRank = -1;
for (const item of items) { const rank = WEAPON_RANK[item.name] || 0; if (rank > bestRank) { bestRank = rank; bestWeapon = item; } }
if (bestWeapon) { try { await this.bot.equip(bestWeapon, 'hand'); } catch(_) {} } }
// ═══ وضع الدرع ═══ async _equipShield() { if (!this.bot) return; const shield = this.bot.inventory.items().find(i => i.name === 'shield'); if (shield) { try { await this.bot.equip(shield, 'off-hand'); } catch(_) {} } }
// ═══ حركة هروب ═══ async _flee() { if (!this.bot?.entity) return; const yaw = Math.random() * Math.PI * 2; this.bot.look(yaw, 0, false); this.bot.setControlState('forward', true); this.bot.setControlState('sprint', true); await sleep(rand(1500, 3000)); this.bot.setControlState('forward', false); this.bot.setControlState('sprint', false); }
// ═══ حركة جانبية ═══ _strafe() { if (!this.bot?.entity) return; const dir = chance(50) ? 'left' : 'right'; this.bot.setControlState(dir, true); setTimeout(() => { try { this.bot.setControlState(dir, false); } catch(_) {} }, rand(200, 500)); }
// ═══ المشي لهدف ═══ async _walkTo(position) { if (!this.bot?.entity) return; const yaw = Math.atan2( position.z - this.bot.entity.position.z, position.x - this.bot.entity.position.x ); this.bot.look(yaw, 0, false); this.bot.setControlState('forward', true); await sleep(rand(200, 500)); this.bot.setControlState('forward', false); }
// ═══ مراقبة الصحة ═══ _checkHealth() { if (!this.bot?.entity) return; const health = this.bot.health; if (health !== undefined && health < 4) { // أكل طعام لو متاح this._eatIfAvailable(); } }
// ═══ أكل لو متاح ═══ async _eatIfAvailable() { if (!this.bot) return; const food = this.bot.inventory.items().find(i => i.name.includes('bread') || i.name.includes('cooked') || i.name.includes('apple') || i.name.includes('steak') || i.name.includes('porkchop') || i.name.includes('chicken') ); if (food) { try { await this.bot.equip(food, 'hand'); await this.bot.consume(); this._log('🍖', 'أكل عشان يسترد الصحة'); } catch(_) {} } }
// ═══ سلوك ليلي ═══ _nightBehavior() { if (!this.bot?.entity) return; const time = this.bot.time?.age; if (time === undefined) return;
// الليل: أكثر عدائية، يدور على الوحوش const isNight = (time % 24000) > 12500 && (time % 24000) < 23000; if (isNight) { this.config.aggroRange = 24; // يشوف أبعد بالليل } else { this.config.aggroRange = 16; } }
getStats() { return { kills: this._kills, damageTaken: this._damageTaken, fighting: this._fighting, active: this._active, }; }
destroy() { this.stop(); this.removeAllListeners(); }}
module.exports = { CombatSystem, HOSTILE_MOBS };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150'use strict';
/** * ╔══════════════════════════════════════════════════════════════════════════╗ * Connection Manager — v19.0 | Smart Connection Pool + Version Cache ║ * ╠══════════════════════════════════════════════════════════════════════════╣ * ✅ DNS Cache: يحفظ DNS lookups لتسريع الاتصال ║ * ✅ Version Cache: يحفظ إصدار السيرفر المكتشف ║ * ✅ Connection Pool: إدارة اتصالات البوتات بذكاء ║ * ✅ Fast Reconnect: إعادة اتصال فورية مع state restore ║ * ✅ Smart Backoff: Exponential backoff + jitter ║ * ✅ Health Monitor: مراقبة صحة الاتصالات ║ * ╚══════════════════════════════════════════════════════════════════════════╝ */
const dns = require('dns');const { EventEmitter } = require('events');
const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const randInt = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const tsNow = () => new Date().toISOString().replace('T', ' ').slice(0, 19);
class ConnectionManager extends EventEmitter { constructor() { super(); this.dnsCache = new Map(); this.dnsCacheTTL = 300000; this.versionCache = new Map(); this.versionCacheTTL = 600000; this.connections = new Map(); this.healthHistory = new Map(); this._log('POOL', 'تم إنشاء Connection Manager'); }
_log(tag, msg) { const ts = tsNow(); console.log(`[${ts}] [CONN] ${tag} ${msg}`); }
async resolveDns(host) { const cached = this.dnsCache.get(host); if (cached && (Date.now() - cached.time) < this.dnsCacheTTL) { this._log('💾', `DNS cache hit: ${host} → ${cached.ip}`); return cached.ip; } return new Promise((resolve) => { dns.resolve4(host, (err, addresses) => { if (err) { this._log('⚠️', `DNS lookup failed: ${host} — ${err.code}`); this.emit('dnsFailed', host, err); resolve(host); return; } const ip = addresses[0]; this.dnsCache.set(host, { ip, time: Date.now() }); this._log('🌐', `DNS resolved: ${host} → ${ip}`); this.emit('dnsResolved', host, ip); resolve(ip); }); }); }
cacheVersion(host, port, version) { const key = `${host}:${port}`; this.versionCache.set(key, { version, time: Date.now() }); this._log('💾', `Version cached: ${key} → ${version}`); }
getCachedVersion(host, port) { const key = `${host}:${port}`; const cached = this.versionCache.get(key); if (cached && (Date.now() - cached.time) < this.versionCacheTTL) { return cached.version; } return null; }
clearVersionCache(host, port) { if (host && port) { this.versionCache.delete(`${host}:${port}`); } else { this.versionCache.clear(); } }
trackConnection(botId, data) { const existing = this.connections.get(botId) || { connects: 0, disconnects: 0, kicks: 0, errors: 0, avgPing: null, pings: [], lastConnect: null, lastDisconnect: null }; existing.connects++; existing.lastConnect = Date.now(); if (data.ping) { existing.pings.push(data.ping); if (existing.pings.length > 20) existing.pings.shift(); existing.avgPing = Math.round(existing.pings.reduce((a, b) => a + b, 0) / existing.pings.length); } this.connections.set(botId, existing); this.emit('connectionTracked', botId, 'connect', existing); }
trackDisconnect(botId, reason) { const existing = this.connections.get(botId) || { connects: 0, disconnects: 0, kicks: 0, errors: 0, avgPing: null, pings: [], lastConnect: null, lastDisconnect: null }; existing.disconnects++; existing.lastDisconnect = Date.now(); const reasonLower = (reason || '').toLowerCase(); if (reasonLower.includes('kick')) existing.kicks++; if (reasonLower.includes('error') || reasonLower.includes('fail')) existing.errors++; this.connections.set(botId, existing); this.emit('connectionTracked', botId, 'disconnect', existing); }
getConnectionStats(botId) { return this.connections.get(botId) || null; }
getAllStats() { const stats = {}; for (const [id, data] of this.connections) { stats[id] = { ...data }; } return stats; }
getReconnectDelay(attempt, baseMs = 10000, maxMs = 120000) { const exp = Math.min(attempt, 8); const base = baseMs * Math.pow(1.5, exp); const jitter = randInt(0, Math.floor(base * 0.2)); return Math.min(base + jitter, maxMs); }
clearDnsCache() { this.dnsCache.clear(); this._log('🗑️', 'تم مسح DNS cache'); }
getStatus() { return { dnsCacheSize: this.dnsCache.size, versionCacheSize: this.versionCache.size, connectionsTracked: this.connections.size, stats: this.getAllStats() }; }}
module.exports = { ConnectionManager };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193'use strict';/** * Crafting System — نظام الصناعة * يصنّع الأدوات، يدير الوصفات، يرتيب المخزون */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const chance = pct => Math.random() * 100 < pct;
const CRAFT_PRIORITY = [ { item: 'crafting_table', count: 1, desc: 'طاولة صناعة' }, { item: 'wooden_pickaxe', count: 1, desc: 'فأس خشبية' }, { item: 'wooden_axe', count: 1, desc: 'فأس خشبية' }, { item: 'furnace', count: 1, desc: 'فرن' }, { item: 'stone_pickaxe', count: 1, desc: 'فأس حجرية' }, { item: 'stone_axe', count: 1, desc: 'فأس حجرية' }, { item: 'chest', count: 2, desc: 'صندوق' }, { item: 'torch', count: 16, desc: 'مشاعل' }, { item: 'iron_pickaxe', count: 1, desc: 'فأس حديدية' }, { item: 'iron_sword', count: 1, desc: 'سيف حديدي' }, { item: 'shield', count: 1, desc: 'درع' },];
class CraftingSystem extends EventEmitter { constructor(bot, config = {}) { super(); this.bot = bot; this.config = { craftInterval: 20000, ...config, }; this._active = false; this._timers = []; this._crafting = false; this._itemsCrafted = 0; this._craftedItems = {}; this._log('INIT', 'نظام الصناعة جاهز'); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [CRAFT] ${tag} ${msg}`); }
start() { if (this._active) return; this._active = true; this._log('START', 'بدء نظام الصناعة');
this._addTimer(() => this._autoCraft(), this.config.craftInterval); }
stop() { this._active = false; this._crafting = false; this._timers.forEach(t => { try { clearInterval(t); clearTimeout(t); } catch(_) {} }); this._timers = []; this._log('STOP', 'إيقاف نظام الصناعة'); }
_addTimer(fn, interval) { const t = setInterval(() => { if (this._active) fn(); }, interval); this._timers.push(t); }
// ═══ صناعة تلقائية ═══ async _autoCraft() { if (this._crafting || !this.bot?.entity) return; if (chance(50)) return;
this._crafting = true; try { // دور على طاولة صناعة const table = this.bot.findBlock({ matching: this.bot.registry?.blocksByName?.crafting_table?.id, maxDistance: 16, count: 1, });
if (!table) { // اصنع طاولة صناعة await this._craftItem('crafting_table', 1); return; }
// جرّب تصنع أي حاجة من القائمة for (const recipe of CRAFT_PRIORITY) { if (this._craftedItems[recipe.item]) continue; const success = await this._craftItem(recipe.item, recipe.count); if (success) break; } } catch(e) { this._log('❌', `خطأ: ${e.message}`); } finally { this._crafting = false; } }
// ═══ صناعة صنف معين ═══ async _craftItem(itemName, count = 1) { if (!this.bot) return false;
try { const mcData = require('minecraft-data')(this.bot.version); const itemInfo = mcData.itemsByName[itemName]; if (!itemInfo) return false;
const table = this.bot.findBlock({ matching: this.bot.registry?.blocksByName?.crafting_table?.id, maxDistance: 16, count: 1, });
if (table) { await this._walkTo(table.position); await sleep(300); }
const recipe = this.bot.recipesFor(itemInfo.id, null, 1, table)[0]; if (recipe) { await this.bot.craft(recipe, count, table || null); this._itemsCrafted += count; this._craftedItems[itemName] = (this._craftedItems[itemName] || 0) + count; this._log('🔨', `صنّع ${itemName} x${count}`); this.emit('crafted', itemName, count); return true; } } catch(_) {} return false; }
// ═══ صهر في الفرن ═══ async _smeltItems(input, fuel, output, count = 1) { if (!this.bot) return false;
const furnace = this.bot.findBlock({ matching: this.bot.registry?.blocksByName?.furnace?.id, maxDistance: 16, count: 1, }); if (!furnace) return false;
try { await this._walkTo(furnace.position); await sleep(300); await this.bot.activateBlock(furnace); await sleep(1000); this.bot.closeWindow(); this._log('🔥', `صهر ${input} → ${output}`); this.emit('smelted', input, output); return true; } catch(_) {} return false; }
async _walkTo(position) { if (!this.bot?.entity) return; const yaw = Math.atan2( position.z - this.bot.entity.position.z, position.x - this.bot.entity.position.x ); this.bot.look(yaw, 0, false); this.bot.setControlState('forward', true); await sleep(rand(200, 500)); this.bot.setControlState('forward', false); }
// ═══ فحص لو محتاج حاجة ═══ needItem(itemName) { if (!this.bot) return false; return !this.bot.inventory.items().some(i => i.name === itemName); }
// ═══ فحص المخزون ═══ getItemCount(itemName) { if (!this.bot) return 0; return this.bot.inventory.items().filter(i => i.name === itemName).reduce((sum, i) => sum + i.count, 0); }
getStats() { return { itemsCrafted: this._itemsCrafted, craftedItems: { ...this._craftedItems }, crafting: this._crafting, active: this._active, }; }
destroy() { this.stop(); this.removeAllListeners(); }}
module.exports = { CraftingSystem, CRAFT_PRIORITY };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328'use strict';/** * Daily Routine — الذكاء اليومي * يحدد البوت إيه اللي محتاجه دلوقتي ويعمل إيه * شجرة قرار: شجرة → خشب → أدوات → حفر → بناء → طعام → نوم */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const chance = pct => Math.random() * 100 < pct;
// ═══ مراحل الحياة ═══const PHASES = { SURVIVE: { priority: 10, desc: 'بقاء: أكل + مأوى' }, TOOLS: { priority: 9, desc: 'أدوات: فأس + مجرفة' }, MINE: { priority: 8, desc: 'تعدين: حديد + ماس' }, BUILD: { priority: 7, desc: 'بناء: مزرعة + بيت' }, EXPLORE: { priority: 6, desc: 'استكشاف: أماكن جديدة' }, FARM: { priority: 5, desc: 'زراعة: محاصيل' }, CRAFT: { priority: 4, desc: 'صناعة: أدوات متطورة' }, SOCIAL: { priority: 3, desc: 'تواصل: مع لاعبين' }, REST: { priority: 2, desc: 'راحة: نوم' }, IDLE: { priority: 1, desc: '闲置: يدور على أي حاجة' },};
class DailyRoutine extends EventEmitter { constructor(bot, systems = {}) { super(); this.bot = bot; this.systems = systems; this._active = false; this._timers = []; this._currentPhase = 'IDLE'; this._phaseStart = Date.now(); this._decisions = []; this._completedTasks = new Set(); this._inventory = {}; this._dayCount = 0; this._log('INIT', 'الذكاء اليومي جاهز'); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [ROUTINE] ${tag} ${msg}`); }
start() { if (this._active) return; this._active = true; this._log('START', 'بدء الذكاء اليومي');
// فحص واتخاذ قرار كل 5 ثواني this._addTimer(() => this._decide(), 5000);
// تحديث المخزون كل 10 ثواني this._addTimer(() => this._scanInventory(), 10000);
// عدّ الأيام this._addTimer(() => this._checkDayNight(), 30000); }
stop() { this._active = false; this._timers.forEach(t => { try { clearInterval(t); clearTimeout(t); } catch(_) {} }); this._timers = []; this._log('STOP', 'إيقاف الذكاء اليومي'); }
_addTimer(fn, interval) { const t = setInterval(() => { if (this._active) fn(); }, interval); this._timers.push(t); }
// ═══ شجرة القرار الرئيسية ═══ _decide() { if (!this.bot?.entity) return;
const needs = this._analyzeNeeds(); const best = needs.sort((a, b) => b.urgency - a.urgency)[0];
if (best && best.phase !== this._currentPhase) { this._log('🧠', `تغيير: ${this._currentPhase} → ${best.phase} (${best.reason})`); this._currentPhase = best.phase; this._phaseStart = Date.now(); this._decisions.push({ phase: best.phase, reason: best.reason, time: Date.now() }); if (this._decisions.length > 50) this._decisions.shift();
this.emit('phaseChange', best.phase, best.reason); }
// نفّذ المرحلة الحالية this._executePhase(); }
// ═══ تحليل الاحتياجات ═══ _analyzeNeeds() { const needs = []; const health = this.bot.health || 20; const food = this.bot.food || 20; const time = this.bot.time?.age || 0; const dayTime = time % 24000; const isNight = dayTime > 13000 || dayTime < 1000; const inv = this._inventory;
// 1. بقاء: صحة قليلة أو جوع if (health < 10) { needs.push({ phase: 'SURVIVE', urgency: 100, reason: `صحة قليلة (${health})` }); } if (food < 10) { needs.push({ phase: 'SURVIVE', urgency: 95, reason: `جوع شديد (${food})` }); }
// 2. أدوات: ما عندوش فأس أو مجرفة if (!this._hasTool('axe')) { needs.push({ phase: 'TOOLS', urgency: 90, reason: 'ما عندوش فأس' }); } if (!this._hasTool('pickaxe')) { needs.push({ phase: 'TOOLS', urgency: 88, reason: 'ما عندوش مجرفة' }); }
// 3. تعدين: لو عندو أدوات حجرية أو أعلى if (this._hasTool('pickaxe') && !inv.iron_ingot) { needs.push({ phase: 'MINE', urgency: 75, reason: 'محتاج حديد' }); } if (inv.iron_ingot && !inv.diamond) { needs.push({ phase: 'MINE', urgency: 70, reason: 'محتاج ماس' }); }
// 4. بناء: لو عندو خشب كافي if ((inv.oak_planks || 0) > 16) { needs.push({ phase: 'BUILD', urgency: 60, reason: 'عندو خشب كافي للبناء' }); }
// 5. زراعة: لو عندو بذور if (inv.wheat_seeds || inv.carrot || inv.potato) { needs.push({ phase: 'FARM', urgency: 55, reason: 'عندو بذور للزراعة' }); }
// 6. استكشاف: لو النهار ومافيش حاجة مهمة if (!isNight && needs.length < 3) { needs.push({ phase: 'EXPLORE', urgency: 40, reason: 'النهار — يستكشف' }); }
// 7. صناعة: لو عندو مواد خام if (inv.raw_iron || inv.cobblestone) { needs.push({ phase: 'CRAFT', urgency: 50, reason: 'عندو مواد خام للصناعة' }); }
// 8. تواصل: لو فيه لاعبين قريبين const nearby = this._getNearbyPlayers(); if (nearby.length > 0) { needs.push({ phase: 'SOCIAL', urgency: 35, reason: `${nearby.length} لاعب قريب` }); }
// 9. نوم: لو الليل if (isNight) { needs.push({ phase: 'REST', urgency: 80, reason: 'الليل — محتاج ينام' }); }
// 10.闲置: لو مافيش حاجة if (needs.length === 0) { needs.push({ phase: 'IDLE', urgency: 5, reason: 'مافيش حاجة مهمة' }); }
return needs; }
// ═══ تنفيذ المرحلة ═══ _executePhase() { if (!this.bot?.entity) return;
switch (this._currentPhase) { case 'SURVIVE': this._executeSurvive(); break; case 'TOOLS': this._executeTools(); break; case 'MINE': this._executeMine(); break; case 'BUILD': this._executeBuild(); break; case 'EXPLORE': this._executeExplore(); break; case 'FARM': this._executeFarm(); break; case 'CRAFT': this._executeCraft(); break; case 'SOCIAL': this._executeSocial(); break; case 'REST': this._executeRest(); break; case 'IDLE': this._executeIdle(); break; } }
// ═══ حفظ بقاء ═══ _executeSurvive() { const sys = this.systems.survival; if (sys) sys._eat(); }
// ═══ صناعة أدوات ═══ _executeTools() { const sys = this.systems.crafting; if (!sys) return;
if (!this._hasTool('axe')) { sys._craftItem('wooden_axe', 1); sys._craftItem('wooden_pickaxe', 1); } }
// ═══ تعدين ═══ _executeMine() { const sys = this.systems.mining; if (sys) sys._scanForOres(); }
// ═══ بناء ═══ _executeBuild() { const sys = this.systems.building; if (sys && !this._completedTasks.has('first_shelter')) { sys.buildShelter().then(() => this._completedTasks.add('first_shelter')); } }
// ═══ استكشاف ═══ _executeExplore() { const sys = this.systems.exploration; if (sys) sys._autoExplore(); }
// ═══ زراعة ═══ _executeFarm() { const sys = this.systems.farming; if (sys) sys._autoFarm(); }
// ═══ صناعة ═══ _executeCraft() { const sys = this.systems.crafting; if (sys) sys._autoCraft(); }
// ═══ تواصل ═══ _executeSocial() { const sys = this.systems.social; if (sys) sys._randomChat(); }
// ═══ نوم ═══ _executeRest() { const sys = this.systems.sleeping; if (sys) sys._trySleep(); }
// ═══闲置 ═══ _executeIdle() { if (chance(30)) { // يدور على أي حاجة يسويها this.bot.setControlState('forward', true); setTimeout(() => { try { this.bot.setControlState('forward', false); } catch(_) {} }, rand(1000, 3000)); } }
// ═══ فحص المخزون ═══ _scanInventory() { if (!this.bot) return; const items = this.bot.inventory.items(); this._inventory = {}; for (const item of items) { this._inventory[item.name] = (this._inventory[item.name] || 0) + item.count; } }
_hasTool(type) { if (!this.bot) return false; return this.bot.inventory.items().some(i => i.name.includes(type)); }
// ═══ فحص ليل/نهار ═══ _checkDayNight() { const time = this.bot.time?.age; if (time === undefined) return; const dayTime = time % 24000; const isNight = dayTime > 13000 || dayTime < 1000; if (isNight && this._currentPhase !== 'REST') { this._log('🌙', 'الليل — يروح ينام'); this.emit('nightTime'); } }
_getNearbyPlayers() { if (!this.bot?.entity) return []; return Object.values(this.bot.players || {}) .filter(p => p.username !== this.bot.username && p.entity && p.entity.position?.distanceTo(this.bot.entity.position) < 16); }
getStats() { return { currentPhase: this._currentPhase, phaseDesc: PHASES[this._currentPhase]?.desc || '', dayCount: this._dayCount, decisions: this._decisions.length, completedTasks: this._completedTasks.size, inventory: { ...this._inventory }, active: this._active, }; }
destroy() { this.stop(); this.removeAllListeners(); }}
module.exports = { DailyRoutine, PHASES };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214'use strict';/** * Exploration System — نظام الاستكشاف * يدور على أماكن جديدة، يكتشف أ biome جديدة، يحفظ مواقع مهمة */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const chance = pct => Math.random() * 100 < pct;
const BIOMES_OF_INTEREST = new Set([ 'jungle','bamboo_jungle','mushroom_fields','flower_forest', 'dark_forest','birch_forest','mesa','savanna','ice_spikes', 'deep_dark','cherry_grove','mangrove_swamp',]);
class ExplorationSystem extends EventEmitter { constructor(bot, config = {}) { super(); this.bot = bot; this.config = { exploreRadius: 64, waypointInterval: 30000, ...config, }; this._active = false; this._timers = []; this._exploring = false; this._waypoints = []; this._distanceTraveled = 0; this._placesFound = []; this._log('INIT', 'نظام الاستكشاف جاهز'); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [EXPLORE] ${tag} ${msg}`); }
start() { if (this._active) return; this._active = true; this._log('START', 'بدء نظام الاستكشاف');
this._addTimer(() => this._autoExplore(), 15000); this._addTimer(() => this._recordWaypoint(), this.config.waypointInterval); }
stop() { this._active = false; this._exploring = false; this._timers.forEach(t => { try { clearInterval(t); clearTimeout(t); } catch(_) {} }); this._timers = []; this._log('STOP', 'إيقاف نظام الاستكشاف'); }
_addTimer(fn, interval) { const t = setInterval(() => { if (this._active) fn(); }, interval); this._timers.push(t); }
// ═══ استكشاف تلقائي ═══ async _autoExplore() { if (this._exploring || !this.bot?.entity) return; if (chance(60)) return;
this._exploring = true; try { const yaw = Math.random() * Math.PI * 2; const distance = rand(20, 50);
this._log('🗺️', `استكشاف: ${distance} بلوك باتجاه ${Math.round(yaw * 180 / Math.PI)}°`); this.bot.look(yaw, 0, false); this.bot.setControlState('forward', true); if (chance(40)) this.bot.setControlState('sprint', true);
await sleep(distance * 300);
this.bot.setControlState('forward', false); this.bot.setControlState('sprint', false); this._distanceTraveled += distance;
// فحص إذا لقينا حاجة مهمة this._checkInteresting(); } catch(_) {} finally { this._exploring = false; } }
// ═══ فحص أماكن مهمة ═══ _checkInteresting() { if (!this.bot?.entity) return; const pos = this.bot.entity.position;
// فحص كهف const caveBlock = this._findCave(); if (caveBlock) { this._placesFound.push({ type: 'cave', pos: { ...pos }, time: Date.now() }); this._log('🕳️', 'لقى كهف!'); this.emit('found', 'cave', pos); }
// فحص بيت لاعب const house = this._findPlayerHouse(); if (house) { this._placesFound.push({ type: 'house', pos: { ...pos }, time: Date.now() }); this._log('🏠', 'لقى بيت لاعب!'); this.emit('found', 'house', pos); }
// فحص شجرة كبيرة const bigTree = this._findBigTree(); if (bigTree) { this._log('🌳', 'لقى شجرة كبيرة'); } }
_findCave() { if (!this.bot?.entity) return null; const pos = this.bot.entity.position; for (let x = -8; x <= 8; x++) { for (let z = -8; z <= 8; z++) { for (let y = -4; y <= 2; y++) { const block = this.bot.blockAt(pos.offset(x, y, z)); if (block && block.name === 'air') { const below = this.bot.blockAt(pos.offset(x, y - 1, z)); if (below && (below.name === 'stone' || below.name === 'deepslate')) { return block; } } } } } return null; }
_findPlayerHouse() { if (!this.bot?.entity) return null; const pos = this.bot.entity.position; for (let x = -16; x <= 16; x += 2) { for (let z = -16; z <= 16; z += 2) { const block = this.bot.blockAt(pos.offset(x, 0, z)); if (block && (block.name.includes('plank') || block.name.includes('brick'))) { return block; } } } return null; }
_findBigTree() { if (!this.bot?.entity) return null; const pos = this.bot.entity.position; for (let x = -8; x <= 8; x++) { for (let z = -8; z <= 8; z++) { const block = this.bot.blockAt(pos.offset(x, 4, z)); if (block && block.name.includes('leaves')) { return block; } } } return null; }
// ═══ حفظ نقطة مرجعية ═══ _recordWaypoint() { if (!this.bot?.entity) return; const pos = this.bot.entity.position; this._waypoints.push({ x: Math.round(pos.x), y: Math.round(pos.y), z: Math.round(pos.z), time: Date.now(), }); if (this._waypoints.length > 50) this._waypoints.shift(); }
// ═══ الرجوع للنقطة الأخيرة ═══ async returnToLastWaypoint() { if (!this.bot?.entity || this._waypoints.length === 0) return; const wp = this._waypoints[this._waypoints.length - 1]; await this._walkTo({ x: wp.x, y: wp.y, z: wp.z }); }
async _walkTo(position) { if (!this.bot?.entity) return; const yaw = Math.atan2( position.z - this.bot.entity.position.z, position.x - this.bot.entity.position.x ); this.bot.look(yaw, 0, false); this.bot.setControlState('forward', true); await sleep(rand(500, 1500)); this.bot.setControlState('forward', false); }
getStats() { return { distanceTraveled: this._distanceTraveled, placesFound: this._placesFound.length, waypoints: this._waypoints.length, exploring: this._exploring, active: this._active, }; }
destroy() { this.stop(); this.removeAllListeners(); }}
module.exports = { ExplorationSystem, BIOMES_OF_INTEREST };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213'use strict';/** * Farming System — نظام الزراعة * يزرع المحاصيل، يسقيها، يحصد، يبني مزرعة */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const chance = pct => Math.random() * 100 < pct;
const CROP_SEEDS = [ 'wheat_seeds','beetroot_seeds','melon_seeds','pumpkin_seeds',];
const CROP_ITEMS = [ 'wheat','beetroot','melon_slice','pumpkin', 'carrot','potato','nether_wart',];
class FarmingSystem extends EventEmitter { constructor(bot, config = {}) { super(); this.bot = bot; this.config = { farmRadius: 8, harvestInterval: 30000, ...config, }; this._active = false; this._timers = []; this._farming = false; this._cropsPlanted = 0; this._cropsHarvested = 0; this._waterPlaced = false; this._log('INIT', 'نظام الزراعة جاهز'); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [FARM] ${tag} ${msg}`); }
start() { if (this._active) return; this._active = true; this._log('START', 'بدء نظام الزراعة');
this._addTimer(() => this._autoFarm(), this.config.harvestInterval); }
stop() { this._active = false; this._farming = false; this._timers.forEach(t => { try { clearInterval(t); clearTimeout(t); } catch(_) {} }); this._timers = []; this._log('STOP', 'إيقاف نظام الزراعة'); }
_addTimer(fn, interval) { const t = setInterval(() => { if (this._active) fn(); }, interval); this._timers.push(t); }
// ═══ زراعة تلقائية ═══ async _autoFarm() { if (this._farming || !this.bot?.entity) return; if (chance(40)) return;
this._farming = true; try { // دور على أرض مزروعة قريبة const farmLand = this._findFarmLand(); if (farmLand) { await this._harvestCrops(farmLand); await this._plantCrops(farmLand); } else { // ابني مزرعة جديدة await this._buildFarm(); } } catch(e) { this._log('❌', `خطأ: ${e.message}`); } finally { this._farming = false; } }
// ═══ دور على أرض مزروعة ═══ _findFarmLand() { if (!this.bot?.entity) return null; const pos = this.bot.entity.position; for (let x = -this.config.farmRadius; x <= this.config.farmRadius; x++) { for (let z = -this.config.farmRadius; z <= this.config.farmRadius; z++) { const block = this.bot.blockAt(pos.offset(x, -1, z)); if (block && block.name === 'farmland') { return block; } } } return null; }
// ═══ حصد المحاصيل ═══ async _harvestCrops(farmLand) { if (!this.bot?.entity) return; const pos = farmLand.position;
for (let x = -2; x <= 2; x++) { for (let z = -2; z <= 2; z++) { const crop = this.bot.blockAt(pos.offset(x, 1, z)); if (!crop) continue;
// فحص لو المحصول ناضج (الكتلة فيها wheat بارتفاع 7) if (crop.name === 'wheat' || crop.name === 'beetroots' || crop.name === 'carrots' || crop.name === 'potatoes') { if (crop.metadata >= 7 || crop.stateId) { try { await this.bot.dig(crop); this._cropsHarvested++; await sleep(rand(50, 150)); } catch(_) {} } } } } }
// ═══ زراعة بذور ═══ async _plantCrops(farmLand) { if (!this.bot?.entity) return; const pos = farmLand.position;
// دور على بذور في المخزون const seeds = this.bot.inventory.items().find(i => CROP_SEEDS.includes(i.name) || i.name === 'carrot' || i.name === 'potato' ); if (!seeds) return;
try { await this.bot.equip(seeds, 'hand'); for (let x = -2; x <= 2; x++) { for (let z = -2; z <= 2; z++) { if (!this.bot?.entity) break; const block = this.bot.blockAt(pos.offset(x, -1, z)); const above = this.bot.blockAt(pos.offset(x, 0, z)); if (block?.name === 'farmland' && above?.name === 'air') { try { await this.bot.placeBlock(block, { x: 0, y: 1, z: 0 }); this._cropsPlanted++; await sleep(rand(50, 100)); } catch(_) {} } } } } catch(_) {} }
// ═══ بناء مزرعة جديدة ═══ async _buildFarm() { if (!this.bot?.entity) return; const hoe = this.bot.inventory.items().find(i => i.name.includes('hoe')); if (!hoe) return;
await this.bot.equip(hoe, 'hand'); const pos = this.bot.entity.position; const base = { x: Math.round(pos.x), y: Math.round(pos.y), z: Math.round(pos.z) };
// حرث الأرض 5x5 for (let x = -2; x <= 2; x++) { for (let z = -2; z <= 2; z++) { if (!this.bot?.entity) break; const block = this.bot.blockAt({ x: base.x + x, y: base.y - 1, z: base.z + z }); if (block && (block.name === 'grass_block' || block.name === 'dirt')) { try { await this.bot.activateBlock(block); await sleep(rand(100, 200)); } catch(_) {} } } }
// ضع ماء في النص const water = this.bot.inventory.items().find(i => i.name === 'water_bucket'); if (water) { try { await this.bot.equip(water, 'hand'); const center = this.bot.blockAt({ x: base.x, y: base.y - 1, z: base.z }); if (center) { await this.bot.placeBlock(center, { x: 0, y: 0, z: 0 }); this._waterPlaced = true; } } catch(_) {} }
this._log('🌾', 'بنى مزرعة جديدة'); this.emit('builtFarm'); }
getStats() { return { cropsPlanted: this._cropsPlanted, cropsHarvested: this._cropsHarvested, farming: this._farming, active: this._active, }; }
destroy() { this.stop(); this.removeAllListeners(); }}
module.exports = { FarmingSystem, CROP_SEEDS, CROP_ITEMS };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148{ "version": "19.0", "categories": { "protection": { "name": "الحماية", "icon": "shield", "order": 1, "color": "#3b82f6" }, "performance": { "name": "الأداء", "icon": "zap", "order": 2, "color": "#22c55e" }, "economy": { "name": "الاقتصاد", "icon": "coins", "order": 3, "color": "#f59e0b" }, "player": { "name": "اللاعبين", "icon": "users", "order": 4, "color": "#8b5cf6" }, "world": { "name": "العوالم", "icon": "globe", "order": 5, "color": "#06b6d4" }, "fun": { "name": "الترفيه", "icon": "gamepad", "order": 6, "color": "#ec4899" }, "admin": { "name": "الإدارة", "icon": "settings", "order": 7, "color": "#ef4444" }, "bots": { "name": "البوتات", "icon": "bot", "order": 8, "color": "#10b981" } }, "features": { "worldguard": { "id": "worldguard", "name": "WorldGuard", "category": "protection", "enabled": true, "description": "حماية المناطق من التخريب والتعديل", "commands": ["/rg define", "/rg flag", "/rg info"], "dependencies": [], "config": { "autoCreateSpawnRegion": true, "spawnRadius": 50 } }, "worldedit": { "id": "worldedit", "name": "WorldEdit", "category": "protection", "enabled": true, "description": "أداة تعديل الخريطة المتقدمة", "commands": ["/set", "/replace", "//copy", "//paste"], "dependencies": [], "config": { "maxRegion": 10000 } }, "coreprotect": { "id": "coreprotect", "name": "CoreProtect", "category": "protection", "enabled": true, "description": "تسجيل التعديلات وإمكانية التراجع", "commands": ["/co i", "/co restore", "/co lookup"], "dependencies": [], "config": { "retentionDays": 30 } }, "griefprevention": { "id": "griefprevention", "name": "GriefPrevention", "category": "protection", "enabled": true, "description": "منع الـ grief وحماية الأراضي بالفأس", "commands": ["/trust", "/accesstrust", "/containertrust"], "dependencies": [], "config": { "initialClaimBlocks": 100 } }, "anticheat": { "id": "anticheat", "name": "AntiCheat", "category": "protection", "enabled": true, "description": "كشف الغش والـ hacks", "commands": [], "dependencies": [], "config": { "punishment": "kick", "sensitivity": "medium" } }, "combatlog": { "id": "combatlog", "name": "CombatLog", "category": "protection", "enabled": true, "description": "منع الفرار من القتال", "commands": [], "dependencies": [], "config": { "combatTime": 10 } }, "spawnprotection": { "id": "spawnprotection", "name": "SpawnProtection", "category": "protection", "enabled": true, "description": "حماية المنطقة الأولية (Spawn)", "commands": [], "dependencies": [], "config": { "radius": 10 } }, "lwc": { "id": "lwc", "name": "LWC (_LOCK_)", "category": "protection", "enabled": false, "description": "حماية الصناديق والأبواب بالقفل", "commands": ["/lock", "/unlock", "/cinfo"], "dependencies": [], "config": {} }, "redprotect": { "id": "redprotect", "name": "RedProtect", "category": "protection", "enabled": false, "description": "حماية مناطق متقدمة مع صلاحيات", "commands": ["/rp create", "/rp flag"], "dependencies": [], "config": {} }, "towny": { "id": "towny", "name": "Towny", "category": "protection", "enabled": false, "description": "نظام مدن وأراضي كامل", "commands": ["/town new", "/town claim", "/nation new"], "dependencies": [], "config": { "startingGold": 300 } }, "factions": { "id": "factions", "name": "Factions", "category": "protection", "enabled": false, "description": "نظام فصائل وحروب", "commands": ["/f create", "/f claim", "/f enemy"], "dependencies": [], "config": {} }, "lands": { "id": "lands", "name": "Lands", "category": "protection", "enabled": false, "description": "نظام أراضي مبسط وقوي", "commands": ["/lands claim", "/lands trust"], "dependencies": [], "config": {} }, "playerwarps": { "id": "playerwarps", "name": "PlayerWarps", "category": "protection", "enabled": false, "description": "نقاط teleport خاصة باللاعبين", "commands": ["/pwarp", "/pw create"], "dependencies": [], "config": {} }, "antiexplosion": { "id": "antiexplosion", "name": "AntiExplosion", "category": "protection", "enabled": false, "description": "منع الانفجارات في المناطق المحمية", "commands": [], "dependencies": [], "config": {} }, "antispam": { "id": "antispam", "name": "AntiSpam", "category": "protection", "enabled": false, "description": "منع السبام في الشات", "commands": [], "dependencies": [], "config": { "cooldown": 3 } },
"clearlag": { "id": "clearlag", "name": "ClearLag", "category": "performance", "enabled": true, "description": "تنظيف الـ entities الزائدة لتقليل الـ lag", "commands": ["/lagg clear", "/lagg check"], "dependencies": [], "config": { "intervalMinutes": 10, "removeItems": true, "removeMobs": false } }, "spark": { "id": "spark", "name": "Spark", "category": "performance", "enabled": true, "description": "أداة مراقبة أداء متقدمة — TPS وRAM", "commands": ["/spark profiler", "/spark gc", "/spark health"], "dependencies": [], "config": { "profilerDuration": 60 } }, "chunky": { "id": "chunky", "name": "Chunky", "category": "performance", "enabled": true, "description": "يولّد الـ chunks مسبقاً لمنع الـ lag", "commands": ["/chunky start", "/chunky stop", "/chunky progress"], "dependencies": [], "config": { "radius": 5000 } }, "laggremover": { "id": "laggremover", "name": "NoLagg", "category": "performance", "enabled": true, "description": "يزيل entities ونواتج البناء لتحسين الأداء", "commands": ["/lagg clear", "/lagg examine"], "dependencies": [], "config": {} }, "farmcontrol": { "id": "farmcontrol", "name": "FarmControl", "category": "performance", "enabled": true, "description": "يتحكم في حجم المزارع لمنع الـ lag", "commands": ["/farmcontrol stats"], "dependencies": [], "config": { "maxEntitiesPerChunk": 50 } }, "entityclearer": { "id": "entityclearer", "name": "EntityClearer", "category": "performance", "enabled": true, "description": "ينظف الـ entities تلقائياً", "commands": [], "dependencies": [], "config": { "intervalMinutes": 15, "keepFarmAnimals": true } }, "tpsmonitor": { "id": "tpsmonitor", "name": "TPSMonitor", "category": "performance", "enabled": true, "description": "مراقبة TPS مع تنبيهات", "commands": ["/tps"], "dependencies": [], "config": { "alertThreshold": 15 } }, "performanceplus": { "id": "performanceplus", "name": "PerformancePlus", "category": "performance", "enabled": false, "description": "تحسين عام للأداء", "commands": [], "dependencies": [], "config": {} }, "fastasyncworldedit": { "id": "fastasyncworldedit", "name": "FastAsyncWorldEdit", "category": "performance", "enabled": false, "description": "نسخة أسرع من WorldEdit", "commands": [], "dependencies": [], "config": {} }, "optimizedgenerators": { "id": "optimizedgenerators", "name": "OptimizedGenerators", "category": "performance", "enabled": false, "description": "تحسين المولدات", "commands": [], "dependencies": [], "config": {} }, "pufferfish": { "id": "pufferfish", "name": "Pufferfish", "category": "performance", "enabled": false, "description": "تحسينات أداء Paper المتقدمة", "commands": [], "dependencies": [], "config": {} },
"essentials_eco": { "id": "essentials_eco", "name": "EssentialsX Economy", "category": "economy", "enabled": true, "description": "نظام اقتصاد أساسي", "commands": ["/balance", "/pay", "/baltop"], "dependencies": ["vault"], "config": { "startingBalance": 1000, "maxBalance": 1000000 } }, "shopguiplus": { "id": "shopguiplus", "name": "ShopGUI+", "category": "economy", "enabled": true, "description": "متجر GUI سهل الاستخدام", "commands": ["/shop"], "dependencies": ["vault"], "config": { "defaultCurrency": "dollars" } }, "auctionhouse": { "id": "auctionhouse", "name": "AuctionHouse", "category": "economy", "enabled": false, "description": "نظام مزادات للاعبين", "commands": ["/ah list", "/ah browse", "/ah bid"], "dependencies": ["vault"], "config": { "maxListings": 10, "listingFee": 50 } }, "jobs": { "id": "jobs", "name": "Jobs", "category": "economy", "enabled": false, "description": "نظام وظائف ومهمات", "commands": ["/jobs browse", "/jobs join", "/jobs stats"], "dependencies": ["vault"], "config": { "maxJobs": 3 } }, "crates": { "id": "crates", "name": "Crates", "category": "economy", "enabled": false, "description": "نظام صناديق العشوائية", "commands": ["/crate", "/crate key"], "dependencies": [], "config": { "dailyKeys": 1 } }, "mcmmo": { "id": "mcmmo", "name": "mcMMO", "category": "economy", "enabled": false, "description": "نظام مهارات RPG مع Economy", "commands": ["/mcstats", "/mctop"], "dependencies": [], "config": {} }, "skills": { "id": "skills", "name": "AureliumSkills", "category": "economy", "enabled": false, "description": "نظام مهارات متقدم", "commands": ["/skills", "/skills top"], "dependencies": [], "config": {} }, "tokenmanager": { "id": "tokenmanager", "name": "TokenManager", "category": "economy", "enabled": false, "description": "نظام توكنات", "commands": ["/token", "/token pay", "/token shop"], "dependencies": [], "config": {} }, "votifier": { "id": "votifier", "name": "Votifier", "category": "economy", "enabled": false, "description": "مكافآت التصويت", "commands": [], "dependencies": [], "config": {} }, "luckyblocks": { "id": "luckyblocks", "name": "LuckyBlocks", "category": "economy", "enabled": false, "description": "صندوق حظ مع مكافآت عشوائية", "commands": [], "dependencies": [], "config": {} },
"essentials_cmds": { "id": "essentials_cmds", "name": "EssentialsX Commands", "category": "player", "enabled": true, "description": "أوامر أساسية: /tpa, /spawn, /home, AFK", "commands": ["/tpa", "/tpahere", "/spawn", "/sethome", "/home", "/afk", "/back", "/warp"], "dependencies": [], "config": { "tpaCooldown": 60, "tpaTimeout": 60 } }, "luckperms": { "id": "luckperms", "name": "LuckPerms", "category": "admin", "enabled": true, "description": "إدارة الصلاحيات المتقدمة", "commands": ["/lp user", "/lp group", "/lp editor"], "dependencies": [], "config": { "defaultGroup": "default" } }, "tab": { "id": "tab", "name": "TAB", "category": "player", "enabled": true, "description": "تخصيص قائمة اللاعبين (TAB list)", "commands": ["/tab"], "dependencies": [], "config": { "header": "&6مرحباً بك!", "footer": "&7Sayed Bot Server" } }, "placeholderapi": { "id": "placeholderapi", "name": "PlaceholderAPI", "category": "player", "enabled": true, "description": "API للـ placeholders للبلاجن الأخرى", "commands": ["/papi list", "/papi register"], "dependencies": [], "config": {} }, "skinsrestorer": { "id": "skinsrestorer", "name": "SkinsRestorer", "category": "player", "enabled": true, "description": "استعادة الـ skins في السيرفرات offline", "commands": ["/skin set", "/skin player", "/skin clear"], "dependencies": [], "config": { "allowCustomSkins": true } }, "discordsrv": { "id": "discordsrv", "name": "DiscordSRV", "category": "admin", "enabled": true, "description": "ربط السيرفر بـ Discord", "commands": ["/discordsrv"], "dependencies": [], "config": { "channelLink": "" } }, "dynmap": { "id": "dynmap", "name": "Dynmap", "category": "world", "enabled": true, "description": "خريطة ديناميكية للسيرفر على المتصفح", "commands": ["/dynmap fullrender", "/dynmap reload"], "dependencies": [], "config": { "webPort": 8123 } }, "bluemap": { "id": "bluemap", "name": "BlueMap", "category": "world", "enabled": false, "description": "خريطة ثلاثية الأبعاد على المتصفح", "commands": [], "dependencies": [], "config": { "webPort": 8100 } }, "chatmanager": { "id": "chatmanager", "name": "ChatManager", "category": "player", "enabled": true, "description": "إدارة وتنسيق الشات", "commands": ["/chatformat"], "dependencies": [], "config": { "chatFormat": "&7[%group%] &f%name%: &r%message%" } }, "afkplus": { "id": "afkplus", "name": "AntiAFK+", "category": "player", "enabled": true, "description": "منع طرد AFK في Aternos", "commands": [], "dependencies": [], "config": { "kickTime": 0 } }, "nightmare": { "id": "nightmare", "name": "Nightmare", "category": "fun", "enabled": false, "description": "إضافة مخلوقات مرعبة ليلية", "commands": [], "dependencies": [], "config": {} }, "customcommands": { "id": "customcommands", "name": "CustomCommands", "category": "player", "enabled": false, "description": "أوامر مخصصة حسب رغبتك", "commands": [], "dependencies": [], "config": { "commands": [] } }, "nicknames": { "id": "nicknames", "name": "Nicknames", "category": "player", "enabled": false, "description": "تغيير الأسماء المستعارة", "commands": ["/nick", "/nick other"], "dependencies": [], "config": {} }, "head数据库": { "id": "heads", "name": "HeadsDatabase", "category": "player", "enabled": false, "description": "آلاف رؤوس اللاعبين للزينة", "commands": ["/heads"], "dependencies": [], "config": {} }, "armorstandtools": { "id": "armorstandtools", "name": "ArmorStandTools", "category": "fun", "enabled": false, "description": "تخصيص دروع الخشب المتقدمة", "commands": ["/ast"], "dependencies": [], "config": {} }, "silkspawner": { "id": "silkspawner", "name": "SilkSpawners", "category": "player", "enabled": false, "description": "نقل مولدات المخلوقات بالـ silk touch", "commands": ["/spawner"], "dependencies": [], "config": {} },
"multiverse": { "id": "multiverse", "name": "Multiverse-Core", "category": "world", "enabled": true, "description": "إدارة عوالم متعددة", "commands": ["/mv create", "/mv tp", "/mv list", "/mv import"], "dependencies": [], "config": { "firstWorld": "world" } }, "multiverse_inventories": { "id": "multiverse_inventories", "name": "MV-Inventories", "category": "world", "enabled": false, "description": "مخزونات منفصلة لكل عالم", "commands": [], "dependencies": ["multiverse"], "config": {} }, "plotme": { "id": "plotme", "name": "PlotMe", "category": "world", "enabled": false, "description": "نظام مساحات بناء (Plot)", "commands": ["/plotme claim", "/plotme home"], "dependencies": [], "config": { "plotSize": 128 } }, "myworlds": { "id": "myworlds", "name": "MyWorlds", "category": "world", "enabled": false, "description": "إدارة عوالم مع teleport وحماية", "commands": ["/world tp", "/world create"], "dependencies": [], "config": {} }, "voidgen": { "id": "voidgen", "name": "VoidGen", "category": "world", "enabled": false, "description": "توليد عوالم فارغة (SkyBlock)", "commands": [], "dependencies": ["multiverse"], "config": {} }, "worldborder": { "id": "worldborder", "name": "WorldBorder", "category": "world", "enabled": false, "description": "حدود عالم مخصصة", "commands": ["/wb set", "/wb fill"], "dependencies": [], "config": {} }, "netherportals": { "id": "netherportals", "name": "NetherPortals", "category": "world", "enabled": false, "description": "تخصيص بوابات الـ Nether", "commands": [], "dependencies": [], "config": {} }, "timecontrol": { "id": "timecontrol", "name": "TimeControl", "category": "world", "enabled": false, "description": "تحكم في الوقت والطقس", "commands": ["/timeset", "/weatherset"], "dependencies": [], "config": {} },
"bedwars": { "id": "bedwars", "name": "BedWars", "category": "fun", "enabled": false, "description": "لعبة BedWars الشهيرة", "commands": ["/bw join", "/bw leave"], "dependencies": [], "config": { "minPlayers": 4, "maxPlayers": 8 } }, "skyblock": { "id": "skyblock", "name": "ASkyBlock", "category": "fun", "enabled": false, "description": "نظام SkyBlock كامل", "commands": ["/island create", "/island go", "/island team"], "dependencies": [], "config": { "startingItems": true } }, "parkour": { "id": "parkour", "name": "Parkour", "category": "fun", "enabled": false, "description": "مسارات Parkour ممتعة", "commands": ["/parkour create", "/parkour join"], "dependencies": [], "config": {} }, "duels": { "id": "duels", "name": "Duels", "category": "fun", "enabled": false, "description": "قتال 1v1 بين اللاعبين", "commands": ["/duel accept", "/duel list"], "dependencies": [], "config": { "maxQueue": 10 } }, "arenapvp": { "id": "arenapvp", "name": "ArenaPvP", "category": "fun", "enabled": false, "description": "منطقة PvP حرة", "commands": ["/arena join", "/arena leave"], "dependencies": [], "config": {} }, "treasurereward": { "id": "treasurereward", "name": "TreasureReward", "category": "fun", "enabled": false, "description": "مكافآت يومية", "commands": ["/daily", "/weekly"], "dependencies": [], "config": {} }, "deathmessages": { "id": "deathmessages", "name": "DeathMessages", "category": "fun", "enabled": false, "description": "رسائل وفاة مخصصة", "commands": [], "dependencies": [], "config": {} }, "mobarena": { "id": "mobarena", "name": "MobArena", "category": "fun", "enabled": false, "description": "﹗ arena مخلوقات", "commands": ["/ma join", "/ma leave"], "dependencies": [], "config": {} }, "minigames": { "id": "minigames", "name": "Minigames", "category": "fun", "enabled": false, "description": "مجموعة ميني غيمز", "commands": ["/mg join", "/mg list"], "dependencies": [], "config": {} }, "trivia": { "id": "trivia", "name": "Trivia", "category": "fun", "enabled": false, "description": "أسئلة معلومات عامة", "commands": ["/trivia start"], "dependencies": [], "config": {} }, "sitanywhere": { "id": "sitanywhere", "name": "SitAnywhere", "category": "fun", "enabled": false, "description": "الجلوس في أي مكان", "commands": [], "dependencies": [], "config": {} }, "cosmetics": { "id": "cosmetics", "name": "CosmeticsPlus", "category": "fun", "enabled": false, "description": "تزيينات وتخصيصات", "commands": ["/cosmetics"], "dependencies": [], "config": {} }, "marriage": { "id": "marriage", "name": "Marriage", "category": "fun", "enabled": false, "description": "نظام زواج بين اللاعبين", "commands": ["/marry", "/divorce"], "dependencies": [], "config": {} }, "pets": { "id": "pets", "name": "PetMaster", "category": "fun", "enabled": false, "description": "حيوانات أليفة تتبعك", "commands": ["/pet spawn", "/pet list"], "dependencies": [], "config": { "maxPets": 3 } }, "headhunting": { "id": "headhunting", "name": "HeadHunting", "category": "fun", "enabled": false, "description": "صيد رؤوس المخلوقات", "commands": [], "dependencies": [], "config": {} }, "treecapitator": { "id": "treecapitator", "name": "Treecapitator", "category": "fun", "enabled": false, "description": "قطع الأشجار دفعة واحدة", "commands": [], "dependencies": [], "config": { "needsAxe": true } }, "veinminer": { "id": "veinminer", "name": "VeinMiner", "category": "fun", "enabled": false, "description": "حفر الأوردة كاملة دفعة واحدة", "commands": [], "dependencies": [], "config": { "needsTool": true, "maxBlocks": 64 } }, "durabilityping": { "id": "durabilityping", "name": "DurabilityPing", "category": "fun", "enabled": false, "description": "تنبيه عند قرب تلف الأدوات", "commands": [], "dependencies": [], "config": { "threshold": 10 } }, "backpacks": { "id": "backpacks", "name": "Backpacks", "category": "player", "enabled": false, "description": "حقيبة ظهر إضافية", "commands": ["/backpack"], "dependencies": [], "config": { "maxSize": 54 } },
"lp_groups": { "id": "lp_groups", "name": "LuckPerms Groups", "category": "admin", "enabled": true, "description": "إدارة المجموعات والصلاحيات", "commands": ["/lp group"], "dependencies": ["luckperms"], "config": { "defaultRank": "newbie", "ranks": ["newbie", "member", "vip", "elite", "admin", "owner"] } }, "bansystem": { "id": "bansystem", "name": "BanSystem", "category": "admin", "enabled": true, "description": "نظام حظر وتنبيهات", "commands": ["/ban", "/unban", "/tempban", "/banlist"], "dependencies": [], "config": { "maxBanDays": 30 } }, "essentials_spawn": { "id": "essentials_spawn", "name": "Essentials Spawn", "category": "admin", "enabled": true, "description": "إدارة نقاط الـ Spawn والـ Warps", "commands": ["/spawn", "/setspawn", "/warp", "/setwarp"], "dependencies": [], "config": {} }, "backup": { "id": "backup", "name": "Backup", "category": "admin", "enabled": true, "description": "نسخ احتياطي تلقائي", "commands": ["/backup", "/backup restore"], "dependencies": [], "config": { "intervalHours": 6, "keepBackups": 5 } }, "permissionsex": { "id": "permissionsex", "name": "PermissionsEx", "category": "admin", "enabled": false, "description": "إدارة صلاحيات بديلة", "commands": ["/pex"], "dependencies": [], "config": {} }, "worldmanager": { "id": "worldmanager", "name": "WorldManager", "category": "admin", "enabled": false, "description": "إدارة شاملة للعوالم", "commands": ["/wm"], "dependencies": [], "config": {} }, "console": { "id": "console", "name": "ServerConsole", "category": "admin", "enabled": false, "description": "تحكم بالسيرفر من داخل اللعبة", "commands": ["/console"], "dependencies": [], "config": {} }, "authme": { "id": "authme", "name": "AuthMe", "category": "admin", "enabled": false, "description": "نظام تسجيل دخول آمن", "commands": ["/register", "/login"], "dependencies": [], "config": { "minPasswordLength": 6 } }, "logsviewer": { "id": "logsviewer", "name": "LogsViewer", "category": "admin", "enabled": false, "description": "عرض السجلات من داخل اللعبة", "commands": ["/logs"], "dependencies": [], "config": {} }, "broadcast": { "id": "broadcast", "name": "Broadcast", "category": "admin", "enabled": false, "description": "رسائل broadcast مخصصة", "commands": ["/broadcast", "/bc"], "dependencies": [], "config": { "interval": 300 } },
"bot_miner": { "id": "bot_miner", "name": "بوت الحفار", "category": "bots", "enabled": true, "description": "يحفر ويجمع خامات تلقائياً", "config": { "oreTargets": ["diamond_ore", "iron_ore", "gold_ore", "coal_ore"], "sessionHours": 6, "breakMinutes": 30 } }, "bot_builder": { "id": "bot_builder", "name": "بوت البنّاء", "category": "bots", "enabled": true, "description": "يبني ويجمع خشب وحجارة", "config": { "buildStyle": "survival", "sessionHours": 7, "breakMinutes": 35 } }, "bot_explorer": { "id": "bot_explorer", "name": "بوت المستكشف", "category": "bots", "enabled": true, "description": "يجوب الخريطة ويكتشف", "config": { "exploreRadius": 500, "sessionHours": 8, "breakMinutes": 40 } }, "bot_redstone": { "id": "bot_redstone", "name": "بوت ريدستون", "category": "bots", "enabled": true, "description": "يعمل مزارع وأجهزة ريدستون", "config": { "focusAreas": ["farms", "sorters", "doors"], "sessionHours": 7, "breakMinutes": 35 } }, "bot_guardian": { "id": "bot_guardian", "name": "بوت الحارس", "category": "bots", "enabled": true, "description": "يراقب اللاعبين ويطرد AFK", "config": { "afkKickMinutes": 35, "welcomeNewPlayers": true, "welcomeMessage": "مرحباً بك في السيرفر!" } } }, "presets": { "survival-pro": { "name": "Survival Pro", "description": "للسيرفرات Survival جدية", "icon": "tent", "enabledFeatures": ["worldguard", "worldedit", "coreprotect", "griefprevention", "anticheat", "combatlog", "clearlag", "spark", "chunky", "essentials_eco", "essentials_cmds", "essentials_spawn", "luckperms", "lp_groups", "tab", "placeholderapi", "skinsrestorer", "chatmanager", "afkplus", "dynmap", "bot_miner", "bot_guardian", "backup", "bansystem"] }, "creative-build": { "name": "Creative Build", "description": "للبناء والإبداع", "icon": "hammer", "enabledFeatures": ["worldguard", "worldedit", "fastasyncworldedit", "multiverse", "essentials_cmds", "essentials_spawn", "luckperms", "lp_groups", "tab", "placeholderapi", "dynmap", "bot_builder", "bot_redstone", "bot_miner", "backup"] }, "minigames-hub": { "name": "Minigames Hub", "description": "للميني غيمز والمنافسات", "icon": "gamepad", "enabledFeatures": ["worldguard", "multiverse", "luckperms", "lp_groups", "tab", "placeholderapi", "discordsrv", "bedwars", "duels", "parkour", "mobarena", "minigames", "bot_guardian", "backup", "bansystem"] }, "hardcore": { "name": "Hardcore", "description": "صعوبة عالية — لا مفر من القتال", "icon": "skull", "enabledFeatures": ["worldguard", "anticheat", "clearlag", "coreprotect", "combatlog", "essentials_eco", "essentials_cmds", "luckperms", "tab", "bot_guardian", "backup", "bansystem", "deathmessages"] }, "custom": { "name": "Custom", "description": "اختر ما يناسبك!", "icon": "wand", "enabledFeatures": [] } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279'use strict';
/** * ╔══════════════════════════════════════════════════════════════════════════╗ * Features Engine — v19.0 | محرك 100 ميزة + Presets ║ * ╠══════════════════════════════════════════════════════════════════════════╣ * ✅ 100 ميزة في 8 فئات: حماية، أداء، اقتصاد، لاعبين، عوالم، ترفيه، إدارة، بوتات ║ * ✅ 5 Presets: Survival Pro, Creative Build, Minigames Hub, Hardcore, Custom ║ * ✅ REST API: GET/POST /api/features + Preset Apply ║ * ✅ Auto-Apply: يطبق الميزات المفعلة عند التشغيل ║ * ✅ Plugin Detection: كشف البلاجن المثبتة وتطابقها مع الميزات ║ * ✅ Dependencies: تفعيل تلقائي للعلاقات ║ * ✅ Export/Import: حفظ وتحميل إعدادات الميزات ║ * ╚══════════════════════════════════════════════════════════════════════════╝ */
const fs = require('fs');const path = require('path');const { EventEmitter } = require('events');
const tsNow = () => new Date().toISOString().replace('T', ' ').slice(0, 19);
class FeaturesEngine extends EventEmitter { constructor(config = {}) { super(); this.configPath = config.configPath || path.join(__dirname, 'features-config.json'); this.dataPath = config.dataPath || path.join(__dirname, 'features-data.json'); this.features = {}; this.categories = {}; this.presets = {}; this.activePreset = 'custom'; this.modifiedFeatures = new Set(); this._log('ENGINE', 'تم إنشاء Features Engine'); }
_log(tag, msg) { const ts = tsNow(); console.log(`[${ts}] [FEATURES] ${tag} ${msg}`); }
init() { this._loadConfig(); this._loadData(); this._log('✅', `تم تحميل ${Object.keys(this.features).length} ميزة في ${Object.keys(this.categories).length} فئة`); this._log('📦', `${Object.keys(this.presets).length} Presets متاحة`); }
_loadConfig() { try { const raw = fs.readFileSync(this.configPath, 'utf8'); const data = JSON.parse(raw); this.features = data.features || {}; this.categories = data.categories || {}; this.presets = data.presets || {}; this._log('📂', 'تم تحميل features-config.json'); } catch (e) { this._log('⚠️', `خطأ في تحميل features-config.json: ${e.message}`); this.features = {}; this.categories = {}; this.presets = {}; } }
_loadData() { try { if (fs.existsSync(this.dataPath)) { const raw = fs.readFileSync(this.dataPath, 'utf8'); const data = JSON.parse(raw); this.activePreset = data.activePreset || 'custom'; if (data.features) { for (const [id, overrides] of Object.entries(data.features)) { if (this.features[id]) { this.features[id] = { ...this.features[id], ...overrides }; } } } this._log('📂', `تم تحميل البيانات المحفوظة (Preset: ${this.activePreset})`); } } catch (e) { this._log('⚠️', `خطأ في تحميل البيانات: ${e.message}`); } }
saveData() { try { const features = {}; for (const [id, f] of Object.entries(this.features)) { features[id] = { enabled: f.enabled, config: f.config }; } const data = { version: '19.0', activePreset: this.activePreset, features, savedAt: tsNow() }; fs.writeFileSync(this.dataPath, JSON.stringify(data, null, 2)); this._log('💾', 'تم حفظ البيانات'); } catch (e) { this._log('❌', `خطأ في الحفظ: ${e.message}`); } }
applyPreset(presetId) { const preset = this.presets[presetId]; if (!preset) { this._log('❌', `Preset غير موجود: ${presetId}`); return false; } this._log('📦', `تطبيق Preset: ${preset.name}`); for (const f of Object.values(this.features)) { f.enabled = preset.enabledFeatures.includes(f.id); } for (const depId of preset.enabledFeatures) { this._enableDependencies(depId); } this.activePreset = presetId; this.saveData(); this.emit('presetApplied', presetId, preset); this._log('✅', `تم تطبيق ${preset.name} — ${preset.enabledFeatures.length} ميزة مفعلة`); return true; }
_enableDependencies(featureId) { const f = this.features[featureId]; if (!f || !f.dependencies) return; for (const depId of f.dependencies) { if (this.features[depId] && !this.features[depId].enabled) { this.features[depId].enabled = true; this._log('🔗', `تفعيل تلقائي: ${depId} (dependency لـ ${featureId})`); this._enableDependencies(depId); } } }
toggleFeature(featureId, enabled) { if (!this.features[featureId]) { this._log('❌', `ميزة غير موجودة: ${featureId}`); return false; } this.features[featureId].enabled = enabled; this.modifiedFeatures.add(featureId); if (enabled) { this._enableDependencies(featureId); } this.activePreset = 'custom'; this.saveData(); this.emit('featureToggled', featureId, enabled); this._log('🔄', `${enabled ? 'تفعيل' : 'تعطيل'}: ${featureId}`); return true; }
updateFeatureConfig(featureId, config) { if (!this.features[featureId]) return false; this.features[featureId].config = { ...this.features[featureId].config, ...config }; this.modifiedFeatures.add(featureId); this.saveData(); this.emit('featureConfigUpdated', featureId, config); return true; }
getFeature(id) { return this.features[id] || null; }
getFeaturesByCategory(categoryId) { return Object.values(this.features).filter(f => f.category === categoryId); }
getAllFeatures() { return Object.values(this.features); }
getEnabledFeatures() { return Object.values(this.features).filter(f => f.enabled); }
getDisabledFeatures() { return Object.values(this.features).filter(f => !f.enabled); }
getCategories() { return Object.entries(this.categories) .sort(([, a], [, b]) => a.order - b.order) .map(([id, cat]) => ({ id, ...cat })); }
getPresets() { return Object.entries(this.presets).map(([id, p]) => ({ id, ...p })); }
getPreset(id) { return this.presets[id] || null; }
getActivePreset() { return { id: this.activePreset, ...this.presets[this.activePreset] }; }
getStats() { const all = Object.values(this.features); const enabled = all.filter(f => f.enabled).length; const disabled = all.length - enabled; const byCategory = {}; for (const f of all) { if (!byCategory[f.category]) byCategory[f.category] = { total: 0, enabled: 0 }; byCategory[f.category].total++; if (f.enabled) byCategory[f.category].enabled++; } return { total: all.length, enabled, disabled, byCategory, activePreset: this.activePreset }; }
matchPlugins(detectedPlugins) { const matches = []; const unmatched = []; for (const plugin of detectedPlugins) { const nameLower = (plugin.name || '').toLowerCase().replace(/[\s\-_]/g, ''); let found = false; for (const f of Object.values(this.features)) { const featureName = (f.name || '').toLowerCase().replace(/[\s\-_]/g, ''); if (nameLower.includes(featureName) || featureName.includes(nameLower)) { matches.push({ plugin: plugin.name, feature: f.id, enabled: f.enabled }); found = true; break; } } if (!found) { unmatched.push(plugin.name); } } return { matches, unmatched, totalPlugins: detectedPlugins.length, totalFeatures: Object.keys(this.features).length }; }
exportConfig() { return { version: '19.0', activePreset: this.activePreset, exportedAt: tsNow(), features: Object.fromEntries( Object.entries(this.features).map(([id, f]) => [id, { enabled: f.enabled, config: f.config }]) ) }; }
importConfig(data) { if (!data || !data.features) return false; let imported = 0; for (const [id, overrides] of Object.entries(data.features)) { if (this.features[id]) { this.features[id] = { ...this.features[id], ...overrides }; imported++; } } if (data.activePreset && this.presets[data.activePreset]) { this.activePreset = data.activePreset; } this.saveData(); this._log('📥', `تم استيراد ${imported} ميزة`); this.emit('configImported', imported); return true; }
getApiData() { return { version: '19.0', stats: this.getStats(), categories: this.getCategories(), features: Object.values(this.features).map(f => ({ id: f.id, name: f.name, category: f.category, enabled: f.enabled, description: f.description, config: f.config, dependencies: f.dependencies, commands: f.commands })), presets: this.getPresets(), activePreset: this.activePreset }; }}
module.exports = { FeaturesEngine };1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474'use strict';
/** * ╔══════════════════════════════════════════════════════════════════════════╗ * Smart Job System — v23.0 | نظام الوظائف الذكي ║ * ╠══════════════════════════════════════════════════════════════════════════╣ * ✅ التعرف على جميع كتل ماين كرافت ║ * ✅ خطة عمل ذكية (شجرة → خشب → أدوات → تعدين → بناء) ║ * ✅ تقسيم المهام حسب عدد البوتات ║ * ✅ تبعيات ذكية (محتاج خشب قبل الأداة) ║ * ✅ سلوك طبيعي واقعي ║ * ✅ إعادة تخطيط تلقائية عند فشل المهمة ║ * ╚══════════════════════════════════════════════════════════════════════════╝ */
const { EventEmitter } = require('events');
const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const pick = arr => arr[Math.floor(Math.random() * arr.length)];const chance = pct => Math.random() * 100 < pct;
// ════════════════════════════════════════════════════════════════════════════// قاعدة بيانات جميع كتل ماين كرافت// ════════════════════════════════════════════════════════════════════════════const BLOCK_DATABASE = { // ─── أخشاب الأشجار ────────────────────────────────────────────────────── wood: { category: 'wood', names: [ 'oak_log', 'spruce_log', 'birch_log', 'jungle_log', 'acacia_log', 'dark_oak_log', 'mangrove_log', 'cherry_log', 'oak_wood', 'spruce_wood', 'birch_wood', 'jungle_wood', 'acacia_wood', 'dark_oak_wood', 'mangrove_wood', 'cherry_wood', 'stripped_oak_log', 'stripped_spruce_log', 'stripped_birch_log', 'stripped_jungle_log', 'stripped_acacia_log', 'stripped_dark_oak_log', 'stripped_mangrove_log', 'stripped_cherry_log', 'stripped_oak_wood', 'stripped_spruce_wood', 'stripped_birch_wood', 'stripped_jungle_wood', ], drops: ['oak_log', 'spruce_log', 'birch_log', 'jungle_log', 'acacia_log', 'dark_oak_log'], tool: 'axe', hardness: 2, tags: ['tree', 'natural', 'fuel'], },
// ─── أوراق الأشجار ────────────────────────────────────────────────────── leaves: { category: 'leaves', names: [ 'oak_leaves', 'spruce_leaves', 'birch_leaves', 'jungle_leaves', 'acacia_leaves', 'dark_oak_leaves', 'mangrove_leaves', 'cherry_leaves', 'azalea_leaves', 'flowering_azalea_leaves', ], drops: ['stick', 'apple', 'oak_sapling', 'spruce_sapling', 'birch_sapling'], tool: null, hardness: 0.2, tags: ['tree', 'natural', 'decoration'], },
// ─── الحجارة ──────────────────────────────────────────────────────────── stone: { category: 'stone', names: [ 'stone', 'granite', 'diorite', 'andesite', 'deepslate', 'granite_polished', 'diorite_polished', 'andesite_polished', 'stone_bricks', 'mossy_stone_bricks', 'cracked_stone_bricks', ], drops: ['cobblestone'], tool: 'pickaxe', hardness: 1.5, tags: ['mineral', 'building', 'natural'], },
// ─── الخامات ──────────────────────────────────────────────────────────── ores: { category: 'ore', names: [ 'coal_ore', 'deepslate_coal_ore', 'iron_ore', 'deepslate_iron_ore', 'copper_ore', 'deepslate_copper_ore', 'gold_ore', 'deepslate_gold_ore', 'redstone_ore', 'deepslate_redstone_ore', 'emerald_ore', 'deepslate_emerald_ore', 'lapis_ore', 'deepslate_lapis_ore', 'diamond_ore', 'deepslate_diamond_ore', 'nether_gold_ore', 'nether_quartz_ore', 'ancient_debris', ], drops: { 'coal_ore': ['coal'], 'deepslate_coal_ore': ['coal'], 'iron_ore': ['raw_iron'], 'deepslate_iron_ore': ['raw_iron'], 'copper_ore': ['raw_copper'], 'deepslate_copper_ore': ['raw_copper'], 'gold_ore': ['raw_gold'], 'deepslate_gold_ore': ['raw_gold'], 'redstone_ore': ['redstone', 'redstone', 'redstone', 'redstone'], 'deepslate_redstone_ore': ['redstone', 'redstone', 'redstone', 'redstone'], 'emerald_ore': ['emerald'], 'deepslate_emerald_ore': ['emerald'], 'lapis_ore': ['lapis_lazuli', 'lapis_lazuli', 'lapis_lazuli'], 'deepslate_lapis_ore': ['lapis_lazuli', 'lapis_lazuli', 'lapis_lazuli'], 'diamond_ore': ['diamond'], 'deepslate_diamond_ore': ['diamond'], 'nether_gold_ore': ['gold_nugget', 'gold_nugget', 'gold_nugget'], 'nether_quartz_ore': ['nether_quartz', 'nether_quartz', 'nether_quartz'], 'ancient_debris': ['ancient_debris'], }, tool: 'pickaxe', hardness: 3, tags: ['mineral', 'valuable', 'mining'], },
// ─── التراب والرمل ────────────────────────────────────────────────────── dirt: { category: 'dirt', names: [ 'dirt', 'coarse_dirt', 'rooted_dirt', 'dirt_path', 'grass_block', 'mycelium', 'podzol', 'mud', 'crimson_nylium', 'warped_nylium', ], drops: ['dirt'], tool: 'shovel', hardness: 0.5, tags: ['natural', 'farming', 'building'], },
sand: { category: 'sand', names: ['sand', 'red_sand', 'soul_sand', 'soul_soil', 'gravel', 'clay'], drops: ['sand', 'red_sand', 'soul_sand', 'soul_soil', 'gravel', 'clay_ball'], tool: 'shovel', hardness: 0.5, tags: ['natural', 'building', 'glass_source'], },
// ─── المعادن (المصنّعة) ───────────────────────────────────────────────── metals: { category: 'metal', names: [ 'iron_block', 'gold_block', 'copper_block', 'raw_iron_block', 'raw_gold_block', 'raw_copper_block', 'lapis_block', 'redstone_block', 'emerald_block', 'diamond_block', 'netherite_block', 'amethyst_block', 'copper_block', ], drops: [], tool: 'pickaxe', hardness: 5, tags: ['valuable', 'storage', 'building'], },
// ─── الخشب المصنّع ────────────────────────────────────────────────────── planks: { category: 'planks', names: [ 'oak_planks', 'spruce_planks', 'birch_planks', 'jungle_planks', 'acacia_planks', 'dark_oak_planks', 'mangrove_planks', 'cherry_planks', 'crimson_planks', 'warped_planks', ], drops: [], tool: 'axe', hardness: 2, tags: ['building', 'crafting', 'fuel'], },
// ─── الصخور النارية ───────────────────────────────────────────────────── nether: { category: 'nether', names: [ 'netherrack', 'nether_bricks', 'red_nether_bricks', 'basalt', 'blackstone', 'smooth_basalt', 'polished_basalt', 'polished_blackstone', 'polished_blackstone_bricks', 'cracked_polished_blackstone_bricks', 'soul_sand', 'soul_soil', 'magma_block', 'glowstone', 'shroomlight', 'warped_wart_block', 'crimson_wart_block', ], drops: [], tool: 'pickaxe', hardness: 2, tags: ['nether', 'building', 'mineral'], },
// ─── الزجاج ───────────────────────────────────────────────────────────── glass: { category: 'glass', names: [ 'glass', 'tinted_glass', 'glass_pane', 'white_stained_glass', 'orange_stained_glass', 'magenta_stained_glass', 'light_blue_stained_glass', 'yellow_stained_glass', 'lime_stained_glass', 'pink_stained_glass', 'gray_stained_glass', 'light_gray_stained_glass', 'cyan_stained_glass', 'purple_stained_glass', 'blue_stained_glass', 'brown_stained_glass', 'green_stained_glass', 'red_stained_glass', 'black_stained_glass', ], drops: [], tool: null, hardness: 0.3, tags: ['decoration', 'building', 'transparent'], },
// ─── الطين والماء ─────────────────────────────────────────────────────── fluids: { category: 'fluid', names: ['water', 'lava', 'flowing_water', 'flowing_lava'], drops: [], tool: null, hardness: 100, tags: ['fluid', 'danger'], },
// ─── النباتات ─────────────────────────────────────────────────────────── plants: { category: 'plant', names: [ 'short_grass', 'tall_grass', 'fern', 'large_fern', 'dandelion', 'poppy', 'blue_orchid', 'allium', 'azure_bluet', 'red_tulip', 'orange_tulip', 'white_tulip', 'pink_tulip', 'oxeye_daisy', 'cornflower', 'lily_of_the_valley', 'wheat', 'carrots', 'potatoes', 'beetroots', 'sugar_cane', 'cactus', 'bamboo', 'kelp', 'seagrass', 'dead_bush', 'brown_mushroom', 'red_mushroom', 'nether_wart', 'chorus_plant', 'chorus_flower', ], drops: [], tool: null, hardness: 0, tags: ['natural', 'farming', 'decoration'], },
// ─── الصناديق والأثاث ─────────────────────────────────────────────────── containers: { category: 'container', names: [ 'chest', 'trapped_chest', 'ender_chest', 'barrel', 'shulker_box', 'white_shulker_box', 'orange_shulker_box', 'dispenser', 'dropper', 'hopper', 'brewing_stand', 'furnace', 'blast_furnace', 'smoker', ], drops: [], tool: 'axe', hardness: 2.5, tags: ['storage', 'utility', 'interaction'], },
// ─── الأبواب ──────────────────────────────────────────────────────────── doors: { category: 'door', names: [ 'oak_door', 'spruce_door', 'birch_door', 'jungle_door', 'acacia_door', 'dark_oak_door', 'mangrove_door', 'cherry_door', 'crimson_door', 'warped_door', 'iron_door', 'oak_fence_gate', 'spruce_fence_gate', 'birch_fence_gate', 'iron_bars', 'chain', ], drops: [], tool: 'axe', hardness: 3, tags: ['building', 'security', 'interaction'], },
// ─── السكك الحديدية ────────────────────────────────────────────────────── rails: { category: 'rail', names: [ 'rail', 'powered_rail', 'detector_rail', 'activator_rail', ], drops: [], tool: 'pickaxe', hardness: 0.7, tags: ['transport', 'redstone', 'utility'], },
// ─── الريدستون ────────────────────────────────────────────────────────── redstone: { category: 'redstone', names: [ 'redstone_wire', 'redstone_torch', 'redstone_block', 'redstone_lamp', 'repeater', 'comparator', 'piston', 'sticky_piston', 'observer', 'note_block', 'target', 'tripwire_hook', 'lever', 'stone_button', 'oak_button', 'oak_pressure_plate', 'stone_pressure_plate', 'light_weighted_pressure_plate', 'heavy_weighted_pressure_plate', 'sculk_sensor', 'sculk_catalyst', ], drops: [], tool: 'pickaxe', hardness: 0.5, tags: ['redstone', 'mechanism', 'automation'], },
// ─── الإضاءة ──────────────────────────────────────────────────────────── lighting: { category: 'lighting', names: [ 'torch', 'wall_torch', 'soul_torch', 'soul_wall_torch', 'lantern', 'soul_lantern', 'jack_o_lantern', 'campfire', 'soul_campfire', 'glowstone', 'shroomlight', 'sea_lantern', 'beacon', 'froglight', 'ochre_froglight', 'verdant_froglight', 'pearlescent_froglight', 'crying_obsidian', 'respawn_anchor', ], drops: [], tool: null, hardness: 0.3, tags: ['lighting', 'utility', 'decoration'], },
// ─── الزخرفة ──────────────────────────────────────────────────────────── decoration: { category: 'decoration', names: [ 'crafting_table', 'cartography_table', 'fletching_table', 'smithing_table', 'loom', 'composter', 'note_block', 'bell', 'loom', 'flower_pot', 'painting', 'item_frame', 'glow_item_frame', 'armor_stand', 'lead', 'name_tag', 'white_bed', 'orange_bed', 'magenta_bed', 'light_blue_bed', 'yellow_bed', 'lime_bed', 'pink_bed', 'gray_bed', 'light_gray_bed', 'cyan_bed', 'purple_bed', 'blue_bed', 'brown_bed', 'green_bed', 'red_bed', 'black_bed', ], drops: [], tool: 'axe', hardness: 1, tags: ['decoration', 'utility', 'interaction'], },
// ─── النادر / الإسمنت ──────────────────────────────────────���─────────── rare: { category: 'rare', names: [ 'obsidian', 'crying_obsidian', 'end_stone', 'end_stone_bricks', 'purpur_block', 'purpur_pillar', 'end_rod', 'chorus_plant', 'dragon_egg', 'bedrock', 'barrier', 'light', 'reinforced_deepslate', 'sculk', 'sculk_vein', 'sculk_sensor', ], drops: [], tool: 'pickaxe', hardness: 50, tags: ['rare', 'valuable', 'special'], },};
// ════════════════════════════════════════════════════════════════════════════// شجرة التكنولوجيا (Tech Tree)// ════════════════════════════════════════════════════════════════════════════const TECH_TREE = { // المرحلة 1: يدين فقط fist: { name: 'الأيدي', requires: [], items: [] },
// المرحلة 2: خشب wood: { name: 'الخشب', requires: ['fist'], items: ['oak_log', 'stick'] },
// المرحلة 3: أدوات خشبية woodTools: { name: 'أدوات خشبية', requires: ['wood'], items: ['wooden_pickaxe', 'wooden_axe', 'wooden_shovel', 'wooden_sword'] },
// المرحلة 4: حجر stone: { name: 'الحجر', requires: ['woodTools'], items: ['cobblestone', 'stone'] },
// المرحلة 5: أدوات حجرية stoneTools: { name: 'أدوات حجرية', requires: ['stone'], items: ['stone_pickaxe', 'stone_axe', 'stone_shovel', 'stone_sword'] },
// المرحلة 6: حديد iron: { name: 'الحديد', requires: ['stoneTools'], items: ['raw_iron', 'iron_ingot'] },
// المرحلة 7: أدوات حديدية ironTools: { name: 'أدوات حديدية', requires: ['iron'], items: ['iron_pickaxe', 'iron_axe', 'iron_shovel', 'iron_sword', 'iron_helmet', 'iron_chestplate', 'iron_leggings', 'iron_boots'] },
// المرحلة 8: ذهب gold: { name: 'الذهب', requires: ['ironTools'], items: ['raw_gold', 'gold_ingot'] },
// المرحلة 9: ألماس diamond: { name: 'الماس', requires: ['ironTools'], items: ['diamond', 'diamond_pickaxe', 'diamond_axe', 'diamond_shovel', 'diamond_sword', 'diamond_helmet', 'diamond_chestplate', 'diamond_leggings', 'diamond_boots'] },
// المرحلة 10: نايثرايت netherite: { name: 'النايثرايت', requires: ['diamond'], items: ['netherite_scrap', 'netherite_ingot', 'netherite_pickaxe', 'netherite_axe', 'netherite_sword', 'netherite_helmet', 'netherite_chestplate', 'netherite_leggings', 'netherite_boots'] },};
// ════════════════════════════════════════════════════════════════════════════// قائمة المهام المتاحة// ════════════════════════════════════════════════════════════════════════════const TASK_DEFINITIONS = { // ─── المرحلة 1: جمع الأخشاب ───────────────────────────────────────────── chopTree: { id: 'chopTree', name: 'قطع الأشجار', icon: '🪵', category: 'gathering', techLevel: 'fist', duration: 60000, priority: 10, dependencies: [], items: ['oak_log', 'stick'], actions: [ { type: 'findTree', desc: 'البحث عن شجرة' }, { type: 'chopLeaves', desc: 'تكسير الأوراق' }, { type: 'chopWood', desc: 'تكсер جذع الشجرة' }, { type: 'collectDrops', desc: 'جمع الأخشاب المتساقطة' }, ], },
// ─── المرحلة 2: صناعة الأدوات الخشبية ─────────────────────────────────── craftWoodTools: { id: 'craftWoodTools', name: 'صناعة أدوات خشبية', icon: '🔨', category: 'crafting', techLevel: 'woodTools', duration: 30000, priority: 9, dependencies: ['chopTree'], items: ['wooden_pickaxe', 'wooden_axe', 'wooden_shovel'], actions: [ { type: 'findCraftingTable', desc: 'البحث عن طاولة الصناعة' }, { type: 'craft', item: 'stick', count: 4, desc: 'صنع عصي' }, { type: 'craft', item: 'wooden_pickaxe', count: 1, desc: 'صنع فأس حجري' }, { type: 'craft', item: 'wooden_axe', count: 1, desc: 'صنع فأس خشبية' }, ], },
// ─── المرحلة 3: تعدين الحجر ─────────────────────────────────────���─────── mineStone: { id: 'mineStone', name: 'تعدين الحجر', icon: '⛏️', category: 'mining', techLevel: 'stone', duration: 90000, priority: 8, dependencies: ['craftWoodTools'], items: ['cobblestone', 'coal'], actions: [ { type: 'findCave', desc: 'البحث عن كهف' }, { type: 'placeTorch', desc: 'وضع مشاعل' }, { type: 'mine', target: 'stone', count: 20, desc: 'حفر الحجر' }, { type: 'mine', target: 'coal_ore', count: 10, desc: 'حفر الفحم' }, ], },
// ─── المرحلة 4: صناعة أدوات حجرية ─────────────────────────────────────── craftStoneTools: { id: 'craftStoneTools', name: 'صناعة أدوات حجرية', icon: '🔨', category: 'crafting', techLevel: 'stoneTools', duration: 30000, priority: 8, dependencies: ['mineStone'], items: ['stone_pickaxe', 'stone_axe', 'stone_shovel'], actions: [ { type: 'craft', item: 'stone_pickaxe', count: 1, desc: 'صنع مجرفة حجرية' }, { type: 'craft', item: 'stone_axe', count: 1, desc: 'صنع فأس حجرية' }, { type: 'craft', item: 'stone_shovel', count: 1, desc: 'صنع مجرفة حجرية' }, ], },
// ─── المرحلة 5: تعدين الحديد ──────────────────────────────────────────── mineIron: { id: 'mineIron', name: 'تعدين الحديد', icon: '⛏️', category: 'mining', techLevel: 'iron', duration: 120000, priority: 7, dependencies: ['craftStoneTools'], items: ['raw_iron', 'coal'], actions: [ { type: 'findCave', desc: 'البحث عن كهف عميق' }, { type: 'placeTorch', desc: 'إنارة الممرات' }, { type: 'mine', target: 'iron_ore', count: 20, desc: 'حفر الحديد' }, { type: 'mine', target: 'coal_ore', count: 15, desc: 'حفر الفحم للصهر' }, ], },
// ─── المرحلة 6: صهر الحديد ────────────────────────────────────────────── smeltIron: { id: 'smeltIron', name: 'صهر الحديد', icon: '🔥', category: 'crafting', techLevel: 'ironTools', duration: 60000, priority: 7, dependencies: ['mineIron'], items: ['iron_ingot'], actions: [ { type: 'findFurnace', desc: 'البحث عن فرن' }, { type: 'smelt', input: 'raw_iron', fuel: 'coal', output: 'iron_ingot', count: 20, desc: 'صهر الحديد' }, ], },
// ─── المرحلة 7: صناعة أدوات حديدية ────────────────────────────────────── craftIronTools: { id: 'craftIronTools', name: 'صناعة أدوات حديدية', icon: '🔨', category: 'crafting', techLevel: 'ironTools', duration: 40000, priority: 7, dependencies: ['smeltIron'], items: ['iron_pickaxe', 'iron_axe', 'iron_sword'], actions: [ { type: 'craft', item: 'iron_pickaxe', count: 1, desc: 'صنع فأس حديدية' }, { type: 'craft', item: 'iron_axe', count: 1, desc: 'صنع فأس حديدية' }, { type: 'craft', item: 'iron_sword', count: 1, desc: 'صنع سيف حديدي' }, ], },
// ─── المرحلة 8: تعدين الماس ──────────────────────────────────────────── mineDiamond: { id: 'mineDiamond', name: 'تعدين الماس', icon: '💎', category: 'mining', techLevel: 'diamond', duration: 180000, priority: 6, dependencies: ['craftIronTools'], items: ['diamond'], actions: [ { type: 'digDown', desc: 'النزول للأعماق' }, { type: 'mine', target: 'diamond_ore', count: 5, desc: 'حفر الماس' }, { type: 'mine', target: 'gold_ore', count: 10, desc: 'حفر الذهب' }, { type: 'mine', target: 'redstone_ore', count: 10, desc: 'حفر الريدستون' }, ], },
// ─── المرحلة 9: صناعة أدوات ماس ──────────────────────────────────────── craftDiamondTools: { id: 'craftDiamondTools', name: 'صناعة أدوات ماس', icon: '💎', category: 'crafting', techLevel: 'diamond', duration: 40000, priority: 6, dependencies: ['mineDiamond'], items: ['diamond_pickaxe', 'diamond_axe', 'diamond_sword'], actions: [ { type: 'craft', item: 'diamond_pickaxe', count: 1, desc: 'صنع فأس ماس' }, { type: 'craft', item: 'diamond_axe', count: 1, desc: '��نع فأس ماس' }, { type: 'craft', item: 'diamond_sword', count: 1, desc: 'صنع سيف ماسي' }, ], },
// ─── زراعة المحاصيل ───────────────────────────────────────────────────── farm: { id: 'farm', name: 'زراعة المحاصيل', icon: '🌾', category: 'farming', techLevel: 'woodTools', duration: 120000, priority: 5, dependencies: ['craftWoodTools'], items: ['wheat', 'carrots', 'potatoes'], actions: [ { type: 'findWater', desc: 'البحث عن مصدر ماء' }, { type: 'hoeLand', desc: 'حرث الأرض' }, { type: 'plant', desc: 'زراعة البذور' }, { type: 'water', desc: 'ري المحاصيل' }, ], },
// ─── بناء ملجأ ────────────────────────────────────────────────────────── buildShelter: { id: 'buildShelter', name: 'بناء ملجأ', icon: '🏠', category: 'building', techLevel: 'woodTools', duration: 90000, priority: 6, dependencies: ['chopTree'], items: ['oak_planks', 'oak_fence', 'torch'], actions: [ { type: 'findSpot', desc: 'اختيار موقع مناسب' }, { type: 'buildFloor', desc: 'بناء الأرضية' }, { type: 'buildWalls', desc: 'بناء الجدران' }, { type: 'buildRoof', desc: 'بناء السقف' }, { type: 'placeDoor', desc: 'وضع باب' }, { type: 'placeTorches', desc: 'إنارة الملجأ' }, ], },
// ─── استكشاف كهف ──────────────────────────────────────────────────────── exploreCave: { id: 'exploreCave', name: 'استكشاف كهف', icon: '🕳️', category: 'exploration', techLevel: 'stoneTools', duration: 120000, priority: 4, dependencies: ['craftStoneTools'], items: [], actions: [ { type: 'findCave', desc: 'البحث عن كهف' }, { type: 'placeTorch', desc: 'إنارة الممرات' }, { type: 'explore', desc: 'استكشاف الأماكن الجديدة' }, { type: 'collectLoot', desc: 'جمع الغنيمة' }, ], },
// ─── صيد السمك ────────────────────────────────────────────────────────── fish: { id: 'fish', name: 'الصيد بالصنارة', icon: '🎣', category: 'gathering', techLevel: 'fist', duration: 90000, priority: 3, dependencies: [], items: ['cod', 'salmon', 'pufferfish', 'string', 'bow'], actions: [ { type: 'findWater', desc: 'البحث عن مياه عميقة' }, { type: 'equipRod', desc: 'ถือ صنارة' }, { type: 'fish', desc: 'الصيد' }, ], },
// ─── جمع الحطب ────────────────────────────────────────────────────────── gatherWood: { id: 'gatherWood', name: 'جمع الحطب', icon: '🪵', category: 'gathering', techLevel: 'fist', duration: 60000, priority: 8, dependencies: [], items: ['oak_log', 'stick'], actions: [ { type: 'findTree', desc: 'البحث عن شجرة' }, { type: 'chopWood', desc: 'تكسير الجذوع' }, { type: 'collectDrops', desc: 'جمع الأخشاب' }, ], },
// ─── جمع الطعام ───────────────────────────────────────────────────────── gatherFood: { id: 'gatherFood', name: 'جمع الطعام', icon: '🍖', category: 'gathering', techLevel: 'fist', duration: 90000, priority: 6, dependencies: [], items: ['bread', 'cooked_porkchop', 'cooked_beef', 'cooked_chicken', 'apple'], actions: [ { type: 'findAnimals', desc: 'البحث عن حيوانات' }, { type: 'hunt', desc: 'صيد الحيوانات' }, { type: 'cook', desc: 'طبخ الطعام' }, ], },
// ─── ترتيب المخزون ────────────────────────────────────────────────────── organizeInventory: { id: 'organizeInventory', name: 'ترتيب المخزون', icon: '📦', category: 'utility', techLevel: 'fist', duration: 30000, priority: 2, dependencies: [], items: [], actions: [ { type: 'findChest', desc: 'البح�� عن صندوق' }, { type: 'sortItems', desc: 'ترتيب الأغراض في الصناديق' }, ], },
// ─── صنع جرعات ────────────────────────────────────────────────────────── brewPotions: { id: 'brewPotions', name: 'صنع جرعات', icon: '🧪', category: 'crafting', techLevel: 'ironTools', duration: 60000, priority: 3, dependencies: ['craftIronTools'], items: ['potion_healing', 'potion_strength', 'potion_speed'], actions: [ { type: 'findBrewingStand', desc: 'البحث عن طاولة التخمير' }, { type: 'brew', desc: 'تخمير الجرعات' }, ], },
// ─── بناء مزرعة تلقائية ───────────────────────────────────────────────── buildAutoFarm: { id: 'buildAutoFarm', name: 'بناء مزرعة تلقائية', icon: '🚜', category: 'building', techLevel: 'ironTools', duration: 180000, priority: 4, dependencies: ['craftIronTools', 'farm'], items: ['piston', 'redstone', 'observer', 'water_bucket'], actions: [ { type: 'findSpot', desc: 'اختيار موقع المزرعة' }, { type: 'buildFrame', desc: 'بناء الهيكل' }, { type: 'placeRedstone', desc: 'تركيب الريدستون' }, { type: 'placeWater', desc: 'إضافة الماء' }, { type: 'plantCrops', desc: 'زراعة المحاصيل' }, ], },};
// ════════════════════════════════════════════════════════════════════════════// أدوار البوتات// ════════════════════════════════════════════════════════════════════════════const BOT_ROLES = { LUMBERJACK: { id: 'lumberjack', name: 'الحطّاب', icon: '🪓', priority: ['chopTree', 'gatherWood', 'buildShelter'] }, MINER: { id: 'miner', name: 'المنجّم', icon: '⛏️', priority: ['mineStone', 'mineIron', 'mineDiamond', 'exploreCave'] }, FARMER: { id: 'farmer', name: 'المزارع', icon: '🌾', priority: ['farm', 'gatherFood', 'buildAutoFarm'] }, CRAFTER: { id: 'crafter', name: 'الصانع', icon: '🔨', priority: ['craftWoodTools', 'craftStoneTools', 'craftIronTools', 'craftDiamondTools', 'smeltIron', 'brewPotions'] }, BUILDER: { id: 'builder', name: 'المبني', icon: '🏗️', priority: ['buildShelter', 'buildAutoFarm'] }, EXPLORER: { id: 'explorer', name: 'الاستكشاف', icon: '🗺️', priority: ['exploreCave', 'fish'] }, UTILITY: { id: 'utility', name: 'المساعد', icon: '📦', priority: ['organizeInventory', 'fish'] },};
// ════════════════════════════════════════════════════════════════════════════// SmartJobSystem الرئيسي// ════════════════════════════════════════════════════════════════════════════class SmartJobSystem extends EventEmitter { constructor(bot, config = {}) { super(); this.bot = bot; this.config = { behaviorMode: 'balanced', // balanced, aggressive, passive maxRetries: 3, taskTimeout: 300000, ...config, };
this.currentTask = null; this.taskQueue = []; this.completedTasks = []; this.failedTasks = []; this.inventory = {}; this.technologies = new Set(['fist']); this.stats = { blocksMined: 0, itemsCrafted: 0, treesChopped: 0, distanceTraveled: 0 }; this._running = false; this._timers = [];
this._log('ENGINE', `تم إنشاء نظام الوظائف الذكي — ${this.bot?.username || 'unknown'}`); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [JOB] ${tag} ${msg}`); }
// ════════════════════════════════════════════════════════════════════════════ // التعرف على الكتل المحيطة // ════════════════════════════════════════════════════════════════════════════ scanSurroundings(radius = 16) { if (!this.bot?.entity) return {}; const pos = this.bot.entity.position; const blocks = {}; const categories = {};
for (let x = -radius; x <= radius; x++) { for (let y = -radius; y <= radius; y++) { for (let z = -radius; z <= radius; z++) { const block = this.bot.blockAt(pos.offset(x, y, z)); if (!block || block.name === 'air') continue;
// تصنيف الكتلة const cat = this._classifyBlock(block.name); if (cat) { if (!categories[cat]) categories[cat] = []; categories[cat].push({ block, name: block.name, category: cat, distance: Math.sqrt(x*x + y*y + z*z) }); }
blocks[block.name] = (blocks[block.name] || 0) + 1; } } }
return { blocks, categories, totalBlocks: Object.values(blocks).reduce((a, b) => a + b, 0) }; }
_classifyBlock(blockName) { for (const [catId, cat] of Object.entries(BLOCK_DATABASE)) { if (cat.names.includes(blockName)) return catId; } return null; }
getBlockInfo(blockName) { for (const [catId, cat] of Object.entries(BLOCK_DATABASE)) { if (cat.names.includes(blockName)) { return { ...cat, id: catId }; } } return null; }
// ════════════════════════════════════════════════════════════════════════════ // خطة العمل الذكية // ════════════════════════════════════════════════════════════════════════════ generatePlan(botCount = 1) { const plan = this._buildTaskGraph(); const assigned = this._divideTasks(plan, botCount); this._log('📋', `خطة عمل: ${assigned.length} مهمة لـ ${botCount} بوت`); return assigned; }
_buildTaskGraph() { const tasks = Object.values(TASK_DEFINITIONS).map(t => ({ ...t, status: 'pending', assignedTo: null, }));
// حساب الأولوية مع التبعيات tasks.forEach(task => { const deps = task.dependencies.map(d => tasks.find(t => t.id === d)).filter(Boolean); task.depth = deps.length > 0 ? Math.max(...deps.map(d => d.depth || 0)) + 1 : 0; task.effectivePriority = task.priority - (task.depth * 0.5); });
return tasks.sort((a, b) => b.effectivePriority - a.effectivePriority); }
_divideTasks(tasks, botCount) { if (botCount === 1) { // بوت واحد: يسوي كل شيء بالترتيب return tasks.map((t, i) => ({ ...t, assignedTo: 0, order: i })); }
// أكثر من بوت: تقسيم ذكي حسب الأدوار const roleKeys = Object.keys(BOT_ROLES); const assignments = []; const usedTasks = new Set();
// تخصيص أدوار للبوتات for (let i = 0; i < botCount; i++) { const roleId = roleKeys[i % roleKeys.length]; const role = BOT_ROLES[roleId]; const botTasks = tasks.filter(t => !usedTasks.has(t.id) && role.priority.includes(t.id) ); botTasks.forEach((t, idx) => { assignments.push({ ...t, assignedTo: i, order: idx, role: roleId }); usedTasks.add(t.id); }); }
// المهام المتبقية: توزع على البوت الأقل حملاً const remaining = tasks.filter(t => !usedTasks.has(t.id)); remaining.forEach((task, idx) => { const botLoads = Array(botCount).fill(0); assignments.forEach(a => botLoads[a.assignedTo]++); const leastLoaded = botLoads.indexOf(Math.min(...botLoads)); assignments.push({ ...task, assignedTo: leastLoaded, order: idx, role: 'utility' }); });
return assignments.sort((a, b) => a.assignedTo - b.assignedTo || a.order - b.order); }
// ════════════════════════════════════════════════════════════════════════════ // تنفيذ المهام // ════════════════════════════════════════════════════════════════════════════ async executeTask(taskDef) { if (!this.bot?.entity) return false; this.currentTask = taskDef; this._log('🚀', `بدء المهمة: ${taskDef.name}`);
try { for (const action of taskDef.actions) { if (!this._running || !this.bot?.entity) break; this._log(' ⚡', action.desc); await this._executeAction(action); await sleep(rand(200, 600)); }
this.completedTasks.push(taskDef.id); this._unlockTech(taskDef); this.emit('taskComplete', taskDef); this._log('✅', `اكتملت المهمة: ${taskDef.name}`); return true; } catch (e) { this.failedTasks.push({ id: taskDef.id, error: e.message }); this.emit('taskFailed', taskDef, e); this._log('❌', `فشلت المهمة: ${taskDef.name} — ${e.message}`); return false; } finally { this.currentTask = null; } }
async _executeAction(action) { if (!this.bot?.entity) return; switch (action.type) { case 'findTree': return await this._findAndGoTo('tree', 32); case 'chopLeaves': return await this._chopCategory('leaves', 8); case 'chopWood': return await this._chopCategory('wood', 6); case 'collectDrops': return await this._collectNearbyItems(); case 'findCave': return await this._findCave(); case 'placeTorch': return await this._placeTorches(3); case 'mine': return await this._mineSpecific(action.target, action.count); case 'digDown': return await this._digDown(40); case 'findCraftingTable': return await this._findAndInteract('crafting_table'); case 'findFurnace': return await this._findAndInteract('furnace'); case 'findBrewingStand': return await this._findAndInteract('brewing_stand'); case 'findChest': return await this._findAndInteract('chest'); case 'findWater': return await this._findAndGoTo('water', 24); case 'findAnimals': return await this._findAnimals(); case 'findSpot': return await this._findBuildSpot(); case 'craft': return await this._craftItem(action.item, action.count); case 'smelt': return await this._smeltItem(action); case 'hoeLand': return await this._hoeLand(); case 'plant': return await this._plantCrops(); case 'water': return await this._waterCrops(); case 'hunt': return await this._huntAnimals(); case 'cook': return await this._cookFood(); case 'equipRod': return await this._equipItem('fishing_rod'); case 'fish': return await this._doFishing(); case 'explore': return await this._exploreArea(); case 'collectLoot': return await this._collectNearbyItems(); case 'sortItems': return await this._sortInventory(); case 'buildFloor': return await this._buildStructure('floor'); case 'buildWalls': return await this._buildStructure('walls'); case 'buildRoof': return await this._buildStructure('roof'); case 'placeDoor': return await this._placeDoor(); case 'placeTorches': return await this._placeTorches(6); case 'buildFrame': return await this._buildStructure('frame'); case 'placeRedstone': return await this._placeRedstone(); case 'placeWater': return await this._placeWater(); case 'plantCrops': return await this._plantCrops(); case 'brew': return await this._brewPotion(); } }
// ════════════════════════════════════════════════════════════════════════════ // إجراءات التنفيذ // ════════════════════════════════════════════════════════════════════════════ async _findAndGoTo(category, maxDist = 32) { if (!this.bot?.entity) return false; const scan = this.scanSurroundings(maxDist); const targets = scan.categories[category]; if (!targets || targets.length === 0) return false;
const target = targets.sort((a, b) => a.distance - b.distance)[0]; await this._walkTo(target.block.position); return true; }
async _walkTo(position) { if (!this.bot?.entity) return; const goal = { entity: { position }, range: 2 }; try { // استخدام pathfinding إذا كان متاحاً const { pathfinder, Movements, goals } = require('mineflayer-pathfinder'); if (this.bot.pathfinder) { const mcData = require('minecraft-data')(this.bot.version); const movements = new Movements(this.bot, mcData); this.bot.pathfinder.setMovements(movements); await this.bot.pathfinder.goto(new goals.GoalBlock(position.x, position.y, position.z)); return; } } catch(_) {}
// بديل: المشي اليدوي const yaw = Math.atan2( position.z - this.bot.entity.position.z, position.x - this.bot.entity.position.x ); this.bot.look(yaw, 0, false); this.bot.setControlState('forward', true); const dist = this.bot.entity.position.distanceTo(position); await sleep(dist * 350); this.bot.setControlState('forward', false); }
async _chopCategory(category, count = 5) { if (!this.bot?.entity) return; const scan = this.scanSurroundings(8); const targets = (scan.categories[category] || []).slice(0, count);
for (const target of targets) { if (!this.bot?.entity) break; try { await this._walkTo(target.block.position.offset(0, 1, 0)); await this.bot.dig(target.block); this.stats.blocksMined++; await sleep(rand(100, 400)); } catch(_) {} } }
async _collectNearbyItems() { if (!this.bot?.entity) return; const items = this.bot.entitiesArray.filter(e => e.type === 'item'); for (const item of items) { if (!this.bot?.entity) break; if (item.position.distanceTo(this.bot.entity.position) < 16) { await this._walkTo(item.position); await sleep(rand(100, 300)); } } }
async _findCave() { if (!this.bot?.entity) return false; // البحث عن كهف: دور على stone + air معاً const scan = this.scanSurroundings(32); const stones = scan.categories.stone || []; const holes = [];
for (const s of stones) { const above = this.bot.blockAt(s.block.position.offset(0, 1, 0)); const above2 = this.bot.blockAt(s.block.position.offset(0, 2, 0)); if (above?.name === 'air' || above2?.name === 'air') { holes.push(s); } }
if (holes.length > 0) { await this._walkTo(pick(holes).block.position); return true; }
// بديل: حفر للأسفل await this._digDown(10); return true; }
async _digDown(depth = 20) { if (!this.bot?.entity) return; for (let i = 0; i < depth; i++) { if (!this.bot?.entity || !this._running) break; const block = this.bot.blockAt(this.bot.entity.position.offset(0, -1, 0)); if (block && block.name !== 'air' && block.name !== 'water' && block.name !== 'lava') { try { await this.bot.dig(block); this.stats.blocksMined++; } catch(_) {} } await sleep(rand(200, 500)); } }
async _mineSpecific(target, count) { if (!this.bot?.entity) return; let mined = 0; const maxSearch = 64;
for (let i = 0; i < maxSearch && mined < count; i++) { if (!this.bot?.entity || !this._running) break; const scan = this.scanSurroundings(8); const targets = scan.categories.ore || scan.categories.stone || []; const match = targets.find(t => t.name === target || t.name.includes(target.split('_')[0]));
if (match) { try { await this._walkTo(match.block.position); await this.bot.dig(match.block); mined++; this.stats.blocksMined++; await sleep(rand(150, 400)); } catch(_) {} } else { // حفر عشوائي للبحث await this._digDown(1); } } }
async _placeTorches(count = 3) { if (!this.bot?.entity) return; const torch = this.bot.inventory.items().find(i => i.name === 'torch' || i.name === 'soul_torch'); if (!torch) return;
await this.bot.equip(torch, 'hand'); for (let i = 0; i < count; i++) { if (!this.bot?.entity) break; try { const block = this.bot.blockAt(this.bot.entity.position.offset( rand(-2, 2), -1, rand(-2, 2) )); if (block && block.name !== 'air') { await this.bot.placeBlock(block, { x: 0, y: 1, z: 0 }); await sleep(rand(200, 500)); } } catch(_) {} } }
async _findAndInteract(blockName) { if (!this.bot?.entity) return false; const block = this.bot.findBlock({ matching: this.bot.registry.blocksByName[blockName]?.id, maxDistance: 32, count: 1, }); if (block) { await this._walkTo(block.position); await sleep(rand(300, 700)); await this.bot.activateBlock(block); return true; } return false; }
async _craftItem(item, count = 1) { if (!this.bot?.entity) return; const mcData = require('minecraft-data')(this.bot.version); const itemInfo = mcData.itemsByName[item]; if (!itemInfo) return;
// البحث عن طاولة صناعة const table = this.bot.findBlock({ matching: this.bot.registry.blocksByName.crafting_table?.id, maxDistance: 16, count: 1, });
if (table) { await this._walkTo(table.position); await sleep(rand(300, 600)); }
try { const recipe = this.bot.recipesFor(itemInfo.id, null, 1, table)[0]; if (recipe) { await this.bot.craft(recipe, count, table || null); this.stats.itemsCrafted += count; await sleep(rand(500, 1000)); } } catch(_) {} }
async _smeltItem(action) { if (!this.bot?.entity) return; const furnace = this.bot.findBlock({ matching: this.bot.registry.blocksByName.furnace?.id, maxDistance: 16, count: 1, }); if (!furnace) return;
await this._walkTo(furnace.position); await sleep(rand(300, 600)); await this.bot.activateBlock(furnace); await sleep(rand(1000, 2000)); this.bot.closeWindow(); }
async _findAnimals() { if (!this.bot?.entity) return null; const animals = this.bot.entitiesArray.filter(e => e.type === 'mob' && ['cow', 'pig', 'chicken', 'sheep', 'rabbit'].includes(e.name) ); return animals.sort((a, b) => a.position.distanceTo(this.bot.entity.position) - b.position.distanceTo(this.bot.entity.position) )[0] || null; }
async _huntAnimals() { const animal = await this._findAnimals(); if (!animal || !this.bot?.entity) return; await this._walkTo(animal.position); try { await this.bot.attack(animal); await sleep(rand(200, 500)); await this._collectNearbyItems(); } catch(_) {} }
async _findBuildSpot() { if (!this.bot?.entity) return; // البحث عن أرض مسطحة const pos = this.bot.entity.position; for (let r = 0; r < 20; r++) { for (let angle = 0; angle < Math.PI * 2; angle += Math.PI / 4) { const x = Math.round(pos.x + Math.cos(angle) * r * 3); const z = Math.round(pos.z + Math.sin(angle) * r * 3); const base = this.bot.blockAt({ x, y: pos.y - 1, z }); const above = this.bot.blockAt({ x, y: pos.y, z }); const above2 = this.bot.blockAt({ x, y: pos.y + 1, z }); if (base && base.name !== 'air' && above?.name === 'air' && above2?.name === 'air') { await this._walkTo({ x, y: pos.y, z }); return; } } } }
async _hoeLand() { if (!this.bot?.entity) return; const hoe = this.bot.inventory.items().find(i => i.name.includes('hoe')); if (hoe) await this.bot.equip(hoe, 'hand');
for (let i = 0; i < 9; i++) { if (!this.bot?.entity) break; const offsets = [{x:0,z:0},{x:1,z:0},{x:-1,z:0},{x:0,z:1},{x:0,z:-1}, {x:1,z:1},{x:-1,z:-1},{x:1,z:-1},{x:-1,z:1}]; const off = offsets[i]; const block = this.bot.blockAt(this.bot.entity.position.offset(off.x, -1, off.z)); if (block && (block.name === 'grass_block' || block.name === 'dirt' || block.name === 'dirt_path')) { try { await this.bot.activateBlock(block); await sleep(rand(200, 400)); } catch(_) {} } } }
async _plantCrops() { if (!this.bot?.entity) return; const seeds = this.bot.inventory.items().find(i => i.name.includes('wheat_seeds') || i.name.includes('carrot') || i.name.includes('potato') ); if (seeds) await this.bot.equip(seeds, 'hand');
for (let i = 0; i < 9; i++) { if (!this.bot?.entity) break; const offsets = [{x:0,z:0},{x:1,z:0},{x:-1,z:0},{x:0,z:1},{x:0,z:-1}]; const off = offsets[i % offsets.length]; const block = this.bot.blockAt(this.bot.entity.position.offset(off.x, -1, off.z)); if (block && block.name === 'farmland') { try { await this.bot.placeBlock(block, { x: 0, y: 1, z: 0 }); await sleep(rand(100, 300)); } catch(_) {} } } }
async _waterCrops() { if (!this.bot?.entity) return; const water = this.bot.inventory.items().find(i => i.name === 'water_bucket'); if (water) { await this.bot.equip(water, 'hand'); const block = this.bot.blockAt(this.bot.entity.position.offset(0, -1, 0)); if (block) { try { await this.bot.placeBlock(block, { x: 0, y: 0, z: 0 }); } catch(_) {} } } }
async _cookFood() { if (!this.bot?.entity) return; const furnace = this.bot.findBlock({ matching: this.bot.registry.blocksByName.furnace?.id, maxDistance: 16, count: 1, }); if (furnace) { await this._walkTo(furnace.position); await this.bot.activateBlock(furnace); await sleep(1000); this.bot.closeWindow(); } }
async _equipItem(itemName) { if (!this.bot?.entity) return; const item = this.bot.inventory.items().find(i => i.name.includes(itemName)); if (item) await this.bot.equip(item, 'hand'); }
async _doFishing() { if (!this.bot?.entity) return; await this._equipItem('fishing_rod'); try { this.bot.fish(); await sleep(rand(5000, 20000)); this.bot.activateItem(); } catch(_) {} }
async _exploreArea() { if (!this.bot?.entity) return; const yaw = Math.random() * Math.PI * 2; const dist = rand(10, 30); this.bot.look(yaw, 0, false); this.bot.setControlState('forward', true); if (chance(30)) this.bot.setControlState('sprint', true); await sleep(dist * 350); this.bot.setControlState('forward', false); this.bot.setControlState('sprint', false); }
async _sortInventory() { if (!this.bot?.entity) return; const chest = this.bot.findBlock({ matching: this.bot.registry.blocksByName.chest?.id, maxDistance: 16, count: 1, }); if (chest) { await this._walkTo(chest.position); await this.bot.activateBlock(chest); await sleep(rand(1000, 3000)); // وضع أغراض في الصندوق const items = this.bot.inventory.items(); for (const item of items.slice(0, Math.min(9, items.length))) { try { await this.bot.clickWindow(item.slot, 0, 0); await sleep(100); } catch(_) {} } this.bot.closeWindow(); } }
async _buildStructure(type) { if (!this.bot?.entity) return; const plank = this.bot.inventory.items().find(i => i.name.includes('plank')); if (!plank) return; await this.bot.equip(plank, 'hand');
const pos = this.bot.entity.position; const base = { x: Math.round(pos.x), y: Math.round(pos.y), z: Math.round(pos.z) };
let blocks = []; if (type === 'floor') { for (let x = -2; x <= 2; x++) for (let z = -2; z <= 2; z++) blocks.push({x: base.x+x, y: base.y-1, z: base.z+z}); } else if (type === 'walls') { for (let y = 0; y <= 3; y++) { for (let x = -2; x <= 2; x++) { blocks.push({x: base.x+x, y: base.y+y, z: base.z-2}); blocks.push({x: base.x+x, y: base.y+y, z: base.z+2}); } for (let z = -1; z <= 1; z++) { blocks.push({x: base.x-2, y: base.y+y, z: base.z+z}); blocks.push({x: base.x+2, y: base.y+y, z: base.z+z}); } } } else if (type === 'roof') { for (let x = -2; x <= 2; x++) for (let z = -2; z <= 2; z++) blocks.push({x: base.x+x, y: base.y+4, z: base.z+z}); }
for (const b of blocks) { if (!this.bot?.entity) break; const block = this.bot.blockAt(b); if (block?.name === 'air') { try { const ref = this.bot.blockAt({x: b.x, y: b.y - 1, z: b.z}); if (ref && ref.name !== 'air') { await this.bot.placeBlock(ref, {x: 0, y: 1, z: 0}); await sleep(rand(80, 200)); } } catch(_) {} } } }
async _placeDoor() { if (!this.bot?.entity) return; const door = this.bot.inventory.items().find(i => i.name.includes('door')); if (door) { await this.bot.equip(door, 'hand'); const pos = this.bot.entity.position; const block = this.bot.blockAt(pos.offset(0, -1, 2)); if (block) { try { await this.bot.placeBlock(block, { x: 0, y: 1, z: 0 }); } catch(_) {} } } }
async _placeRedstone() { if (!this.bot?.entity) return; const items = ['redstone', 'piston', 'observer', 'repeater']; for (const itemName of items) { const item = this.bot.inventory.items().find(i => i.name.includes(itemName)); if (item) { await this.bot.equip(item, 'hand'); await sleep(rand(200, 400)); } } }
async _placeWater() { if (!this.bot?.entity) return; const water = this.bot.inventory.items().find(i => i.name === 'water_bucket'); if (water) { await this.bot.equip(water, 'hand'); const block = this.bot.blockAt(this.bot.entity.position.offset(0, -1, 0)); if (block) { try { await this.bot.placeBlock(block, { x: 0, y: 0, z: 0 }); } catch(_) {} } } }
async _brewPotion() { if (!this.bot?.entity) return; const stand = this.bot.findBlock({ matching: this.bot.registry.blocksByName.brewing_stand?.id, maxDistance: 16, count: 1, }); if (stand) { await this._walkTo(stand.position); await this.bot.activateBlock(stand); await sleep(rand(1000, 2000)); this.bot.closeWindow(); } }
// ════════════════════════════════════════════════════════════════════════════ // تقنية Tech Tree // ════════════════════════════════════════════════════════════════════════════ _unlockTech(taskDef) { for (const [techId, tech] of Object.entries(TECH_TREE)) { if (this.technologies.has(techId)) continue; const reqs = tech.requires.every(r => this.technologies.has(r)); if (reqs) { this.technologies.add(techId); this._log('🔓', `فُتحت تقنية جديدة: ${tech.name}`); } } }
canDoTask(taskId) { const task = TASK_DEFINITIONS[taskId]; if (!task) return false; return task.dependencies.every(d => this.completedTasks.includes(d)); }
getAvailableTasks() { return Object.values(TASK_DEFINITIONS).filter(t => this.canDoTask(t.id) && !this.completedTasks.includes(t.id) ); }
// ════════════════════════════════════════════════════════════════════════════ // بدء/إيقاف النظام // ��═══════════════════════════════════════════════════════════════════════════ start() { if (this._running) return; this._running = true; this._log('🟢', 'بدء نظام الوظائف الذكي');
// حلقة العمل الرئيسية this._workLoop(); }
stop() { this._running = false; this._timers.forEach(t => { try { clearInterval(t); clearTimeout(t); } catch(_){} }); this._timers = []; this._log('🔴', 'إيقاف نظام الوظائف'); }
async _workLoop() { while (this._running && this.bot?.entity) { try { const available = this.getAvailableTasks(); if (available.length === 0) { this._log('💤', 'لا توجد مهام متاحة — في انتظار...'); await sleep(10000); continue; }
// اختيار المهمة الأعلى أولوية const task = available.sort((a, b) => b.priority - a.priority)[0]; await this.executeTask(task);
// راحة بين المهام await sleep(rand(2000, 5000)); } catch(e) { this._log('❌', `خطأ في حلقة العمل: ${e.message}`); await sleep(5000); } } }
// ════════════════════════════════════════════════════════════════════════════ // API // ════════════════════════════════════════════════════════════════════════════ getStatus() { return { running: this._running, currentTask: this.currentTask ? { id: this.currentTask.id, name: this.currentTask.name } : null, completedTasks: this.completedTasks.length, failedTasks: this.failedTasks.length, technologies: [...this.technologies], stats: { ...this.stats }, availableTasks: this.getAvailableTasks().length, }; }
destroy() { this.stop(); this.removeAllListeners(); }}
module.exports = { SmartJobSystem, BLOCK_DATABASE, TECH_TREE, TASK_DEFINITIONS, BOT_ROLES };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234'use strict';/** * Mining System — نظام التعدين * يروح يحفر، يجمع معادن، يكتشف كهوف */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const chance = pct => Math.random() * 100 < pct;const pick = arr => arr[Math.floor(Math.random() * arr.length)];
const ORE_PRIORITY = [ 'diamond_ore','deepslate_diamond_ore', 'emerald_ore','deepslate_emerald_ore', 'gold_ore','deepslate_gold_ore', 'iron_ore','deepslate_iron_ore', 'redstone_ore','deepslate_redstone_ore', 'lapis_ore','deepslate_lapis_ore', 'coal_ore','deepslate_coal_ore', 'copper_ore','deepslate_copper_ore',];
const VALUABLE_ITEMS = new Set([ 'diamond','emerald','gold_ingot','iron_ingot','netherite_scrap', 'netherite_ingot','redstone','lapis_lazuli','coal','copper_ingot', 'raw_iron','raw_gold','raw_copper','flint',]);
class MiningSystem extends EventEmitter { constructor(bot, config = {}) { super(); this.bot = bot; this.config = { scanRadius: 24, mineDepth: 40, torchInterval: 12, ...config, }; this._active = false; this._timers = []; this._mining = false; this._blocksMined = 0; this._oresFound = {}; this._totalValue = 0; this._log('INIT', 'نظام التعدين جاهز'); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [MINING] ${tag} ${msg}`); }
start() { if (this._active) return; this._active = true; this._log('START', 'بدء نظام التعدين');
// يدور على معادن كل 5 ثواني this._addTimer(() => this._scanForOres(), 5000);
// يحط مشاعل تلقائياً this._addTimer(() => this._placeTorches(), 8000); }
stop() { this._active = false; this._mining = false; this._timers.forEach(t => { try { clearInterval(t); clearTimeout(t); } catch(_) {} }); this._timers = []; this._log('STOP', 'إيقاف نظام التعدين'); }
_addTimer(fn, interval) { const t = setInterval(() => { if (this._active) fn(); }, interval); this._timers.push(t); }
// ═══ كشف المعادن القريبة ═══ _scanForOres() { if (!this.bot?.entity || this._mining) return; const pos = this.bot.entity.position; const radius = this.config.scanRadius;
for (let x = -radius; x <= radius; x += 2) { for (let y = -radius; y <= radius; y++) { for (let z = -radius; z <= radius; z += 2) { const block = this.bot.blockAt(pos.offset(x, y, z)); if (!block) continue; if (ORE_PRIORITY.includes(block.name)) { this._mineBlock(block); return; } } } } }
// ═══ حفر كتلة ═══ async _mineBlock(block) { if (this._mining || !this.bot?.entity) return; this._mining = true;
try { // اختار أفضل مجرفة/فأس await this._equipBestTool(block.name);
// امشي للكتلة await this._walkTo(block.position);
// حفر try { await this.bot.dig(block); this._blocksMined++;
// سجّل المعدن if (ORE_PRIORITY.includes(block.name)) { const ore = block.name.replace('deepslate_', '').replace('_ore', ''); this._oresFound[ore] = (this._oresFound[ore] || 0) + 1; this._totalValue += this._getOreValue(ore); this._log('⛏️', `حفر ${block.name} (إجمالي: ${this._blocksMined})`); this.emit('ore', ore, block.name); } } catch(_) {}
await sleep(rand(100, 300)); } catch(e) { this._log('❌', `خطأ: ${e.message}`); } finally { this._mining = false; } }
// ═══ اختيار أفضل أداة ═══ async _equipBestTool(blockName) { if (!this.bot) return; const isOre = blockName.includes('ore'); const isStone = ['stone','deepslate','granite','diorite','andesite'].some(s => blockName.includes(s));
let toolType = 'pickaxe'; if (blockName.includes('log') || blockName.includes('wood')) toolType = 'axe'; else if (blockName.includes('dirt') || blockName.includes('sand') || blockName.includes('gravel')) toolType = 'shovel';
const items = this.bot.inventory.items(); const tools = items.filter(i => i.name.includes(toolType)); if (tools.length > 0) { // الأعلى في الترتيب const best = tools.sort((a, b) => this._toolRank(b.name) - this._toolRank(a.name))[0]; try { await this.bot.equip(best, 'hand'); } catch(_) {} } }
_toolRank(name) { if (name.includes('netherite')) return 6; if (name.includes('diamond')) return 5; if (name.includes('iron')) return 4; if (name.includes('stone')) return 3; if (name.includes('golden')) return 2; if (name.includes('wooden')) return 1; return 0; }
// ═══ المشي ═══ async _walkTo(position) { if (!this.bot?.entity) return; const yaw = Math.atan2( position.z - this.bot.entity.position.z, position.x - this.bot.entity.position.x ); this.bot.look(yaw, 0, false); this.bot.setControlState('forward', true); await sleep(rand(200, 600)); this.bot.setControlState('forward', false); }
// ═══ وضع مشاعل ═══ async _placeTorches() { if (!this.bot?.entity) return; const torch = this.bot.inventory.items().find(i => i.name === 'torch' || i.name === 'soul_torch'); if (!torch) return;
// لو المشاعل قليلة، حط واحدة كل فتره const torchCount = this.bot.inventory.items().filter(i => i.name === 'torch').length; if (torchCount > 3 && chance(50)) return;
try { await this.bot.equip(torch, 'hand'); const block = this.bot.blockAt(this.bot.entity.position.offset(0, -1, 0)); if (block && block.name !== 'air') { await this.bot.placeBlock(block, { x: 0, y: 1, z: 0 }); } } catch(_) {} }
// ═══ قيمة المعدن ═══ _getOreValue(ore) { const values = { diamond: 10, emerald: 8, gold: 5, iron: 3, redstone: 2, lapis: 2, coal: 1, copper: 1 }; return values[ore] || 1; }
// ═══ النزول للأعماق ═══ async digDown() { if (!this.bot?.entity) return; this._log('🔽', 'النزول للأعماق'); for (let i = 0; i < this.config.mineDepth; i++) { if (!this.bot?.entity || !this._active) break; const block = this.bot.blockAt(this.bot.entity.position.offset(0, -1, 0)); if (block && block.name !== 'air' && block.name !== 'water' && block.name !== 'lava') { try { await this._equipBestTool(block.name); await this.bot.dig(block); this._blocksMined++; } catch(_) {} } await sleep(rand(150, 400)); } }
getStats() { return { blocksMined: this._blocksMined, oresFound: { ...this._oresFound }, totalValue: this._totalValue, mining: this._mining, active: this._active, }; }
destroy() { this.stop(); this.removeAllListeners(); }}
module.exports = { MiningSystem, ORE_PRIORITY, VALUABLE_ITEMS };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242'use strict';
/** * ╔══════════════════════════════════════════════════════════════════════════╗ * Multi-Server Manager — v23.0 | دعم سيرفرات متعددة ║ * ╠══════════════════════════════════════════════════════════════════════════╣ * ✅ Multiple Servers: تشغيل سيرفرات متعددة في نفس الوقت ║ * ✅ Server Switching: التبديل بين السيرفرات ║ * ✅ Load Balancing: توزيع البوتات على السيرفرات ║ * ✅ Server Profiles: ملفات شخصية لكل سيرفر ║ * ✅ Cross-Server Chat: دردشة بين السيرفرات ║ * ✅ Resource Sharing: مشاركة الموارد بين السيرفرات ║ * ✅ Auto-Failover: تبديل تلقائي عند فشل سيرفر ║ * ✅ Health Monitoring: مراقبة صحة جميع السيرفرات ║ * ╚══════════════════════════════════════════════════════════════════════════╝ */
const { EventEmitter } = require('events');const fs = require('fs');const path = require('path');
const tsNow = () => new Date().toISOString().replace('T', ' ').slice(0, 19);
class MultiServerManager extends EventEmitter { constructor(config = {}) { super(); this.configPath = config.configPath || path.join(__dirname, 'servers.json'); this.servers = new Map(); this.activeServers = new Map(); this.serverHistory = []; this.maxHistory = 100; this._running = false; this._healthTimer = null; this._log('MULTI', 'تم إنشاء Multi-Server Manager'); }
_log(tag, msg) { console.log(`[${tsNow()}] [MULTI] ${tag} ${msg}`); }
// ─── Server Management ──────────────────────────────────────────────── addServer(id, config) { const server = { id, name: config.name || `Server ${id}`, host: config.host, port: config.port || 25565, version: config.version || '1.21.4', maxBots: config.maxBots || 4, currentBots: 0, status: 'offline', priority: config.priority || 0, lastCheck: null, lastOnline: null, consecutiveFailures: 0, config: config, botNames: config.botNames || [], features: config.features || {}, metadata: {}, }; this.servers.set(id, server); this._log('➕', `سيرفر جديد: ${server.name} (${server.host}:${server.port})`); this.emit('serverAdded', server); return server; }
removeServer(id) { const server = this.servers.get(id); if (!server) return false; this.servers.delete(id); this._log('➖', `حذف سيرفر: ${server.name}`); this.emit('serverRemoved', server); return true; }
getServer(id) { return this.servers.get(id) || null; }
getAllServers() { return [...this.servers.values()]; }
getOnlineServers() { return [...this.servers.values()].filter(s => s.status === 'online'); }
getAvailableServers() { return [...this.servers.values()].filter(s => s.status === 'online' && s.currentBots < s.maxBots ); }
// ─── Load Balancing ─────────────────────────────────────────────────── getNextServer() { const available = this.getAvailableServers(); if (available.length === 0) return null; available.sort((a, b) => { if (a.priority !== b.priority) return b.priority - a.priority; return (a.currentBots / a.maxBots) - (b.currentBots / b.maxBots); }); return available[0]; }
distributeBots(botCount) { const servers = this.getAvailableServers(); if (servers.length === 0) return [];
const distribution = []; const perServer = Math.ceil(botCount / servers.length);
for (const server of servers) { const botsForServer = Math.min(perServer, server.maxBots - server.currentBots); if (botsForServer > 0) { distribution.push({ server, count: botsForServer }); } }
return distribution; }
// ─── Server Status ──────────────────────────────────────────────────── updateServerStatus(id, status, metadata = {}) { const server = this.servers.get(id); if (!server) return;
const oldStatus = server.status; server.status = status; server.lastCheck = Date.now(); Object.assign(server.metadata, metadata);
if (status === 'online') { server.lastOnline = Date.now(); server.consecutiveFailures = 0; } else if (status === 'offline') { server.consecutiveFailures++; }
if (oldStatus !== status) { this._log('🔄', `${server.name}: ${oldStatus} → ${status}`); this.emit('statusChange', id, status, oldStatus); }
this._recordEvent(id, 'status', { from: oldStatus, to: status }); }
_recordEvent(serverId, type, data) { this.serverHistory.push({ serverId, type, data, time: Date.now() }); if (this.serverHistory.length > this.maxHistory) this.serverHistory.shift(); }
// ─── Cross-Server Chat ──────────────────────────────────────────────── broadcastMessage(fromServer, username, message) { for (const [id, server] of this.servers) { if (id !== fromServer && server.status === 'online') { this.emit('crossServerMessage', { fromServer, toServer: id, username, message }); } } }
// ─── Health Monitoring ──────────────────────────────────────────────── startMonitoring(intervalMs = 30000) { if (this._running) return; this._running = true; this._healthTimer = setInterval(() => this._checkHealth(), intervalMs); this._log('🟢', 'بدء مراقبة السيرفرات'); }
stopMonitoring() { this._running = false; if (this._healthTimer) { clearInterval(this._healthTimer); this._healthTimer = null; } this._log('🔴', 'إيقاف مراقبة السيرفرات'); }
_checkHealth() { for (const [id, server] of this.servers) { if (server.consecutiveFailures >= 5) { this.emit('serverUnstable', id, server); } if (server.status === 'offline' && server.consecutiveFailures >= 3) { this.emit('failoverNeeded', id, server); } } }
// ─── File Persistence ───────────────────────────────────────────────── saveConfig() { try { const data = {}; for (const [id, server] of this.servers) { data[id] = { name: server.name, host: server.host, port: server.port, version: server.version, maxBots: server.maxBots, priority: server.priority, config: server.config, botNames: server.botNames, features: server.features, }; } fs.writeFileSync(this.configPath, JSON.stringify(data, null, 2)); this._log('💾', 'تم حفظ إعدادات السيرفرات'); } catch (e) { this._log('❌', `خطأ في الحفظ: ${e.message}`); } }
loadConfig() { try { if (!fs.existsSync(this.configPath)) return; const raw = fs.readFileSync(this.configPath, 'utf8'); const data = JSON.parse(raw); for (const [id, cfg] of Object.entries(data)) { this.addServer(id, cfg); } this._log('📂', `تم تحميل ${Object.keys(data).length} سيرفر`); } catch (e) { this._log('❌', `خطأ في التحميل: ${e.message}`); } }
// ─── Status ─────────────────────────────────────────────────────────── getStatus() { const servers = [...this.servers.values()]; return { total: servers.length, online: servers.filter(s => s.status === 'online').length, offline: servers.filter(s => s.status === 'offline').length, starting: servers.filter(s => s.status === 'starting').length, totalBots: servers.reduce((a, s) => a + s.currentBots, 0), maxBots: servers.reduce((a, s) => a + s.maxBots, 0), servers: servers.map(s => ({ id: s.id, name: s.name, host: s.host, port: s.port, status: s.status, bots: `${s.currentBots}/${s.maxBots}`, priority: s.priority, failures: s.consecutiveFailures, })), history: this.serverHistory.slice(-20), }; }
destroy() { this.stopMonitoring(); this.removeAllListeners(); }}
module.exports = { MultiServerManager };123456789101112131415161718192021222324252627282930{ "name": "sayed-bot-team", "version": "23.0.0", "private": true, "scripts": { "start": "node bot-team.js", "dev": "node --max-old-space-size=450 bot-team.js", "build": "npm install --production --no-optional" }, "dependencies": { "dotenv": "^16.4.7", "express": "^4.18.2", "minecraft-data": "^3.81.0", "minecraft-protocol": "^1.47.0", "mineflayer": "^4.37.1", "mineflayer-pathfinder": "^2.4.5", "socket.io": "^4.7.0", "vec3": "^0.2.0", "ws": "^8.16.0", "zod": "^3.22.0" }, "optionalDependencies": { "@sparticuz/chromium": "^123.0.1", "puppeteer": "^22.6.5", "puppeteer-core": "^22.6.5" }, "engines": { "node": ">=18.0.0" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218'use strict';
/** * ╔══════════════════════════════════════════════════════════════════════════╗ * Performance Optimizer — v23.0 | تحسين الأداء والذاكرة ║ * ╠══════════════════════════════════════════════════════════════════════════╣ * ✅ Memory Management: إدارة ذاكرة ذكية + auto-cleanup ║ * ✅ Object Pooling: إعادة استخدام الكائنات لتقليل GC ║ * ✅ Throttling: تقييد العمليات الثقيلة ║ * ✅ Caching: تخزين مؤقت ذكي للاستعلامات المتكررة ║ * ✅ Metrics: قياس الأداء في الوقت الحقيقي ║ * ✅ Auto-Tune: تحسين تلقائي للإعدادات حسب الأداء ║ * ✅ Garbage Collection: جامع نفايات ذكي ║ * ✅ Connection Pool: إدارة اتصالات فعّالة ║ * ╚══════════════════════════════════════════════════════════════════════════╝ */
const { EventEmitter } = require('events');
const tsNow = () => new Date().toISOString().replace('T', ' ').slice(0, 19);
class PerformanceOptimizer extends EventEmitter { constructor(config = {}) { super(); this.config = { memoryLimitMB: config.memoryLimitMB || 380, gcIntervalMs: config.gcIntervalMs || 30000, metricsIntervalMs: config.metricsIntervalMs || 5000, maxCacheSize: config.maxCacheSize || 1000, throttleMs: config.throttleMs || 100, autoTune: config.autoTune !== false, ...config, };
this.metrics = { memory: { used: 0, total: 0, limit: 0, usage: 0 }, cpu: { usage: 0, loadAvg: [0, 0, 0] }, events: { emitted: 0, processed: 0, dropped: 0 }, cache: { hits: 0, misses: 0, size: 0 }, gc: { collections: 0, freed: 0, lastAt: null }, uptime: 0, botCount: 0, activeTimers: 0, };
this.cache = new Map(); this.pools = new Map(); this.throttled = new Map(); this._running = false; this._gcTimer = null; this._metricsTimer = null;
this._log('OPTIMIZER', 'تم إنشاء Performance Optimizer'); }
_log(tag, msg) { console.log(`[${tsNow()}] [PERF] ${tag} ${msg}`); }
start() { if (this._running) return; this._running = true; this._log('🟢', 'بدء تحسين الأداء');
this._gcTimer = setInterval(() => this._runGC(), this.config.gcIntervalMs); this._metricsTimer = setInterval(() => this._collectMetrics(), this.config.metricsIntervalMs); this._collectMetrics(); }
stop() { this._running = false; if (this._gcTimer) { clearInterval(this._gcTimer); this._gcTimer = null; } if (this._metricsTimer) { clearInterval(this._metricsTimer); this._metricsTimer = null; } this._log('🔴', 'إيقاف Performance Optimizer'); }
// ─── Memory Management ──────────────────────────────────────────────── _collectMetrics() { if (!this._running) return; try { const mem = process.memoryUsage(); this.metrics.memory = { used: Math.round(mem.heapUsed / 1024 / 1024), total: Math.round(mem.heapTotal / 1024 / 1024), limit: this.config.memoryLimitMB, usage: Math.round((mem.heapUsed / 1024 / 1024 / this.config.memoryLimitMB) * 100), }; this.metrics.cpu = { usage: process.cpuUsage().user / 1000000, loadAvg: require('os').loadavg().map(l => Math.round(l * 100) / 100), }; this.metrics.uptime = Math.round(process.uptime()); this.metrics.cache.size = this.cache.size;
if (this.metrics.memory.usage > 85) { this._log('⚠️', `ذاكرة عالية: ${this.metrics.memory.usage}%`); this._aggressiveCleanup(); this.emit('memoryWarning', this.metrics.memory); }
if (this.config.autoTune) this._autoTune();
this.emit('metrics', this.metrics); } catch(_) {} }
_runGC() { if (!this._running) return; try { if (global.gc) { const before = process.memoryUsage().heapUsed; global.gc(); const after = process.memoryUsage().heapUsed; const freed = Math.round((before - after) / 1024 / 1024); this.metrics.gc.collections++; this.metrics.gc.freed += freed; this.metrics.gc.lastAt = tsNow(); if (freed > 1) this._log('🗑️', `GC: freed ${freed}MB`); } } catch(_) {} }
_aggressiveCleanup() { this.cache.clear(); this.pools.forEach(pool => { pool.length = 0; }); if (global.gc) try { global.gc(); } catch(_) {} this._log('🧹', 'تنظيف عنيف للذاكرة'); }
_autoTune() { const usage = this.metrics.memory.usage; if (usage > 80) { this.config.gcIntervalMs = Math.max(10000, this.config.gcIntervalMs - 5000); this.config.maxCacheSize = Math.max(100, this.config.maxCacheSize - 100); } else if (usage < 50) { this.config.gcIntervalMs = Math.min(60000, this.config.gcIntervalMs + 5000); this.config.maxCacheSize = Math.min(2000, this.config.maxCacheSize + 100); } }
// ─── Object Pooling ─────────────────────────────────────────────────── getPool(name, factory, initialSize = 10) { if (!this.pools.has(name)) { const pool = []; for (let i = 0; i < initialSize; i++) pool.push(factory()); this.pools.set(name, pool); } return { acquire: () => { const pool = this.pools.get(name); return pool.length > 0 ? pool.pop() : factory(); }, release: (obj) => { const pool = this.pools.get(name); if (pool.length < this.config.maxCacheSize) pool.push(obj); }, }; }
// ─── Caching ────────────────────────────────────────────────────────── cacheGet(key) { const entry = this.cache.get(key); if (entry && Date.now() - entry.time < (entry.ttl || 30000)) { this.metrics.cache.hits++; return entry.value; } this.metrics.cache.misses++; if (entry) this.cache.delete(key); return null; }
cacheSet(key, value, ttlMs = 30000) { if (this.cache.size >= this.config.maxCacheSize) { const oldest = this.cache.keys().next().value; if (oldest) this.cache.delete(oldest); } this.cache.set(key, { value, time: Date.now(), ttl: ttlMs }); }
cacheClear() { this.cache.clear(); }
// ─── Throttling ─────────────────────────────────────────────────────── throttle(key, fn, delayMs) { const last = this.throttled.get(key) || 0; const now = Date.now(); if (now - last >= (delayMs || this.config.throttleMs)) { this.throttled.set(key, now); return fn(); } return null; }
// ─── Metrics API ────────────────────────────────────────────────────── getMetrics() { return { ...this.metrics }; }
getHealth() { const m = this.metrics; return { status: m.memory.usage < 70 ? 'healthy' : m.memory.usage < 85 ? 'warning' : 'critical', memory: `${m.memory.used}/${m.memory.limit}MB (${m.memory.usage}%)`, cache: `hits: ${m.cache.hits}, misses: ${m.cache.misses}`, gc: `collections: ${m.gc.collections}, freed: ${m.gc.freed}MB`, uptime: `${Math.floor(m.uptime/3600)}h ${Math.floor((m.uptime%3600)/60)}m`, }; }
destroy() { this.stop(); this.cache.clear(); this.pools.clear(); this.throttled.clear(); this.removeAllListeners(); }}
module.exports = { PerformanceOptimizer };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238'use strict';/** * Q&A System — نظام الأسئلة والأجوبة * يسمع سؤال من اللاعب ويرد بجواب واقعي */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const chance = pct => Math.random() * 100 < pct;const pick = arr => arr[Math.floor(Math.random() * arr.length)];
// ═══ قاعدة معرفة الأسئلة ═══const KNOWLEDGE_BASE = { // ─── أسئلة عامة ────────────────────────────────────────────────────── general: [ { q: ['وين أنت','وين أنت؟','وين نت؟','وين أنتو'], a: ['هناك بالقرب','قريب منك','أنا هنا','لفي شوي وبتلقاني'] }, { q: ['شنو أسمك','شنو اسمك','وش اسمك','اسمك إيه'], a: ['أنا بوت','سayed bot','اسمي ما يهم','أنا صديقك'] }, { q: ['شسالفة','شنو السالفة','شنو صاير','وين الناس'], a: ['السيرفر شغال عادي','كل شي تمام','الجو حلو','خلنا نلعب'] }, { q: [' كيفك','شلونك','شخبارك','عامل إيه'], a: ['الحمد لله تمام','بخير وعافية','كويس أنت عامل إيه','تمام والله'] }, { q: ['تصبحون على خير','تصبح على خير','باي','مع السلامة'], a: ['وأنت من أهل الخير','باي','الله معك','نورتنا'] }, { q: ['صباح الخير','صباح النور'], a: ['صباح النور','صباح الفل','يومك حلو',' Allah ysbhak bel kheir'] }, ],
// ─── أسئلة عن السيرفر ────────────────────────────────────────────── server: [ { q: ['وين السيرفر','شسمه السيرفر','اسم السيرفر','اي سيرفر'], a: ['هذا سيرفر أصدقاء','سيرفرنا الحلو','السيرفر مفتوح للجميع','انضم وانبسط'] }, { q: ['شغال السيرفر','السيرفر شغال','شغّال'], a: ['أيوا شغال 24/7','الحمد لله شغال','شغال وما وقف','يوم الليل والنهار'] }, { q: ['كم لاعب','كم واحد','كم واحد أونلاين'], a: ['الحين بس أنت وأنا','فيه ناس بتيجي','السيرفر جديد','شوية شوية'] }, { q: ['شنو المودات','شنو البلاجن','ايش المثبت'], a: ['فيه بلجنات كتير','شوف القائمة','بلاجنات حماية وأداء','كل شي مثبت'] }, ],
// ─── أسئلة عن البناء ────────────────────────────────────────────── building: [ { q: ['وش أبني','ابني إيه','نبي نبني','ابنيلي'], a: ['ابنِ بيت صغير','خلنا نبني قصر','ابنِ مزرعة','الخيار لك'] }, { q: ['وين الخشب','عندي خشب','نبي خشب'], a: ['روح قطع شجر','فيه أشجار قريبة','استخدم الفأس'] }, { q: ['شسوي بالحجر','الحجر يسوى'], a: ['ابنِ جدار','سوي أدوات','حط حجر فوق حجر','الحجر useful'] }, ],
// ─── أسئلة عن القتال ────────────────────────────────────────────── combat: [ { q: ['فيه وحوش','وحوش قريبة','خلونا نقاتل','نبي نضرب'], a: ['روح بالليل','تلقى وحوش كتير','انتبه للكريبرز','خذ سيفك'] }, { q: ['وش أحسن سلاح','أفضل سلاح','سيف أو فأس'], a: ['السيف للقتال','الفأس للحفر والقتال','الماس أحسن شي','خزّن سلاحك'] }, { q: ['كيف أقتل الكريبرز','الكريبرز ينفجر','خلونا نهرب من الكريبرز'], a: ['اضربه واهرب','ابعده بالقوس','لا تقرب منه كثير','اركض!'] }, { q: ['شلون أقوى','كيف أتص做强','نبي أقوى'], a: ['خزّن ماس','سوي درع حديد','اكل عشان تقوى','تدرّب'] }, ],
// ─── أسئلة عن الطعام ────────────────────────────────────────────── food: [ { q: ['جعان','نبي أكل','فيني جوع','أبي أكل'], a: ['اكل خبز','صيد حيوان','فيه تفاح','اطبخ لحم'] }, { q: ['وش آكل','أفضل أكل','ايش آكل'], a: ['الخبز سهل','لحم مشوي أحسن','تفاح صحي','اكل أي شي'] }, { q: ['فيني عطش','شرب','نبي ماء'], a: ['اشرب من النهر','خزّن دلو ماء','فيه ماء قريب'] }, ],
// ─── أسئلة عن التعدين ────────────────────────────────────────────── mining: [ { q: ['وين الحديد','فين الحديد','نبي حديد'], a: ['روح الكهف','حفر للأسفل','الحديد تحتك'] }, { q: ['وين الماس','فين الماس','نبي ماس'], a: ['حفر عميق','المنجم 11','انتبه للمخلوقات'] }, { q: ['شلون أحفر','كيف أحفر','نبي أحفر'], a: ['خذ مجرفة','روح كهف','حط مشاعل'] }, ],
// ─── أسئلة عن الزراعة ────────────────────────────────────────────── farming: [ { q: ['نبي أزرع','شلون أزرع','كيف أزرع'], a: ['خذ حرثة','حفر الأرض','حط بذور','اسقي'] }, { q: ['وين البذور','فين البذور','نبي بذور'], a: ['كسر العشب','عندك بذور','اشتري من المتجر'] }, ],
// ─── أسئلة عن الصناعة ────────────────────────────────────────────── crafting: [ { q: ['شلون أصنع','كيف أصنع','نبي أصنع'], a: ['حط طاولة صناعة','اضغط يمين','شوف الوصفات'] }, { q: ['وين الفرن','فين الفرن','نبي فرن'], a: ['اصنع واحد','8 حجر','حطه وبستخدمه'] }, ],};
// ═══ إشارات السؤال ═══const QUESTION_SIGNALS = ['؟', '?', 'وش', 'شنو', 'كيف', 'وين', 'ليش', 'كم', 'مين', 'أفضل', 'شنو رأيك'];
class QASystem extends EventEmitter { constructor(bot, config = {}) { super(); this.bot = bot; this.config = { respondChance: config.respondChance || 60, cooldown: config.cooldown || 5000, maxResponseLength: config.maxResponseLength || 100, customAnswers: config.customAnswers || {}, ...config, }; this._active = false; this._chatHandler = null; this._lastResponse = 0; this._questionsAnswered = 0; this._customKB = {}; // قاعدة معرفة مخصصة this._log('INIT', 'نظام الأسئلة والأجوبة جاهز'); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [QA] ${tag} ${msg}`); }
start() { if (this._active) return; this._active = true;
// استمع للرسائل this._chatHandler = (msg) => this._onMessage(msg); this.bot.on('messagestr', this._chatHandler);
this._log('START', 'بدء نظام الأسئلة'); }
stop() { this._active = false; if (this.bot && this._chatHandler) { this.bot.removeListener('messagestr', this._chatHandler); } this._log('STOP', 'إيقاف نظام الأسئلة'); }
// ═══ استقبال رسالة ═══ _onMessage(msg) { if (!this._active || !msg) return; const text = msg.toString().replace(/<[^>]+>/g, '').trim(); if (!text || text.length < 3) return;
// فحص لو سؤال const isQuestion = QUESTION_SIGNALS.some(s => text.includes(s)); if (!isQuestion) return;
// فحصCooldown if (Date.now() - this._lastResponse < this.config.cooldown) return;
// فحص احتمال الرد if (!chance(this.config.respondChance)) return;
// دور على جواب const answer = this._findAnswer(text); if (answer) { this._sendAnswer(answer); } }
// ═══ البحث عن جواب ═══ _findAnswer(question) { const q = question.toLowerCase();
// دور في قاعدة المعرفة for (const [category, items] of Object.entries(KNOWLEDGE_BASE)) { for (const item of items) { if (item.q.some(pattern => q.includes(pattern.toLowerCase()))) { return { text: pick(item.a), category, confidence: 0.9, }; } } }
// دور في القاعدة المخصصة for (const [pattern, answers] of Object.entries(this._customKB)) { if (q.includes(pattern.toLowerCase())) { return { text: pick(answers), category: 'custom', confidence: 1.0, }; } }
// لو ما لقى شي — رد عام if (chance(30)) { return { text: pick(['الله أعلم','مش عارف','جرّب وشوف','ما أدري','سؤال حلو']), category: 'fallback', confidence: 0.2, }; }
return null; }
// ═══ إرسال جواب ═══ async _sendAnswer(answer) { if (!this.bot) return;
try { const safe = answer.text.replace(/[^\x20-\x7E\u0600-\u06FF ]/g, '').slice(0, this.config.maxResponseLength); this.bot.chat(safe); this._lastResponse = Date.now(); this._questionsAnswered++; this._log('💬', `رد: ${safe} (${answer.category})`); this.emit('answered', answer); } catch(_) {} }
// ═══ إضافة جواب مخصص ═══ addCustomAnswer(pattern, answers) { if (typeof pattern === 'string' && Array.isArray(answers)) { this._customKB[pattern] = answers; this._log('➕', `إضافة: "${pattern}" → ${answers.length} أجوبة`); } }
// ═══ إزالة جواب مخصص ═══ removeCustomAnswer(pattern) { delete this._customKB[pattern]; }
// ═══ تعلم سؤال جديد ═══ learnQuestion(question, answer) { if (!question || !answer) return; const q = question.toLowerCase();
// أضف للقاعدة المخصصة if (!this._customKB[q]) { this._customKB[q] = []; } this._customKB[q].push(answer); this._log('🧠', `تعلم: "${question}" → "${answer}"`); }
// ═══ إحصائيات ═══ getStats() { return { questionsAnswered: this._questionsAnswered, customAnswers: Object.keys(this._customKB).length, active: this._active, }; }
destroy() { this.stop(); this.removeAllListeners(); }}
module.exports = { QASystem, KNOWLEDGE_BASE, QUESTION_SIGNALS };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265'use strict';
/** * ╔══════════════════════════════════════════════════════════════════════════╗ * Security — v19.0 | Security Layers for Bot + Dashboard ║ * ╠══════════════════════════════════════════════════════════════════════════╣ * ✅ Rate Limiting: Token bucket per IP/bot ║ * ✅ Input Validation: Whitelist commands + sanitize strings ║ * ✅ Auth: Simple password for dashboard (DASH_PASSWORD env) ║ * ✅ Command Injection Prevention: No eval, parameterized ║ * ✅ Anti-Bot Detection: Randomized usernames + human patterns ║ * ✅ Data Protection: Config sanitization ║ * ╚══════════════════════════════════════════════════════════════════════════╝ */
const crypto = require('crypto');
const tsNow = () => new Date().toISOString().replace('T', ' ').slice(0, 19);
class RateLimiter { constructor(options = {}) { this.maxTokens = options.maxTokens || 10; this.refillRate = options.refillRate || 1; this.refillInterval = options.refillInterval || 1000; this.buckets = new Map(); this._cleanupTimer = setInterval(() => this._cleanup(), 60000); }
_cleanup() { const now = Date.now(); for (const [key, bucket] of this.buckets) { if (now - bucket.lastRefill > 300000) { this.buckets.delete(key); } } }
tryConsume(key, tokens = 1) { const now = Date.now(); let bucket = this.buckets.get(key); if (!bucket) { bucket = { tokens: this.maxTokens, lastRefill: now }; this.buckets.set(key, bucket); } const elapsed = now - bucket.lastRefill; const refill = Math.floor(elapsed / this.refillInterval) * this.refillRate; bucket.tokens = Math.min(this.maxTokens, bucket.tokens + refill); bucket.lastRefill = now; if (bucket.tokens >= tokens) { bucket.tokens -= tokens; return true; } return false; }
getRemaining(key) { const bucket = this.buckets.get(key); return bucket ? bucket.tokens : this.maxTokens; }
destroy() { clearInterval(this._cleanupTimer); this.buckets.clear(); }}
class SecurityManager { constructor(config = {}) { this.dashPassword = config.dashPassword || process.env.DASH_PASSWORD || ''; this.authEnabled = !!this.dashPassword; this.sessions = new Map(); this.sessionTTL = config.sessionTTL || 3600000; this.rateLimiter = new RateLimiter({ maxTokens: config.rateMaxTokens || 30, refillRate: config.rateRefillRate || 1, refillInterval: config.rateRefillInterval || 1000 }); this.apiRateLimiter = new RateLimiter({ maxTokens: config.apiMaxTokens || 20, refillRate: config.apiRefillRate || 1, refillInterval: config.apiRefillInterval || 1000 }); this.allowedCommands = new Set([ 'stop', 'restart', 'plugins', 'optimize', 'come', 'follow', 'sleep', 'wake', 'chat' ]); this.blockedPatterns = [ /eval\s*\(/i, /exec\s*\(/i, /system\s*\(/i, /\.\.\//i, /\.\.\\/, /<script/i, /javascript:/i, /\$\{.*\}/i, /\$\(/i, /`[^`]*`/i ]; this.suspiciousIps = new Map(); this._log('SECURITY', `تم إنشاء Security Manager (Auth: ${this.authEnabled ? 'ON' : 'OFF'})`); }
_log(tag, msg) { const ts = tsNow(); console.log(`[${ts}] [SECURITY] ${tag} ${msg}`); }
generateSession() { const token = crypto.randomBytes(32).toString('hex'); const expires = Date.now() + this.sessionTTL; this.sessions.set(token, { created: Date.now(), expires }); return token; }
validateSession(token) { if (!token) return false; const session = this.sessions.get(token); if (!session) return false; if (Date.now() > session.expires) { this.sessions.delete(token); return false; } return true; }
// مقارنة آمنة ضد هجمات التوقيت (timing attacks) _safeCompare(a, b) { const ha = crypto.createHash('sha256').update(String(a)).digest(); const hb = crypto.createHash('sha256').update(String(b)).digest(); return crypto.timingSafeEqual(ha, hb); }
login(password, ip = 'unknown') { if (!this.authEnabled) return { success: true, token: this.generateSession() }; // قفل بعد 5 محاولات فاشلة خلال 10 دقائق (حماية من brute-force) const rec = this.suspiciousIps.get(ip) || { fails: 0, until: 0 }; if (rec.until > Date.now()) { this._log('🚫', `IP محظور مؤقتاً: ${ip}`); return { success: false, error: 'محاولات كثيرة — حاول لاحقاً' }; } if (!this._safeCompare(password, this.dashPassword)) { rec.fails++; if (rec.fails >= 5) { rec.until = Date.now() + 600000; rec.fails = 0; } this.suspiciousIps.set(ip, rec); this._log('❌', 'محاولة دخول فاشلة'); return { success: false, error: 'كلمة المرور غير صحيحة' }; } this.suspiciousIps.delete(ip); const token = this.generateSession(); this._log('✅', 'تسجيل دخول ناجح'); return { success: true, token }; }
logout(token) { if (token) this.sessions.delete(token); }
validatePassword(password) { if (!this.authEnabled) return true; return this._safeCompare(password, this.dashPassword); }
checkRateLimit(key) { return this.rateLimiter.tryConsume(key); }
checkApiRateLimit(key) { return this.apiRateLimiter.tryConsume(key); }
isCommandAllowed(cmd) { return this.allowedCommands.has(String(cmd)); }
sanitizeInput(input) { if (typeof input !== 'string') return ''; let clean = input .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '') .replace(/[<>]/g, '') .trim() .slice(0, 500); for (const pattern of this.blockedPatterns) { if (pattern.test(clean)) { this._log('🚫', `محظور: ${clean.slice(0, 50)}`); return ''; } } return clean; }
sanitizeUsername(username) { if (typeof username !== 'string') return ''; return username.replace(/[^a-zA-Z0-9_\-]/g, '').slice(0, 16); }
sanitizeCommand(cmd) { if (typeof cmd !== 'string') return ''; return cmd.replace(/[^a-zA-Z0-9_\-\/ ]/g, '').slice(0, 100); }
isSuspiciousIp(ip) { const data = this.suspiciousIps.get(ip); if (!data) return false; if (Date.now() - data.lastSeen > 3600000) { this.suspiciousIps.delete(ip); return false; } return data.failures >= 10; }
reportSuspiciousActivity(ip, reason) { const data = this.suspiciousIps.get(ip) || { failures: 0, lastSeen: 0 }; data.failures++; data.lastSeen = Date.now(); this.suspiciousIps.set(ip, data); this._log('🚨', `نشاط مشبوه من ${ip}: ${reason} (فشل #${data.failures})`); }
getAntiBotConfig() { return { useRealisticNames: true, avoidBotWords: ['bot', 'robot', 'auto', 'mcbot', 'minecraft'], nameFormats: [ '{adjective}_{noun}{number}', '{noun}{noun}{number}', '{name}_{number}' ], adjectives: ['Cool', 'Swift', 'Brave', 'Dark', 'Wild', 'Red', 'Blue', 'Epic', 'Max', 'Neo'], nouns: ['Miner', 'Crafter', 'Builder', 'Hunter', 'Rider', 'Smith', 'Warden', 'Blade', 'Storm', 'Wolf'], behaviorPatterns: { typingDelay: { min: 35, max: 90 }, thinkPause: { min: 80, max: 300 }, randomPauses: true, humanLikeMistakes: false, emojiFrequency: 0.1 } }; }
generateRealisticName() { const config = this.getAntiBotConfig(); const format = config.nameFormats[Math.floor(Math.random() * config.nameFormats.length)]; const adjective = config.adjectives[Math.floor(Math.random() * config.adjectives.length)]; const noun = config.nouns[Math.floor(Math.random() * config.nouns.length)]; const number = Math.floor(Math.random() * 9000) + 1000; return format .replace('{adjective}', adjective) .replace('{noun}', noun) .replace('{number}', number) .replace('{name}', noun); }
getStatus() { return { authEnabled: this.authEnabled, activeSessions: this.sessions.size, suspiciousIps: this.suspiciousIps.size, rateLimiterBuckets: this.rateLimiter.buckets.size, apiRateLimiterBuckets: this.apiRateLimiter.buckets.size, allowedCommands: [...this.allowedCommands] }; }
destroy() { this.rateLimiter.destroy(); this.apiRateLimiter.destroy(); this.sessions.clear(); this.suspiciousIps.clear(); }}
module.exports = { SecurityManager, RateLimiter };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161'use strict';
/** * ╔══════════════════════════════════════════════════════════════════════════╗ * Server Monitor — v19.0 | مراقبة مستمرة لحالة السيرفر ║ * ╠══════════════════════════════════════════════════════════════════════════╣ * ✅ مراقبة كل 30 ثانية: Status + Players + TPS + Memory ║ * ✅ كشف Deep Sleep وتفعيل Auto-Start ║ * ✅ EventEmitter: statusChange, deepSleep, lowTps, highRam ║ * ✅ Smart Scheduling: جدولة ذكية حسب أوقات الذروة ║ * ✅ Keep-Alive: يمنع HuggingFace من إيقاف الـ Space ║ * ╚══════════════════════════════════════════════════════════════════════════╝ */
const { EventEmitter } = require('events');const { AternosAPI } = require('./aternos-api');const http = require('http');const https = require('https');
const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const randInt = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const tsNow = () => new Date().toISOString().replace('T', ' ').slice(0, 19);
class ServerMonitor extends EventEmitter { constructor(config = {}) { super(); this.api = new AternosAPI(config); this.pollInterval = config.pollInterval || 30000; this.keepAliveInterval = config.keepAliveInterval || 240000; this.hfSpaceUrl = process.env.HF_SPACE_URL || (process.env.SPACE_HOST ? `https://${process.env.SPACE_HOST}` : '') || (process.env.SPACE_ID ? `https://${process.env.SPACE_ID.replace('/', '-')}.hf.space` : ''); this.lastStatus = 'unknown'; this.deepSleepThreshold = config.deepSleepThreshold || 20; this.statusHistory = []; this.maxHistory = 100; this._running = false; this._pollTimer = null; this._keepAliveTimer = null; this._deepSleepStart = null; this._atsRunning = false; this._log('MONITOR', 'تم إنشاء Server Monitor'); }
_log(tag, msg) { const ts = tsNow(); console.log(`[${ts}] [MONITOR] ${tag} ${msg}`); }
start() { if (this._running) return; this._running = true; this._log('🟢', 'بدء المراقبة...'); this._poll(); this._pollTimer = setInterval(() => this._poll(), this.pollInterval); this._keepAliveTimer = setInterval(() => this._keepAlive(), this.keepAliveInterval); this._keepAlive(); }
stop() { this._running = false; if (this._pollTimer) { clearInterval(this._pollTimer); this._pollTimer = null; } if (this._keepAliveTimer) { clearInterval(this._keepAliveTimer); this._keepAliveTimer = null; } this._log('🔴', 'إيقاف المراقبة'); }
async _poll() { if (!this._running) return; try { const status = await this.api.getServerStatus(); const now = Date.now(); this.statusHistory.push({ time: now, status, info: this.api.serverInfo }); if (this.statusHistory.length > this.maxHistory) this.statusHistory.shift(); if (status !== this.lastStatus) { this._log('🔄', `تغيرت الحالة: ${this.lastStatus} → ${status}`); this.emit('statusChange', status, this.api.serverInfo); this.lastStatus = status; } if (status === 'online') { this._deepSleepStart = null; const tps = this.api.serverInfo.tps; if (tps && tps < 14) { this.emit('lowTps', tps); } const ram = this.api.serverInfo.ram; if (ram && ram > 90) { this.emit('highRam', ram); } } else if (status === 'offline' || status === 'unknown') { if (!this._deepSleepStart) { this._deepSleepStart = now; this._log('😴', 'بداية Deep Sleep'); this.emit('deepSleep', 'started'); } else { const elapsed = Math.floor((now - this._deepSleepStart) / 60000); if (elapsed >= this.deepSleepThreshold && !this._atsRunning) { this._log('🔔', `Deep Sleep > ${this.deepSleepThreshold} دقيقة — تفعيل Auto-Start`); this.emit('deepSleep', 'timeout'); this._atsRunning = true; const started = await this.api.autoStart(); if (started) { this._log('✅', 'تم تشغيل السيرفر بنجاح!'); this.emit('autoStart', 'success'); } else { this._log('❌', 'فشل التشغيل التلقائي'); this.emit('autoStart', 'failed'); } this._atsRunning = false; } } } } catch (e) { this._log('❌', `خطأ في المراقبة: ${e.message}`); } }
_keepAlive() { this._internalPing(); if (this.hfSpaceUrl) this._externalPing(); }
_internalPing() { try { const port = process.env.PORT || 7860; http.get(`http://localhost:${port}/healthz`, r => r.resume()) .on('error', () => {}); } catch (_) {} }
_externalPing() { if (!this.hfSpaceUrl) return; try { const target = this.hfSpaceUrl.replace(/\/$/, '') + '/healthz'; const mod = target.startsWith('https') ? https : http; const req = mod.get(target, { headers: { 'User-Agent': 'AternosMonitor-KeepAlive/19.0' }, timeout: 15000 }, r => { r.resume(); this._log('🏓', `HF ping → ${r.statusCode}`); }); req.on('error', () => {}); req.on('timeout', () => req.destroy()); } catch (_) {} }
getStatus() { return { running: this._running, lastStatus: this.lastStatus, serverInfo: this.api.serverInfo, queue: this.api.queuePosition, deepSleepStart: this._deepSleepStart, atsRunning: this._atsRunning, historyCount: this.statusHistory.length, hfSpaceUrl: this.hfSpaceUrl || null }; }}
module.exports = { ServerMonitor };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729'use strict';
/** * ╔══════════════════════════════════════════════════════════════════════════╗ * Server Optimizer — v1.0 | تحسين السيرفر في الأوقات الحرجة والمتوسطة ║ * ╠══════════════════════════════════════════════════════════════════════════╣ * ✅ مراقبة مستمرة: TPS + RAM + Entities + Chunks + Players ║ * ✅ 3 أوضاع: CRITICAL / MODERATE / NORMAL ║ * ✅ تحسين تلقائي: تقليل البوتات + تعطيل Pathfinding + تقليل الرسائل ║ * ✅ تحليل ذكي: أنماط الأداء + توصيات + تنبؤ بالمشاكل ║ * ✅ تنسيق مع البوتات: إرسال أوامر تعطيل/تفعيل حسب الحالة ║ * ✅ تقارير دورية: ملخص أداء كل 5 دقائق ║ * ╚══════════════════════════════════════════════════════════════════════════╝ */
const { EventEmitter } = require('events');
const tsNow = () => new Date().toISOString().replace('T', ' ').slice(0, 19);const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));
// ═══════════════════════════════════════════════════════════════════════════// الحدود والعتبات (Thresholds)// ═══════════════════════════════════════════════════════════════════════════
const THRESHOLDS = { // ─── CRITICAL (أقل من كده السيرفر بيموت) ─────────────────────────────── critical: { tps: 10, // TPS أقل من 10 ram: 92, // RAM أعلى من 92% entities: 200, // Entities أعلى من 200 chunkRate: 50, // Chunks per second أقل من 50 playerPing: 500, // Ping أعلى من 500ms }, // ─── MODERATE (فيه ضغط بس لسه شغال) ─────────────────────────────────── moderate: { tps: 16, // TPS أقل من 16 ram: 80, // RAM أعلى من 80% entities: 120, // Entities أعلى من 120 chunkRate: 100, // Chunks per second أقل من 100 playerPing: 300, // Ping أعلى من 300ms }, // ─── NORMAL (كل حاجة تمام) ───────────────────────────────────────────── normal: { tps: 19, ram: 65, entities: 60, chunkRate: 200, playerPing: 150, }};
// ═══════════════════════════════════════════════════════════════════════════// إعدادات كل وضع// ═══════════════════════════════════════════════════════════════════════════
const MODE_CONFIGS = { // ─── CRITICAL: أقل نشاط ممكن ──────────────────────────────────────────── critical: { label: '🔴 حرج', botActivity: 'minimal', // أقل نشاط pathfinding: false, // تعطيل Pathfinding تماماً chatFrequency: 0, // تعطيل الرسائل taskInterval: 60000, // المهام كل دقيقة maxActiveBots: 2, // أقل عدد بوتات شغالة autoEat: true, // الأكل شغال دايماً autoSleep: true, // النوم شغال combatResponse: 'flee', // الهروب بس miningEnabled: false, // تعطيل التعدين buildingEnabled: false, // تعطيل البناء farmingEnabled: false, // تعطيل الزراعة explorationEnabled: false, // تعطيل الاستكشاف tradingEnabled: false, // تعطيل التجارة socialEnabled: false, // تعطيل التفاعل dailyRoutine: false, // تعطيل الروتين اليومي antiAfk: 'sleep', // بس نوم viewDistance: 'tiny', // أقل مسافة رؤية },
// ─── MODERATE: نشاط متوسط ─────────────────────────────────────────────── moderate: { label: '🟡 متوسط', botActivity: 'reduced', // نشاط مخفف pathfinding: true, // Pathfinding شغال بس بطيء chatFrequency: 0.3, // 30% من الرسائل العادية taskInterval: 30000, // المهام كل 30 ثانية maxActiveBots: 4, // 4 بوتات كحد أقصى autoEat: true, autoSleep: true, combatResponse: 'fight', // قتال عادي miningEnabled: true, buildingEnabled: true, farmingEnabled: true, explorationEnabled: false, // الاستكشاف متوقف tradingEnabled: false, // التجارة متوقفة socialEnabled: true, dailyRoutine: true, antiAfk: 'moderate', // حركة متوسطة viewDistance: 'short', // مسافة رؤية قصيرة },
// ─── NORMAL: كل حاجة شغالة ────────────────────────────────────────────── normal: { label: '🟢 طبيعي', botActivity: 'full', // نشاط كامل pathfinding: true, chatFrequency: 1.0, // كل الرسائل taskInterval: 15000, // المهام كل 15 ثانية maxActiveBots: 10, // كل البوتات autoEat: true, autoSleep: true, combatResponse: 'fight', miningEnabled: true, buildingEnabled: true, farmingEnabled: true, explorationEnabled: true, tradingEnabled: true, socialEnabled: true, dailyRoutine: true, antiAfk: 'full', // حركة كاملة viewDistance: 'normal', // مسافة رؤية عادية }};
// ═══════════════════════════════════════════════════════════════════════════// ServerOptimizer Class// ═══════════════════════════════════════════════════════════════════════════
class ServerOptimizer extends EventEmitter { constructor(config = {}) { super(); this.config = { checkInterval: config.checkInterval || 10000, // فحص كل 10 ثواني reportInterval: config.reportInterval || 300000, // تقرير كل 5 دقائق historySize: config.historySize || 300, // 50 دقيقة من البيانات recoveryDelay: config.recoveryDelay || 60000, // دقيقة قبل الرجوع من CRITICAL autoModeSwitch: config.autoModeSwitch !== false, // تغيير تلقائي للوضع ...config };
// ─── الحالة الحالية ─────────────────────────────────────────────────── this.currentMode = 'normal'; // الوضع الحالي this.previousMode = 'normal'; // الوضع السابق this.modeStartTime = Date.now(); // وقت بدء الوضع الحالي this.modeTransitionPending = null; // تغيير وشيك this.modeTransitionTimer = null; // مؤقت التغيير
// ─── البيانات ───────────────────────────────────────────────────────── this.metrics = { tps: 20, ram: 50, entities: 0, chunks: 0, players: 0, ping: 0, worldTime: 0, uptime: 0, botCount: 0, activeBots: 0, };
this.history = []; this.alerts = []; this.optimizations = []; this.stats = { modeChanges: 0, optimizationsApplied: 0, criticalEvents: 0, moderateEvents: 0, normalEvents: 0, totalChecks: 0, avgTps: 20, avgRam: 50, worstTps: 20, worstRam: 50, };
// ─── البوتات المتصلة ────────────────────────────────────────────────── this.connectedBots = new Map(); // botId → { bot, mode, lastAction }
this._running = false; this._checkTimer = null; this._reportTimer = null;
this._log('OPTIMIZER', 'تم إنشاء Server Optimizer v1.0'); }
_log(tag, msg) { console.log(`[${tsNow()}] [OPTIMIZER] ${tag} ${msg}`); }
// ═══════════════════════════════════════════════════════════════════════════ // بدء/إيقاف التحسين // ═══════════════════════════════════════════════════════════════════════════
start() { if (this._running) return; this._running = true; this._log('🟢', 'بدء مراقبة وتحسين السيرفر...');
this._checkTimer = setInterval(() => this._check(), this.config.checkInterval); this._reportTimer = setInterval(() => this._report(), this.config.reportInterval);
this._check(); this._report(); }
stop() { this._running = false; if (this._checkTimer) { clearInterval(this._checkTimer); this._checkTimer = null; } if (this._reportTimer) { clearInterval(this._reportTimer); this._reportTimer = null; } if (this.modeTransitionTimer) { clearTimeout(this.modeTransitionTimer); this.modeTransitionTimer = null; } this._log('🔴', 'إيقاف Server Optimizer'); }
// ═══════════════════════════════════════════════════════════════════════════ // التحقق الرئيسي (كل 10 ثواني) // ═══════════════════════════════════════════════════════════════════════════
async _check() { if (!this._running) return; this.stats.totalChecks++;
try { // ─── تحليل الحالة ─────────────────────────────────────────────────── const analysis = this._analyzeMetrics(); const newMode = analysis.recommendedMode;
// ─── تحديث الإحصائيات ─────────────────────────────────────────────── this._updateStats();
// ─── حفظ في التاريخ ───────────────────────────────────────────────── this.history.push({ time: Date.now(), mode: this.currentMode, tps: this.metrics.tps, ram: this.metrics.ram, entities: this.metrics.entities, players: this.metrics.players, analysis: analysis.reasons }); if (this.history.length > this.config.historySize) this.history.shift();
// ─── تغيير الوضع إذا لزم ────────────────────────────────────────── if (this.config.autoModeSwitch && newMode !== this.currentMode) { this._requestModeChange(newMode, analysis.reasons); }
// ─── تطبيق التحسينات على البوتات ──────────────────────────────────── this._applyOptimizations();
// ─── إرسال الأحداث ────────────────────────────────────────────────── this.emit('check', { mode: this.currentMode, metrics: { ...this.metrics }, analysis });
} catch (err) { this._log('❌', `خطأ في الفحص: ${err.message}`); } }
// ═══════════════════════════════════════════════════════════════════════════ // تحليل المقاييس وتحديد الوضع // ═══════════════════════════════════════════════════════════════════════════
_analyzeMetrics() { const m = this.metrics; const reasons = []; let score = 0; // 0-100 (0=حرج, 100=ممتاز)
// ─── تحليل TPS ──────────────────────────────────────────────────────── if (m.tps <= THRESHOLDS.critical.tps) { score -= 40; reasons.push(`TPS حرج: ${m.tps}`); } else if (m.tps <= THRESHOLDS.moderate.tps) { score -= 20; reasons.push(`TPS منخفض: ${m.tps}`); } else { score += 20; }
// ─── تحليل RAM ──────────────────��───────────────────────────────────── if (m.ram >= THRESHOLDS.critical.ram) { score -= 30; reasons.push(`RAM حرج: ${m.ram}%`); } else if (m.ram >= THRESHOLDS.moderate.ram) { score -= 15; reasons.push(`RAM مرتفع: ${m.ram}%`); } else { score += 15; }
// ─── تحليل Entities ─────────────────────────────────────────────────── if (m.entities >= THRESHOLDS.critical.entities) { score -= 15; reasons.push(`Entities كتير: ${m.entities}`); } else if (m.entities >= THRESHOLDS.moderate.entities) { score -= 8; reasons.push(`Entities متوسط: ${m.entities}`); } else { score += 10; }
// ─── تحليل اللاعبين ────────────────────────────────────────────────── if (m.players > 10) { score -= 10; reasons.push(`لاعبين كتير: ${m.players}`); } else if (m.players > 5) { score -= 5; } else { score += 5; }
// ─── تحليل البوتات ──────────────────────────────────────────────────── const activeBots = this.connectedBots.size; if (activeBots > 6) { score -= 10; reasons.push(`بوتات كتير شغالة: ${activeBots}`); } else if (activeBots > 3) { score -= 5; } else { score += 5; }
// ─── تحديد الوضع ────────────────────────────────────────────────────── let recommendedMode; if (score <= 20) { recommendedMode = 'critical'; } else if (score <= 55) { recommendedMode = 'moderate'; } else { recommendedMode = 'normal'; }
// ─── تحليل الاتجاه (هل Situation بتتحسن أو بت tệ؟) ────────────────── const trend = this._analyzeTrend();
return { score: Math.max(0, Math.min(100, score)), recommendedMode, reasons, trend, details: { tpsStatus: m.tps >= 19 ? '🟢' : m.tps >= 16 ? '🟡' : '🔴', ramStatus: m.ram <= 65 ? '🟢' : m.ram <= 80 ? '🟡' : '🔴', entityStatus: m.entities <= 60 ? '🟢' : m.entities <= 120 ? '🟡' : '🔴', } }; }
_analyzeTrend() { if (this.history.length < 10) return 'stable'; const recent = this.history.slice(-10); const older = this.history.slice(-20, -10);
if (older.length === 0) return 'stable';
const recentAvgTps = recent.reduce((s, h) => s + h.tps, 0) / recent.length; const olderAvgTps = older.reduce((s, h) => s + h.tps, 0) / older.length;
if (recentAvgTps > olderAvgTps + 2) return 'improving'; if (recentAvgTps < olderAvgTps - 2) return 'worsening'; return 'stable'; }
// ═══════════════════════════════════════════════════════════════════════════ // تغيير الوضع // ═══════════════════════════════════════════════════════════════════════════
_requestModeChange(newMode, reasons) { // ─── CRITICAL: تغيير فوري ────────────────────────────────────────────── if (newMode === 'critical') { this._switchMode(newMode, reasons); return; }
// ─── MODERATE → NORMAL: انتظار 30 ثانية للتأكد ────────────────────────── if (this.currentMode === 'critical' && newMode === 'moderate') { if (this.modeTransitionPending === 'moderate') { // انتظر أكثر return; } this.modeTransitionPending = 'moderate'; this._log('⏳', 'انتظار 30 ثانية للرجوع من CRITICAL...'); this.modeTransitionTimer = setTimeout(() => { this._switchMode('moderate', reasons); this.modeTransitionPending = null; }, 30000); return; }
// ─── MODERATE → NORMAL: انتظار دقيقة ──────────────────────────────────── if (this.currentMode === 'moderate' && newMode === 'normal') { if (this.modeTransitionPending === 'normal') return; this.modeTransitionPending = 'normal'; this._log('⏳', 'انتظار 60 ثانية للرجوع من MODERATE...'); this.modeTransitionTimer = setTimeout(() => { this._switchMode('normal', reasons); this.modeTransitionPending = null; }, 60000); return; }
// ─── أي تغيير تاني: فوري ────────────────────────────────────────────── this._switchMode(newMode, reasons); }
_switchMode(newMode, reasons) { if (this.modeTransitionTimer) { clearTimeout(this.modeTransitionTimer); this.modeTransitionTimer = null; } this.modeTransitionPending = null;
const oldMode = this.currentMode; this.previousMode = oldMode; this.currentMode = newMode; this.modeStartTime = Date.now(); this.stats.modeChanges++;
if (newMode === 'critical') this.stats.criticalEvents++; else if (newMode === 'moderate') this.stats.moderateEvents++; else this.stats.normalEvents++;
const config = MODE_CONFIGS[newMode]; this._log('🔄', `تغيير الوضع: ${MODE_CONFIGS[oldMode].label} → ${config.label}`); this._log('📋', `الأسباب: ${reasons.join(', ')}`);
// ─── إرسال أحداث ────────────────────────────────────────────────────── this.emit('modeChange', { from: oldMode, to: newMode, config, reasons, timestamp: Date.now() });
// ─── إشعار البوتات ──────────────────────────────────────────────────── this._notifyBotsModeChange(newMode, config); }
// ═══════════════════════════════════════════════════════════════════════════ // إدارة البوتات المتصلة // ═══════════════════════════════════════════════════════════════════════════
registerBot(botId, bot) { this.connectedBots.set(botId, { bot, mode: this.currentMode, lastAction: Date.now(), disabled: false, pathfindingEnabled: true, chatEnabled: true, }); this._log('🤖', `بوت مسجل: ${botId} (${this.connectedBots.size} بوت)`); this._applyBotMode(botId); }
unregisterBot(botId) { this.connectedBots.delete(botId); this._log('👋', `بوت انفصل: ${botId} (${this.connectedBots.size} بوت)`); }
_notifyBotsModeChange(newMode, config) { this.connectedBots.forEach((data, botId) => { data.mode = newMode; this._applyBotMode(botId); }); }
_applyBotMode(botId) { const data = this.connectedBots.get(botId); if (!data || !data.bot) return;
const config = MODE_CONFIGS[this.currentMode];
try { // ─── تعطيل/تفعيل Pathfinding ──────────────────────────────────────── data.pathfindingEnabled = config.pathfinding;
// ─── تعطيل/تفعيل الرسائل ──────────────────────────────────────────── data.chatEnabled = config.chatFrequency > 0;
// ─── تقليل نشاط البوت ──────────────────────────────────────────────── if (config.botActivity === 'minimal') { data.bot._optimizerMode = 'minimal'; } else if (config.botActivity === 'reduced') { data.bot._optimizerMode = 'reduced'; } else { data.bot._optimizerMode = 'full'; }
this._log('⚙️', ` Bot ${botId}: وضع ${config.label}`); } catch (err) { this._log('❌', `خطأ في تطبيق الوضع على ${botId}: ${err.message}`); } }
_applyOptimizations() { const config = MODE_CONFIGS[this.currentMode];
this.connectedBots.forEach((data, botId) => { if (!data.bot) return;
try { // ─── في الوضع الحرج: تقليل كل حاجة ──────────────────────────────── if (this.currentMode === 'critical') { // ─── إيقاف أي حركة ────────────────────────────────────────────── if (data.bot.pathfinder && data.pathfindingEnabled) { data.pathfindingEnabled = false; }
// ─── إيقاف التعدين ────────────────────────────────────────────── if (data.bot._mining && config.miningEnabled === false) { data.bot._mining = false; }
// ─── إيقاف البناء ────────────────────────────────────────────── if (data.bot._building && config.buildingEnabled === false) { data.bot._building = false; } }
// ─── في الوضع المتوسط: تقليل النشاط ────────────────────────────── if (this.currentMode === 'moderate') { // ─── تقليل سرعة Pathfinding ───────────────────────────────────── if (data.bot.pathfinder && data.pathfindingEnabled) { data.bot.pathfinder.setTicksPerTick(2); // بطيء } }
// ─── في الوضع الطبيعي: كل حاجة شغالة ────────────────────────────── if (this.currentMode === 'normal') { if (data.bot.pathfinder && !data.pathfindingEnabled) { data.pathfindingEnabled = true; } if (data.bot.pathfinder) { data.bot.pathfinder.setTicksPerTick(1); // عادي } }
} catch (err) { // تجاهل الأخطاء } }); }
// ═══════════════════════════════════════════════════════════════════════════ // تحديث المقاييس (يتم استدعاؤه من внешние أنظمة) // ═══════════════════════════════════════════════════════════════════════════
updateMetrics(newMetrics) { Object.assign(this.metrics, newMetrics); }
updateTps(tps) { this.metrics.tps = tps; }
updateRam(ramPercent) { this.metrics.ram = ramPercent; }
updateEntities(count) { this.metrics.entities = count; }
updatePlayers(count) { this.metrics.players = count; }
// ═══════════════════════════════════════════════════════════════════════════ // تحديث الإحصائيات // ═══════════════════════════════════════════════════════════════════════════
_updateStats() { const m = this.metrics; const n = this.stats.totalChecks;
this.stats.avgTps = ((this.stats.avgTps * (n - 1)) + m.tps) / n; this.stats.avgRam = ((this.stats.avgRam * (n - 1)) + m.ram) / n; this.stats.worstTps = Math.min(this.stats.worstTps, m.tps); this.stats.worstRam = Math.max(this.stats.worstRam, m.ram); }
// ═══════════════════════════════════════════════════════════════════════════ // التقارير الدورية // ═══════════════════════════════════════════════════════════════════════════
_report() { if (!this._running) return;
const m = this.metrics; const config = MODE_CONFIGS[this.currentMode]; const uptime = Date.now() - this.modeStartTime; const uptimeMin = Math.floor(uptime / 60000);
this._log('📊', '═══════════════════════════════════════════════'); this._log('📊', `الوضع الحالي: ${config.label}`); this._log('📊', `TPS: ${m.tps} | RAM: ${m.ram}% | Entities: ${m.entities} | Players: ${m.players}`); this._log('📊', `بوتات متصلة: ${this.connectedBots.size}`); this._log('📊', `مدة الوضع الحالي: ${uptimeMin} دقيقة`); this._log('📊', `تغييرات الوضع: ${this.stats.modeChanges} | أحداث حرجة: ${this.stats.criticalEvents}`); this._log('📊', `TPS المتوسط: ${this.stats.avgTps.toFixed(1)} | Worst: ${this.stats.worstTps}`); this._log('📊', `RAM المتوسط: ${this.stats.avgRam.toFixed(1)}% | Worst: ${this.stats.worstRam}%`); this._log('📊', '═══════════════════════════════════════════════');
this.emit('report', this.getStatus()); }
// ═══════════════════════════════════════════════════════════════════════════ // الحصول على الحالة الكاملة // ═══════════════════════════════════════════════════════════════════════════
getStatus() { const config = MODE_CONFIGS[this.currentMode]; const uptime = Date.now() - this.modeStartTime;
return { running: this._running, currentMode: this.currentMode, modeLabel: config.label, previousMode: this.previousMode, modeUptime: uptime, modeUptimeMin: Math.floor(uptime / 60000), metrics: { ...this.metrics }, config: { ...config }, stats: { ...this.stats }, connectedBots: this.connectedBots.size, historySize: this.history.length, analysis: this._analyzeMetrics(), recommendations: this._getRecommendations(), }; }
// ═══════════════════════════════════════════════════════════════════════════ // التوصيات الذكية // ═══════════════════════════════════════════════════════════════════════════
_getRecommendations() { const recs = []; const m = this.metrics;
if (m.tps < 14) { recs.push({ priority: 'high', type: 'tps', message: 'TPS منخفض جداً — قلل عدد البوتات أو عطّل بعض الميزات', action: 'reduce_bots' }); }
if (m.ram > 85) { recs.push({ priority: 'high', type: 'ram', message: 'RAM عالي جداً — شغّل GC يدوياً أو قلل الكاش', action: 'force_gc' }); }
if (m.entities > 150) { recs.push({ priority: 'medium', type: 'entities', message: 'عدد Entities كبير — قلل مسافة الرؤية أو عطّل بعض الميزات', action: 'reduce_view' }); }
if (this.connectedBots.size > 5) { recs.push({ priority: 'medium', type: 'bots', message: `عدد البوتات كبير (${this.connectedBots.size}) — قلل العدد`, action: 'reduce_bots' }); }
if (this.stats.worstTps < 8) { recs.push({ priority: 'low', type: 'history', message: `وصل TPS لـ ${this.stats.worstTps} قبل كده — راقب الأسباب`, action: 'monitor' }); }
return recs; }
// ═══════════════════════════════════════════════════════════════════════════ // التحكم اليدوي // ═══════════════════════════════════════════════════════════════════════════
setMode(mode) { if (!MODE_CONFIGS[mode]) { this._log('❌', `وضع غير صحيح: ${mode}`); return false; } this._switchMode(mode, ['manual_override']); this._log(' manual', `تم تغيير الوضع يدوياً إلى: ${MODE_CONFIGS[mode].label}`); return true; }
forceOptimization() { this._log('🔧', 'تحسين إجباري...'); this._applyOptimizations(); this.stats.optimizationsApplied++; return true; }
getModeConfig(mode) { return MODE_CONFIGS[mode] ? { ...MODE_CONFIGS[mode] } : null; }
getHistory(minutes = 30) { const cutoff = Date.now() - (minutes * 60000); return this.history.filter(h => h.time >= cutoff); }
destroy() { this.stop(); this.connectedBots.clear(); this.history = []; this.alerts = []; this.optimizations = []; this.removeAllListeners(); }}
module.exports = { ServerOptimizer, THRESHOLDS, MODE_CONFIGS };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191'use strict';/** * Sleeping System — نظام النوم والراحة * ينام بالليل، يدور على سرير، يستيقظ بالصبح */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const chance = pct => Math.random() * 100 < pct;
const BED_BLOCKS = [ 'white_bed','orange_bed','magenta_bed','light_blue_bed', 'yellow_bed','lime_bed','pink_bed','gray_bed', 'light_gray_bed','cyan_bed','purple_bed','blue_bed', 'brown_bed','green_bed','red_bed','black_bed',];
class SleepingSystem extends EventEmitter { constructor(bot, config = {}) { super(); this.bot = bot; this.config = { nightCheckInterval: 5000, sleepHour: 13000, wakeHour: 1000, ...config, }; this._active = false; this._timers = []; this._sleeping = false; this._slept = 0; this._lastSleep = null; this._log('INIT', 'نظام النوم جاهز'); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [SLEEP] ${tag} ${msg}`); }
start() { if (this._active) return; this._active = true; this._log('START', 'بدء نظام النوم');
this._addTimer(() => this._checkTime(), this.config.nightCheckInterval); }
stop() { this._active = false; this._sleeping = false; this._timers.forEach(t => { try { clearInterval(t); clearTimeout(t); } catch(_) {} }); this._timers = []; this._log('STOP', 'إيقاف نظام النوم'); }
_addTimer(fn, interval) { const t = setInterval(() => { if (this._active) fn(); }, interval); this._timers.push(t); }
// ═══ فحص الوقت ═══ _checkTime() { if (!this.bot?.entity || this._sleeping) return; const time = this.bot.time?.age; if (time === undefined) return;
const dayTime = time % 24000; const isNight = dayTime > this.config.sleepHour || dayTime < this.config.wakeHour;
if (isNight && !this._sleeping) { this._log('🌙', 'الليل — يدور على سرير'); this._trySleep(); } }
// ═══ محاولة النوم ═══ async _trySleep() { if (this._sleeping || !this.bot?.entity) return;
// دور على سرير قريب const bed = this._findBed(); if (!bed) { this._log('⚠️', 'لا سرير متاح — ينام على الأرض'); this._sleepOnGround(); return; }
try { // امشي للسرير await this._walkTo(bed.position);
// نام await this.bot.sleep(bed); this._sleeping = true; this._slept++; this._lastSleep = Date.now(); this._log('😴', `نام (إجمالي: ${this._slept})`); this.emit('sleeping');
// استنى لحد ما الصبح await this._waitForMorning(); } catch(e) { this._log('❌', `ما قدر ينام: ${e.message}`); this._sleepOnGround(); } }
// ═══ دور على سرير ═══ _findBed() { if (!this.bot) return null; const bedBlock = this.bot.findBlock({ matching: (block) => BED_BLOCKS.includes(block.name), maxDistance: 16, count: 1, }); return bedBlock; }
// ═══ نوم على الأرض ═══ _sleepOnGround() { if (!this.bot?.entity) return; this._sleeping = true; this._slept++; this._lastSleep = Date.now(); this._log('😴', 'نام على الأرض'); this.emit('sleeping');
// نام لمدة 7 ثواني (بديل للنوم الحقيقي) setTimeout(() => { this._sleeping = false; this._log('☀️', 'استيقظ'); this.emit('wakeup'); }, 7000); }
// ═══ انتظار الصبح ═══ async _waitForMorning() { while (this._active && this._sleeping && this.bot?.entity) { const time = this.bot.time?.age; if (time === undefined) break; const dayTime = time % 24000; if (dayTime >= this.config.wakeHour && dayTime < this.config.sleepHour) { this._sleeping = false; this._log('☀️', 'استيقظ'); this.emit('wakeup'); break; } await sleep(1000); } }
// ═══ استيقظ ═══ async wakeUp() { if (!this._sleeping || !this.bot) return; try { await this.bot.wakeUp(); this._sleeping = false; this._log('☀️', 'استيقظ يدوياً'); this.emit('wakeup'); } catch(_) {} }
async _walkTo(position) { if (!this.bot?.entity) return; const yaw = Math.atan2( position.z - this.bot.entity.position.z, position.x - this.bot.entity.position.x ); this.bot.look(yaw, 0, false); this.bot.setControlState('forward', true); await sleep(rand(300, 800)); this.bot.setControlState('forward', false); }
getStats() { return { slept: this._slept, lastSleep: this._lastSleep ? new Date(this._lastSleep).toISOString() : null, sleeping: this._sleeping, active: this._active, }; }
destroy() { this.stop(); this.removeAllListeners(); }}
module.exports = { SleepingSystem, BED_BLOCKS };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240'use strict';/** * Social System — نظام التواصل الاجتماعي * يرد على الرسائل، يتكلم مع الصحاب، يرحّب بالجديد */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const chance = pct => Math.random() * 100 < pct;const pick = arr => arr[Math.floor(Math.random() * arr.length)];
const GREETINGS = [ 'هلا والله','أهلا','مرحبا','السلام عليكم','يا هلا','صباح الخير','مساء الخير', 'هاي','هلو','أهلاً وسهلاً','نورتونا','حللت',];
const CHAT_RESPONSES = [ 'ايه رأيكم في السيرفر؟','السيرفر تحفة والله','نبي نبني حاجة حلوة', 'مين يبي يحفر معاي؟','يلا نروح نستكشف','الجو حلو اليوم', 'شسالفة؟','ههههه','تمام','أكيد','لا والله','إن شاء الله', 'يلا نلعب','نبي سيف حلو','معاي فضة','منورين',];
const QUESTIONS = [ 'وين أنتم؟','شنو تسوي؟','تبي تحفر معاي؟','عندكم أكل؟', 'وش أسمك؟','من أنت؟','تبي نبني؟','في كهف قريب؟',];
const COMPLIMENTS = [ 'محلو','شغلك حلو','ما شاء الله','حلو','تمام','أحسنت',];
const JOKE_SETUPS = [ 'ليش الـ Creeper يقول مرحبا؟', 'وش يقول الـ Zombie لما يشوف لاعب جديد؟', 'ليش الـ Skeleton ما يلعب كرة؟',];
const JOKE_PUNCHLINES = [ 'لأنه خايف ينفجر! 😂', 'يقول: "أنت جديد هنا؟ تعال نتمشى" 💀', 'لأنه ما عنده عضلات! 🏀',];
class SocialSystem extends EventEmitter { constructor(bot, config = {}) { super(); this.bot = bot; this.config = { chatInterval: 15000, greetOnJoin: true, respondToChat: true, randomChat: true, ...config, }; this._active = false; this._timers = []; this._chatCooldown = 0; this._messagesSent = 0; this._greetings = []; this._knownPlayers = new Set(); this._chatLog = []; this._log('INIT', 'نظام التواصل الاجتماعي جاهز'); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [SOCIAL] ${tag} ${msg}`); }
start() { if (this._active) return; this._active = true; this._log('START', 'بدء نظام التواصل');
// استمع للرسائل this.bot.on('messagestr', (msg) => this._onChat(msg));
// شات عشوائي if (this.config.randomChat) { this._addTimer(() => this._randomChat(), this.config.chatInterval); }
// ترحيب باللاعبين الجدد if (this.config.greetOnJoin) { this.bot.on('playerJoined', (player) => this._onPlayerJoin(player)); }
// مراقبة اللاعبين القريبين this._addTimer(() => this._scanPlayers(), 10000); }
stop() { this._active = false; this._timers.forEach(t => { try { clearInterval(t); clearTimeout(t); } catch(_) {} }); this._timers = []; this._log('STOP', 'إيقاف نظام التواصل'); }
_addTimer(fn, interval) { const t = setInterval(() => { if (this._active) fn(); }, interval); this._timers.push(t); }
// ═══ استقبال رسالة ═══ _onChat(msg) { if (!this._active) return; const cleaned = msg.toString().replace(/<[^>]+>/g, '').trim(); if (!cleaned || cleaned.length < 2) return;
// سجّل الرسالة this._chatLog.push({ text: cleaned, time: Date.now() }); if (this._chatLog.length > 100) this._chatLog.shift();
// لو الرسالة موجهة للبوت (اسمه فيها) const username = this.bot.username?.toLowerCase() || ''; if (cleaned.toLowerCase().includes(username)) { this._respondToDirect(cleaned); } }
// ═══ رد على رسالة مباشرة ═══ async _respondToDirect(msg) { if (Date.now() < this._chatCooldown) return; this._chatCooldown = Date.now() + rand(2000, 5000);
const responses = [ pick(GREETINGS), pick(CHAT_RESPONSES), pick(COMPLIMENTS), 'هلا! 😊', 'أهلاً فيك', pick(QUESTIONS), ];
const reply = pick(responses); await this._sendChat(reply); }
// ═══ ترحيب بلاعب جديد ═══ async _onPlayerJoin(player) { if (!this._active || !player?.username) return; if (player.username === this.bot.username) return;
if (!this._knownPlayers.has(player.username)) { this._knownPlayers.add(player.username); await sleep(rand(2000, 6000)); const safeName = player.username.replace(/[^\x20-\x7E\u0600-\u06FF]/g, '').slice(0, 16); await this._sendChat(`${pick(GREETINGS)} يا ${safeName}! 👋`); this._log('👋', `رحّب بـ ${player.username}`); this.emit('greeted', player.username); } }
// ═══ شات عشوائي ═══ async _randomChat() { if (!this._active) return; if (Date.now() < this._chatCooldown) return;
// فحص لو فيه لاعبين قريبين const nearbyPlayers = this._getNearbyPlayers(); if (nearbyPlayers.length === 0) return;
if (chance(25)) { await this._sendChat(pick(QUESTIONS)); } else if (chance(15)) { await this._sendChat(pick(JOKE_SETUPS)); await sleep(rand(3000, 6000)); await this._sendChat(pick(JOKE_PUNCHLINES)); } else if (chance(40)) { await this._sendChat(pick(CHAT_RESPONSES)); } }
// ═══ فحص اللاعبين القريبين ═══ _scanPlayers() { if (!this.bot?.entity) return; const players = this._getNearbyPlayers(); for (const p of players) { this._knownPlayers.add(p.username); } }
_getNearbyPlayers() { if (!this.bot?.entity) return []; return Object.values(this.bot.players || {}) .filter(p => p.username !== this.bot.username && p.entity && p.entity.position?.distanceTo(this.bot.entity.position) < 16); }
// ═══ إرسال رسالة ═══ async _sendChat(msg) { if (!this.bot) return; try { const safe = msg.replace(/[^\x20-\x7E\u0600-\u06FF ]/g, '').slice(0, 100); this.bot.chat(safe); this._messagesSent++; this._chatCooldown = Date.now() + rand(3000, 8000); this._log('💬', `قال: ${safe}`); this.emit('chat', safe); } catch(_) {} }
// ═══ رد على أمر من لاعب ═══ async respondToCommand(sender, command) { if (!this._active) return; const cmd = command.toLowerCase().trim();
if (cmd === 'hi' || cmd === 'hello' || cmd === 'هلا') { await this._sendChat(`${pick(GREETINGS)} ${sender}!`); } else if (cmd.includes('follow') || cmd.includes('اتبعني')) { await this._sendChat('يلا! 👣'); this.emit('follow', sender); } else if (cmd.includes('come') || cmd.includes('تعال')) { await this._sendChat('جاي! 🏃'); this.emit('come', sender); } else if (cmd.includes('stop') || cmd.includes('وقف')) { await this._sendChat('تمام ✋'); this.emit('stop', sender); } else { await this._sendChat(pick(CHAT_RESPONSES)); } }
getStats() { return { messagesSent: this._messagesSent, knownPlayers: this._knownPlayers.size, chatLog: this._chatLog.length, active: this._active, }; }
destroy() { this.stop(); this.removeAllListeners(); }}
module.exports = { SocialSystem, GREETINGS, CHAT_RESPONSES };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194'use strict';/** * Survival System — نظام البقاء * ياكل لو جوعان، يشرب، يرتاح، يتجنب الخطر */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const chance = pct => Math.random() * 100 < pct;
const FOOD_ITEMS = [ 'bread','cooked_beef','cooked_porkchop','cooked_chicken','cooked_mutton', 'cooked_rabbit','cooked_cod','cooked_salmon','steak','baked_potato', 'pumpkin_pie','mushroom_stew','beetroot_soup','rabbit_stew', 'apple','golden_apple','sweet_berries','glow_berries','chorus_fruit', 'dried_kelp','cake','cookie','melon_slice',];
const DANGER_BLOCKS = new Set([ 'lava','flowing_lava','fire','soul_fire','cactus','magma_block', 'sweet_berry_bush','wither_rose','powder_snow',]);
class SurvivalSystem extends EventEmitter { constructor(bot, config = {}) { super(); this.bot = bot; this.config = { hungerCheckInterval: 3000, healthCheckInterval: 1000, safeFallHeight: 4, ...config, }; this._active = false; this._timers = []; this._eating = false; this._lastFood = 0; this._foodEaten = 0; this._log('INIT', 'نظام البقاء جاهز'); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [SURVIVAL] ${tag} ${msg}`); }
start() { if (this._active) return; this._active = true; this._log('START', 'بدء نظام البقاء');
this._addTimer(() => this._checkHunger(), this.config.hungerCheckInterval); this._addTimer(() => this._checkHealth(), this.config.healthCheckInterval); this._addTimer(() => this._avoidDanger(), 1500); this._addTimer(() => this._checkFall(), 2000); }
stop() { this._active = false; this._timers.forEach(t => { try { clearInterval(t); clearTimeout(t); } catch(_) {} }); this._timers = []; this._log('STOP', 'إيقاف نظام البقاء'); }
_addTimer(fn, interval) { const t = setInterval(() => { if (this._active) fn(); }, interval); this._timers.push(t); }
// ═══ فحص الجوع ═══ _checkHunger() { if (!this.bot?.entity || this._eating) return; const food = this.bot.food; if (food !== undefined && food < 14) { this._log('🍖', `جوع (food: ${food}) — يأكل`); this._eat(); } }
// ═══ فحص الصحة ═══ _checkHealth() { if (!this.bot?.entity) return; const health = this.bot.health; if (health !== undefined && health < 6) { this._log('❤️', `صحة قليلة (${health}) — يأكل`); this._eat(); } }
// ═══ أكل ═══ async _eat() { if (this._eating || !this.bot) return; this._eating = true; try { const foodItem = this.bot.inventory.items().find(i => FOOD_ITEMS.includes(i.name)); if (!foodItem) { this._log('⚠️', 'لا طعام متاح!'); this.emit('noFood'); this._eating = false; return; }
await this.bot.equip(foodItem, 'hand'); await this.bot.consume(); this._foodEaten++; this._lastFood = Date.now(); this._log('✅', `أكل ${foodItem.name} (إجمالي: ${this._foodEaten})`); this.emit('ate', foodItem.name); } catch(e) { this._log('❌', `خطأ في الأكل: ${e.message}`); } finally { this._eating = false; } }
// ═══ تجنب الخطر ═══ _avoidDanger() { if (!this.bot?.entity) return; const pos = this.bot.entity.position; const blockBelow = this.bot.blockAt(pos.offset(0, -1, 0)); if (!blockBelow) return;
if (DANGER_BLOCKS.has(blockBelow.name)) { this._log('⚠️', `خطر! ${blockBelow.name} تحتينا — نهرب`); this.emit('danger', blockBelow.name); // اهرب من الخطر const yaw = Math.random() * Math.PI * 2; this.bot.look(yaw, 0, false); this.bot.setControlState('forward', true); this.bot.setControlState('sprint', true); setTimeout(() => { try { this.bot.setControlState('forward', false); this.bot.setControlState('sprint', false); } catch(_) {} }, rand(1000, 2000)); } }
// ═══ تجنب السقوط ═══ _checkFall() { if (!this.bot?.entity) return; const pos = this.bot.entity.position; // فحص لو قدامنا حفرة const forward = this.bot.blockAt(pos.offset(0, -3, 0)); if (forward?.name === 'air') { this._log('⚠️', 'حفرة قدامنا — نتفاداها'); this.bot.setControlState('back', true); setTimeout(() => { try { this.bot.setControlState('back', false); } catch(_) {} }, 500); } }
// ═══ أكل من الصندوق لو مش متاح ═══ async _searchFoodInChests() { if (!this.bot) return null; const chestBlock = this.bot.findBlock({ matching: this.bot.registry?.blocksByName?.chest?.id, maxDistance: 16, count: 1, }); if (!chestBlock) return null;
try { await this.bot.openChest(chestBlock); await sleep(500); const chestItems = this.bot.currentWindow?.items() || []; const food = chestItems.find(i => FOOD_ITEMS.includes(i.name)); if (food) { await this.bot.clickWindow(food.slot, 1, 0); await sleep(300); this.bot.closeWindow(); return food; } this.bot.closeWindow(); } catch(_) {} return null; }
getStats() { return { foodEaten: this._foodEaten, lastFood: this._lastFood ? new Date(this._lastFood).toISOString() : null, active: this._active, hunger: this.bot?.food, health: this.bot?.health, }; }
destroy() { this.stop(); this.removeAllListeners(); }}
module.exports = { SurvivalSystem, FOOD_ITEMS };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199'use strict';/** * Trading System — نظام التجارة * يتبادل الأغراض مع اللاعبين، يعرض صرف، يتفاوض */const { EventEmitter } = require('events');const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;const chance = pct => Math.random() * 100 < pct;const pick = arr => arr[Math.floor(Math.random() * arr.length)];
const TRADE_OFFERS = [ { give: 'cobblestone', want: 'diamond', ratio: 64, desc: '64 حجر ↔ 1 ماس' }, { give: 'iron_ingot', want: 'diamond', ratio: 8, desc: '8 حديد ↔ 1 ماس' }, { give: 'coal', want: 'iron_ingot', ratio: 8, desc: '8 فحم ↔ 1 حديد' }, { give: 'bread', want: 'iron_ingot', ratio: 4, desc: '4 خبز ↔ 1 حديد' }, { give: 'oak_planks', want: 'cobblestone', ratio: 4, desc: '4 خشب ↔ 4 حجر' },];
const TRADE_MESSAGES = [ 'مين يبي يتبادل معاي؟', 'عنددي موارد أبيعها', 'أي حد يبي حديد؟', 'أنا أبيع خشب رخيص', 'مين يبي خبز؟', 'أعرض مواردي للبيع', 'تبي نتبادل؟',];
const TRADE_RESPONSES = { accept: ['تمام! يلا نتبادل','أكيد','موافق','يلا','ما عندي مانع'], reject: ['لا شكراً','مش مهتم','بعدين','ما أبي'], counter: ['لا بس أبي أكثر','غالي علي','أنا أverse لك أكثر','ما تقبل؟'],};
class TradingSystem extends EventEmitter { constructor(bot, config = {}) { super(); this.bot = bot; this.config = { offerInterval: 25000, maxTradeDistance: 4, ...config, }; this._active = false; this._timers = []; this._trading = false; this._tradesCompleted = 0; this._tradeOffers = 0; this._log('INIT', 'نظام التجارة جاهز'); }
_log(tag, msg) { const ts = new Date().toISOString().replace('T', ' ').slice(0, 19); console.log(`[${ts}] [TRADE] ${tag} ${msg}`); }
start() { if (this._active) return; this._active = true; this._log('START', 'بدء نظام التجارة');
// عرض تبادل عشوائي this._addTimer(() => this._offerTrade(), this.config.offerInterval);
// استمع لرسائل التجارة this.bot.on('messagestr', (msg) => this._onTradeMessage(msg)); }
stop() { this._active = false; this._trading = false; this._timers.forEach(t => { try { clearInterval(t); clearTimeout(t); } catch(_) {} }); this._timers = []; this._log('STOP', 'إيقاف نظام التجارة'); }
_addTimer(fn, interval) { const t = setInterval(() => { if (this._active) fn(); }, interval); this._timers.push(t); }
// ═══ عرض تبادل ═══ async _offerTrade() { if (this._trading || !this.bot?.entity) return; if (chance(60)) return;
const nearbyPlayers = this._getNearbyPlayers(); if (nearbyPlayers.length === 0) return;
const offer = pick(TRADE_OFFERS); const giveItem = this.bot.inventory.items().find(i => i.name === offer.give); if (!giveItem || giveItem.count < offer.ratio) return;
await this._sendChat(pick(TRADE_MESSAGES)); this._tradeOffers++; this._log('💰', `عرض: ${offer.desc}`); this.emit('offered', offer); }
// ═══ رد على رسالة ═══ async _onTradeMessage(msg) { if (!this._active) return; const cleaned = msg.toString().replace(/<[^>]+>/g, '').trim().toLowerCase();
if (cleaned.includes('تبادل') || cleaned.includes('swap') || cleaned.includes('trade')) { if (chance(50)) { await this._sendChat(pick(TRADE_RESPONSES.accept)); this._trading = true; await sleep(rand(1000, 2000)); await this._executeTrade(); } else { await this._sendChat(pick(TRADE_RESPONSES.reject)); } } }
// ═══ تنفيذ التبادل ═══ async _executeTrade() { if (!this.bot?.entity) return; try { // دور على لاعب قريب const player = this._getNearbyPlayers()[0]; if (!player) return;
// امشي للاعب await this._walkTo(player.entity.position);
// فتح التبادل await sleep(rand(500, 1000)); // mineflayer ما عنده تبادل مباشر، بس نقدر نرمي أغراض const offer = pick(TRADE_OFFERS); const item = this.bot.inventory.items().find(i => i.name === offer.give); if (item) { await this.bot.tossStack(item); this._tradesCompleted++; this._log('✅', `تبادل: ${item.name}`); this.emit('traded', item.name); } } catch(_) {} finally { this._trading = false; } }
// ═══ رمي أغراض ═══ async tossItem(itemName, count) { if (!this.bot) return; const item = this.bot.inventory.items().find(i => i.name === itemName); if (item) { await this.bot.tossStack(item); this._log('扔', `رمى ${itemName}`); } }
async _walkTo(position) { if (!this.bot?.entity) return; const yaw = Math.atan2( position.z - this.bot.entity.position.z, position.x - this.bot.entity.position.x ); this.bot.look(yaw, 0, false); this.bot.setControlState('forward', true); await sleep(rand(200, 500)); this.bot.setControlState('forward', false); }
async _sendChat(msg) { if (!this.bot) return; try { const safe = msg.replace(/[^\x20-\x7E\u0600-\u06FF ]/g, '').slice(0, 100); this.bot.chat(safe); this._log('💬', `قال: ${safe}`); } catch(_) {} }
_getNearbyPlayers() { if (!this.bot?.entity) return []; return Object.values(this.bot.players || {}) .filter(p => p.username !== this.bot.username && p.entity && p.entity.position?.distanceTo(this.bot.entity.position) < 16); }
getStats() { return { tradesCompleted: this._tradesCompleted, tradeOffers: this._tradeOffers, trading: this._trading, active: this._active, }; }
destroy() { this.stop(); this.removeAllListeners(); }}
module.exports = { TradingSystem, TRADE_OFFERS };DockerfileAdded+58
Download.mcpackAdded
HF-DEPLOY.mdAdded+132
README.md+124-9
ai-engine.jsAdded+657
aternos-api.jsAdded+370
aternos-starter.jsAdded+238
authme.jsAdded+235
auto-recovery.jsAdded+217
bot-team.jsAdded
building.jsAdded+240
combat-bow.jsAdded+187
combat-defense.jsAdded+170
combat-dodge.jsAdded+191
combat-sword.jsAdded+176
combat-team.jsAdded+238
combat.jsAdded+282
connection-manager.jsAdded+150
crafting.jsAdded+193
daily-routine.jsAdded+328
exploration.jsAdded+214
farming.jsAdded+213
features-config.jsonAdded+148
features-engine.jsAdded+279
human-behavior.jsAdded
job-system.jsAdded+1474
mining.jsAdded+234
multi-server.jsAdded+242
package.jsonAdded+30
performance-optimizer.jsAdded+218
qa-system.jsAdded+238
security.jsAdded+265
server-monitor.jsAdded+161
server-optimizer.jsAdded+729
sleeping.jsAdded+191
social.jsAdded+240
survival.jsAdded+194
trading.jsAdded+199