Suvarii commited on
Commit
0cb39e8
·
verified ·
1 Parent(s): 511f2af

Update bot.js

Browse files
Files changed (1) hide show
  1. bot.js +503 -177
bot.js CHANGED
@@ -44,19 +44,13 @@ const CIFTCI_SELL_ALL_SLOT = 45;
44
  const CIFTCI_COMMAND = "/çiftçi menü";
45
  const CIFTCI_WINDOW_TIMEOUT_MS = 6000;
46
  const CIFTCI_LORE_FALLBACK_KEYWORDS = ["hepsini sat"];
47
- // Menü açıldıktan sonra sunucunun içeriği (lore/slot) tam yerleştirmesi için
48
- // beklenecek süre, tıklamadan önce. Ardından art arda birkaç kez tıklanır.
49
  const CIFTCI_CLICK_DELAY_AFTER_OPEN_MS = 1000;
50
  const CIFTCI_CLICK_REPEAT_COUNT = 3;
51
  const CIFTCI_CLICK_REPEAT_GAP_MS = 350;
52
 
53
- // --- KAZICI PERİYODİK DÖNGÜ AYARLARI (bağımsız, 5 dakikada bir) ---
54
- const KAZICI_CYCLE_INTERVAL_MS = 5 * 60 * 1000; // 5 dakika
55
 
56
- // --- ÇİFTÇİ PERİYODİK DÖNGÜ AYARLARI (bağımsız, 1 dakikada bir) ---
57
- const CIFTCI_CYCLE_INTERVAL_MS = 60 * 1000; // 1 dakika
58
-
59
- // --- ÇİFTÇİ FİLTRE / STORAGE INFO TARAMA AYARLARI ---
60
  const CIFTCI_FILTER_MODES = [
61
  "Standart",
62
  "Favoriler",
@@ -65,14 +59,27 @@ const CIFTCI_FILTER_MODES = [
65
  "Satışı açık olanlar",
66
  "Toplaması açık olanlar"
67
  ];
68
- const CIFTCI_TARGET_FILTER_INDEX = 3; // "Jeneratör materyalleri"
69
  const CIFTCI_ACTIVE_FILTER_COLOR = "#FCF988";
70
  const CIFTCI_FILTER_ITEM_NAME_KEYWORD = "Filtre";
71
- const CIFTCI_FILTER_STEP_WAIT_MS = 1000; // her tık sonrası ilk bekleme
72
- const CIFTCI_FILTER_RETRY_WAIT_MS = 1000; // item gözükmezse ek bekleme
73
- const CIFTCI_FILTER_MAX_RETRIES = 10; // güvenlik limiti
74
- const STORAGE_SCAN_INTERVAL_MS = 15 * 60 * 1000; // 15 dakika
75
- const STORAGE_TRACKED_ITEMS = ["diamond", "emerald", "iron_block"]; // internal name eşleşmesi
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
  let storageInfoCache = {
78
  diamond: null,
@@ -82,23 +89,18 @@ let storageInfoCache = {
82
  };
83
  let storageScanIntervalHandle = null;
84
 
85
- // Çiftçi penceresinin şu an hangi amaçla açık olduğunu tutan bayrak.
86
- // "sell" -> hepsini-sat akışı, "scan" -> storage bilgisi tarama akışı.
87
  let ciftciWindowPurpose = "sell";
88
 
89
- // --- KAZICI FAILOVER (YEDEK HESAP) AYARLARI ---
90
- const STALL_CHECK_INTERVAL_MS = 15 * 1000; // pose kontrolü ne sıklıkla yapılsın
91
- const STALL_TIMEOUT_MS = 60 * 1000; // bu süre hareketsiz kalırsa "durdu" say
92
- const FAILOVER_HOME_ARRIVAL_DELAY_MS = 4000; // yedek hesapta /is go sonrası varış beklemesi
93
  const FAILOVER_LOGIN_DELAY_MS = 2500;
94
  const FAILOVER_SKYBLOCK_DELAY_MS = 7500;
95
  const FAILOVER_ISGO_DELAY_MS = 12500;
96
- const FAILOVER_RECHECK_INTERVAL_MS = 20 * 1000; // yedek hesapta minyonları tekrar kontrol aralığı
97
- const FAILOVER_MAX_WAIT_MS = 60 * 60 * 1000; // güvenlik: 1 saatte hâlâ aktifleşmediyse pes et, ana hesaba dön
98
- const FAILOVER_SPAWN_TIMEOUT_MS = 30 * 1000; // yedek hesap 30 sn içinde spawn olmazsa vazgeç
99
 
100
- // İzlenen (KAZICI_NAMES ile eşleşmeyen, başka hesaptan konan) kazıcı minyonların
101
- // skin texture hash'i. Bu skin + elde iron_pickaxe olan armor stand'ler izlenir.
102
  const WATCHED_KAZICI_SKIN_HASHES = new Set([
103
  "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNDQ4ODcwY2E3N2FhNjk5ZDAxNzA5M2I4Mjc3OWQwYTU5OGRjNGYzZjQ5ZDM1MTUzMmFlNGQ5NjMzZGNjMmE1YSJ9fX0=",
104
  ]);
@@ -113,7 +115,6 @@ let messagesTimeout = null;
113
  let isListeningChat = false;
114
  const ansiToHtmlConvert = new (require('ansi-to-html'))({ newline: true });
115
 
116
- // --- GÜVENLİ BAĞLANTI DEĞİŞKENLERİ ---
117
  let isConnecting = false;
118
  let isDestroying = false;
119
  let reconnectTimeout = null;
@@ -122,42 +123,37 @@ let currentStream = null;
122
  let currentSocket = null;
123
  let windowOpenResolvers = [];
124
 
125
- // --- PANEL METRİKLERİ ---
126
  let botUptimeStart = null;
127
  let lastFullFeedTimeStr = "Henüz besleme yapılmadı";
128
  let lastCheckTimeStr = "Henüz kontrol yapılmadı";
129
  let nextScheduledCheckTimeStr = "Botun spawn olması bekleniyor...";
130
 
131
- // --- KAZICI PANEL METRİKLERİ (bağımsız) ---
132
  let lastKaziciCheckTimeStr = "Henüz kazıcı kontrolü yapılmadı";
133
  let nextKaziciTimeStr = "Botun spawn olması bekleniyor...";
134
  let nextKaziciAtMs = null;
135
 
136
- // --- ÇİFTÇİ PANEL METRİKLERİ (bağımsız) ---
137
  let lastCiftciSellTimeStr = "Henüz çiftçi satışı yapılmadı";
138
  let nextCiftciTimeStr = "Botun spawn olması bekleniyor...";
139
  let nextCiftciAtMs = null;
140
 
141
- // --- ÇİFTÇİ/KAZICI PERİYODİK DÖNGÜ KONTROLÜ ---
142
- let lastCheckAtMs = null; // Besleyici için (panel bilgisi amaçlı, artık kazıcı/çiftçiyi etkilemiyor)
143
- let nextScheduledCheckAtMs = null; // Besleyici için
144
- let kaziciIntervalHandle = null; // Kazıcı bağımsız döngü zamanlayıcısı (5 dk)
145
- let ciftciIntervalHandle = null; // Çiftçi bağımsız döngü zamanlayıcısı (1 dk)
146
- let isMainCycleRunning = false; // Besleyici (goToIsland->besle) ana döngüsü sürüyor mu
 
147
 
148
- // --- KAZICI FAILOVER (YEDEK HESAP) DURUM DEĞİŞKENLERİ ---
149
- let poseTracker = new Map(); // entityId -> { poseKey, lastChangeAt, uuid }
150
  let stallCheckIntervalHandle = null;
151
- let failoverModeActive = false; // true iken ana botun periyodik işlemleri fiilen durur (bot=null olduğu için)
152
- let failoverBot = null; // yedek hesabın mineflayer instance'ı
153
- let failoverInProgress = false; // aynı anda 2 kez tetiklenmesin diye kilit
154
 
155
- // --- DİNAMİK IP VE KONUM BİLGİLERİ ---
156
  let activeConnectionIp = "Bilinmiyor";
157
  let activeConnectionLocation = "Bilinmiyor";
158
  let localExternalIp = "Bilinmiyor";
159
 
160
- // --- DİNAMİK ZAMANLAYICI KONTROLÜ ---
161
  let periodicTimeoutHandle = null;
162
  let activeTimeouts = [];
163
 
@@ -167,7 +163,6 @@ function setSafeTimeout(fn, delay) {
167
  return t;
168
  }
169
 
170
- // --- ÖNCELİKLİ GUI KİLİDİ (MUTEX) ---
171
  class PriorityGuiMutex {
172
  constructor() {
173
  this._locked = false;
@@ -207,7 +202,8 @@ let botActions = {
207
  sendSkyblockManual: null,
208
  antiBotMove: null,
209
  sendMoneyToNick: null,
210
- scanStorageInfoManual: null
 
211
  };
212
 
213
  function formatDurationMs(ms) {
@@ -261,7 +257,6 @@ function stopPeriodicHomeChecks() {
261
  nextCiftciTimeStr = "Zamanlama durduruldu.";
262
  }
263
 
264
- // --- MANUEL DURDURMA/BAŞLATMA KONTROLÜ ---
265
  let manualStopRequested = false;
266
 
267
  async function getIpLocation(ip) {
@@ -310,14 +305,6 @@ https.get('https://api.ipify.org?format=json', (res) => {
310
  });
311
  }).on('error', () => {});
312
 
313
- // =====================================================================
314
- // KAZICI FAILOVER (YEDEK HESAP) YARDIMCI FONKSİYONLARI
315
- // Bunlar module-level (createBot() dışında) çünkü bot bağlantısı kesilip
316
- // yeniden kurulduğunda bile (createBot() tekrar çağrıldığında) hayatta
317
- // kalmaları gerekiyor.
318
- // =====================================================================
319
-
320
- // Entity'nin skin texture değerini (player_head equipment'inden) çıkarır.
321
  function getEntitySkinHash(entity) {
322
  try {
323
  const equipment = entity.equipment || [];
@@ -337,7 +324,6 @@ function getEntitySkinHash(entity) {
337
  return null;
338
  }
339
 
340
- // Entity'nin elinde (equipment[0] = main hand) iron_pickaxe olup olmadığını kontrol eder.
341
  function hasIronPickaxeEquipped(entity) {
342
  try {
343
  const equipment = entity.equipment || [];
@@ -348,7 +334,6 @@ function hasIronPickaxeEquipped(entity) {
348
  }
349
  }
350
 
351
- // Skin + iron_pickaxe ikisi birden tutuyorsa bu entity izlenen kazıcı minyondur.
352
  function isWatchedKaziciEntity(entity) {
353
  if (!entity || entity.name !== "armor_stand") return false;
354
  const skinHash = getEntitySkinHash(entity);
@@ -356,7 +341,6 @@ function isWatchedKaziciEntity(entity) {
356
  return hasIronPickaxeEquipped(entity);
357
  }
358
 
359
- // metadata içindeki pose (kol/kafa açıları) + pozisyonu birleştirip bir imza çıkarır.
360
  function getPoseKey(entity) {
361
  try {
362
  const md = entity.metadata || [];
@@ -375,8 +359,6 @@ function getPoseKey(entity) {
375
  }
376
  }
377
 
378
- // bot.on('entityMoved', ...) ve bot.on('entitySpawn', ...) içinden çağrılır.
379
- // İzlenen kazıcı minyonun pose'unu takip eder.
380
  function trackKaziciPoseIfWatched(entity) {
381
  if (!entity) return;
382
  if (!isWatchedKaziciEntity(entity)) return;
@@ -394,10 +376,8 @@ function trackKaziciPoseIfWatched(entity) {
394
  prev.poseKey = poseKey;
395
  prev.lastChangeAt = Date.now();
396
  }
397
- // poseKey aynıysa lastChangeAt GÜNCELLENMEZ -> hareketsizlik süresi büyümeye devam eder.
398
  }
399
 
400
- // Artık dünyada olmayan entity kayıtlarını temizler.
401
  function pruneStaleTrackedEntities() {
402
  if (!bot || !bot.entities) return;
403
  for (const id of poseTracker.keys()) {
@@ -438,9 +418,6 @@ function stopStallWatcher() {
438
  poseTracker.clear();
439
  }
440
 
441
- // Ana hesabı geçici düşürüp yedek hesabı (kullaniciadi1) devreye alan, izlenen
442
- // kazıcı minyonlar tekrar hareket edene kadar bekleyen, sonra ana hesabı
443
- // yeniden bağlayan tam akış.
444
  async function triggerFailoverSequence() {
445
  if (failoverInProgress) return;
446
  failoverInProgress = true;
@@ -451,7 +428,7 @@ async function triggerFailoverSequence() {
451
 
452
  logger.warn(`[Failover] İzlenen kazıcı(lar) durdu. Ana hesap (${mainUsername}) geçici olarak düşürülüp yedek hesap (${backupUsername}) devreye alınıyor.`);
453
 
454
- manualStopRequested = true; // mevcut auto-reconnect mantığını geçici olarak devre dışı bırakır
455
  stopPeriodicHomeChecks();
456
  safeDestroyAllConnections();
457
 
@@ -470,9 +447,6 @@ async function triggerFailoverSequence() {
470
  failoverInProgress = false;
471
  }
472
 
473
- // Yedek hesapla ayrı bir mineflayer bot'u başlatır: /login, /skyblock, /is go
474
- // atar (ana hesaptaki ile AYNI gecikme süreleriyle), sonra izlenen minyonların
475
- // hareketine bakar. Hareket geri gelince bağlantıyı kapatıp resolve eder.
476
  function runBackupAccountAndWaitForRecovery(backupUsername) {
477
  return new Promise((resolve) => {
478
  const backupPoseTracker = new Map();
@@ -535,7 +509,6 @@ function runBackupAccountAndWaitForRecovery(backupUsername) {
535
  logger.info(`[Failover - Yedek Hesap] ${GO_ISLAND_COMMAND} gönderildi, izlenen minyonların tekrar hareket etmesi bekleniyor...`);
536
  }, FAILOVER_ISGO_DELAY_MS);
537
 
538
- // Adaya varış + izleme başlatma
539
  setTimeout(() => {
540
  recheckHandle = setInterval(() => {
541
  try {
@@ -552,7 +525,7 @@ function runBackupAccountAndWaitForRecovery(backupUsername) {
552
 
553
  if (!prev) {
554
  backupPoseTracker.set(e.id, { poseKey, lastChangeAt: Date.now() });
555
- allRecovered = false; // henüz yeterince veri yok, bir tur daha bekle
556
  continue;
557
  }
558
 
@@ -560,7 +533,7 @@ function runBackupAccountAndWaitForRecovery(backupUsername) {
560
  prev.poseKey = poseKey;
561
  prev.lastChangeAt = Date.now();
562
  } else if (Date.now() - prev.lastChangeAt < STALL_TIMEOUT_MS) {
563
- // son 1 dk içinde bir değişiklik olmuş demek ki hareket ediyor
564
  } else {
565
  allRecovered = false;
566
  }
@@ -591,7 +564,6 @@ function runBackupAccountAndWaitForRecovery(backupUsername) {
591
  }
592
  });
593
 
594
- // Güvenlik: sonsuza kadar beklemesin
595
  safetyTimeoutHandle = setTimeout(() => {
596
  logger.warn(`[Failover - Yedek Hesap] Azami bekleme süresi (${formatDurationMs(FAILOVER_MAX_WAIT_MS)}) doldu, ana hesaba geri dönülüyor.`);
597
  finish();
@@ -953,72 +925,68 @@ async function createBot() {
953
  } catch (e) { return undefined; }
954
  };
955
 
956
- // components dizisinden belirli tipteki component'in data'sını bulur
957
- function getComponentData(slot, type) {
958
- try {
959
- if (!slot || !Array.isArray(slot.components)) return undefined;
960
- const comp = slot.components.find(c => c && c.type === type);
961
- return comp ? comp.data : undefined;
962
- } catch (e) { return undefined; }
963
- }
964
-
965
- // {type,value} tarzı NBT-benzeri sarmalayıcıyı açar
966
- function nbtUnwrap(node) {
967
- if (node && typeof node === "object" && "type" in node && "value" in node) {
968
- return node.value;
969
  }
970
- return node;
971
- };
972
 
973
- // Yeni "components" formatındaki text-component ağacını düz metne çevirir
974
- function flattenTextComponent(node) {
975
- if (node == null) return "";
976
- if (typeof node === "string") return node;
977
- if (Array.isArray(node)) return node.map(flattenTextComponent).join("");
978
-
979
- if (typeof node === "object") {
980
- if ("type" in node && "value" in node) {
981
- const t = node.type, v = node.value;
982
- if (t === "string") return typeof v === "string" ? v : "";
983
- if (t === "list" || t === "compound") return flattenTextComponent(v);
984
- return ""; // byte/int vs. metin değil
985
- }
986
- let out = "";
987
- if ("text" in node) out += flattenTextComponent(node.text);
988
- if ("extra" in node) out += flattenTextComponent(node.extra);
989
- return out;
990
- }
991
- return "";
992
- };
993
 
994
- // Tek bir lore satırı node'unu {text, color} olarak parse eder (yeni format)
995
- function parseComponentLoreLine(lineNode) {
996
- let text = "";
997
- let color = null;
998
 
999
- function walk(node) {
1000
- if (node == null) return;
1001
- if (typeof node === "string") { text += node; return; }
1002
- if (Array.isArray(node)) { node.forEach(walk); return; }
1003
  if (typeof node === "object") {
1004
  if ("type" in node && "value" in node) {
1005
  const t = node.type, v = node.value;
1006
- if (t === "string") { text += (typeof v === "string" ? v : ""); return; }
1007
- if (t === "list" || t === "compound") { walk(v); return; }
1008
- return;
1009
  }
1010
- if ("color" in node) {
1011
- const colVal = nbtUnwrap(node.color);
1012
- if (color == null && typeof colVal === "string") color = colVal;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1013
  }
1014
- if ("text" in node) walk(node.text);
1015
- if ("extra" in node) walk(node.extra);
1016
  }
1017
- }
1018
 
1019
- walk(lineNode);
1020
- return { text: text.trim(), color };
1021
- };
1022
 
1023
  function deepSearchForString(root, targetVariantsList) {
1024
  const results = [];
@@ -1092,8 +1060,7 @@ function parseComponentLoreLine(lineNode) {
1092
  const texts = [];
1093
  try {
1094
  if (!slot) return texts;
1095
-
1096
- // Yeni format: components
1097
  const customNameData = getComponentData(slot, "custom_name");
1098
  if (customNameData !== undefined) {
1099
  const nameTxt = flattenTextComponent(customNameData);
@@ -1107,8 +1074,7 @@ function parseComponentLoreLine(lineNode) {
1107
  }
1108
  }
1109
  if (texts.length > 0) return texts;
1110
-
1111
- // Eski format: nbt (fallback)
1112
  function extractPlain(raw) {
1113
  if (!raw || typeof raw !== "string") return null;
1114
  try {
@@ -1123,12 +1089,12 @@ function parseComponentLoreLine(lineNode) {
1123
  } catch (e) {}
1124
  return raw;
1125
  }
1126
-
1127
  if (slot.nbt) {
1128
  const name = safeGet(slot.nbt, ["value", "display", "value", "Name", "value"]);
1129
  const plainName = extractPlain(name);
1130
  if (plainName) texts.push(plainName);
1131
-
1132
  const lore = safeGet(slot.nbt, ["value", "display", "value", "Lore", "value"]);
1133
  if (Array.isArray(lore)) {
1134
  for (const line of lore) {
@@ -1137,7 +1103,7 @@ function parseComponentLoreLine(lineNode) {
1137
  }
1138
  }
1139
  }
1140
-
1141
  if (texts.length === 0) {
1142
  texts.push(util.inspect(slot, { depth: null }));
1143
  }
@@ -1180,12 +1146,10 @@ function parseComponentLoreLine(lineNode) {
1180
  }
1181
  }
1182
 
1183
- // --- SENDMONEY: /money oku, bakiyeden 1000 eksiğini ilgili nick'e /pay ile gönder ---
1184
  const MONEY_BALANCE_REGEX = /bakiyen:\s*([\d.,]+)\s*TL/i;
1185
  const MONEY_RESPONSE_TIMEOUT_MS = 8000;
1186
 
1187
  function parseBalanceToAdjustedAmount(rawBalanceStr) {
1188
- // "444,626.89" -> virgülleri kaldır -> "444626.89" -> noktadan öncesini al -> "444626"
1189
  const noCommas = rawBalanceStr.replace(/,/g, "");
1190
  const beforeDot = noCommas.split(".")[0];
1191
  const intValue = parseInt(beforeDot, 10);
@@ -1267,22 +1231,21 @@ function parseComponentLoreLine(lineNode) {
1267
  if (!bot || !botIsReady) return;
1268
  try {
1269
  const moves = ['forward', 'left', 'right', 'jump'];
1270
-
1271
- const moveCount = Math.floor(Math.random() * 4) + 2; // 2-5 hareket
1272
-
1273
  for (let i = 0; i < moveCount; i++) {
1274
  const move = moves[Math.floor(Math.random() * moves.length)];
1275
  const duration = 150 + Math.floor(Math.random() * 500);
1276
-
1277
  bot.setControlState(move, true);
1278
  await new Promise(r => setTimeout(r, duration));
1279
  bot.setControlState(move, false);
1280
-
1281
  await new Promise(r => setTimeout(r, 100 + Math.random() * 300));
1282
-
1283
  }
1284
-
1285
- // Rastgele kafa hareketi
1286
  await bot.look(
1287
  bot.entity.yaw + ((Math.random() - 0.5) * 1.5),
1288
  bot.entity.pitch + ((Math.random() - 0.5) * 0.3),
@@ -1738,24 +1701,18 @@ function activateEntityAtNoLook(entity, position) {
1738
  }
1739
  }
1740
 
1741
- // =====================================================================
1742
- // ÇİFTÇİ FİLTRE NAVİGASYONU + STORAGE INFO TARAMA
1743
- // =====================================================================
1744
-
1745
  function stripColorAndGetLoreLines(window) {
1746
  if (!window || !Array.isArray(window.slots)) return null;
1747
  for (const slot of window.slots) {
1748
  if (!slot) continue;
1749
-
1750
  let nameTxt = "";
1751
-
1752
- // Yeni format: components
1753
  const customNameData = getComponentData(slot, "custom_name");
1754
  if (customNameData !== undefined) {
1755
  nameTxt = flattenTextComponent(customNameData);
1756
  }
1757
-
1758
- // Eski format: nbt (fallback)
1759
  if (!nameTxt && slot.nbt) {
1760
  const nameRaw = safeGet(slot.nbt, ["value", "display", "value", "Name", "value"]);
1761
  try {
@@ -1764,7 +1721,7 @@ function activateEntityAtNoLook(entity, position) {
1764
  else if (maybe && maybe.text) nameTxt = maybe.text;
1765
  } catch (e) { nameTxt = nameRaw || ""; }
1766
  }
1767
-
1768
  if (nameTxt.includes(CIFTCI_FILTER_ITEM_NAME_KEYWORD)) {
1769
  return { slot, index: window.slots.indexOf(slot) };
1770
  }
@@ -1774,8 +1731,7 @@ function activateEntityAtNoLook(entity, position) {
1774
 
1775
  function getFilterItemLoreEntries(filterSlot) {
1776
  const entries = [];
1777
-
1778
- // Yeni format: components
1779
  const loreData = getComponentData(filterSlot, "lore");
1780
  if (Array.isArray(loreData)) {
1781
  for (const line of loreData) {
@@ -1783,8 +1739,7 @@ function activateEntityAtNoLook(entity, position) {
1783
  }
1784
  if (entries.length > 0) return entries;
1785
  }
1786
-
1787
- // Eski format: nbt (fallback)
1788
  try {
1789
  const lore = safeGet(filterSlot.nbt, ["value", "display", "value", "Lore", "value"]);
1790
  if (!Array.isArray(lore)) return entries;
@@ -1820,7 +1775,6 @@ function activateEntityAtNoLook(entity, position) {
1820
  );
1821
  if (match) return i;
1822
  }
1823
- // fallback: sadece renkle bulmayı dene
1824
  const colorMatch = loreEntries.find(e => e.color === CIFTCI_ACTIVE_FILTER_COLOR);
1825
  if (colorMatch) {
1826
  for (let i = 0; i < CIFTCI_FILTER_MODES.length; i++) {
@@ -1831,7 +1785,6 @@ function activateEntityAtNoLook(entity, position) {
1831
  }
1832
 
1833
  async function waitForFilterItem(maxRetries) {
1834
- // window açıldıktan sonra Filtre item'ı gözükene kadar bekler
1835
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
1836
  await new Promise(r => setTimeout(r, attempt === 0 ? CIFTCI_FILTER_STEP_WAIT_MS : CIFTCI_FILTER_RETRY_WAIT_MS));
1837
  if (!bot || !bot.currentWindow) return null;
@@ -1867,6 +1820,15 @@ function activateEntityAtNoLook(entity, position) {
1867
  };
1868
  }
1869
 
 
 
 
 
 
 
 
 
 
1870
  async function navigateCiftciFilterToGenerator() {
1871
  if (!bot || !bot.currentWindow) return false;
1872
 
@@ -1894,11 +1856,11 @@ function activateEntityAtNoLook(entity, position) {
1894
  }
1895
 
1896
  const total = CIFTCI_FILTER_MODES.length;
1897
- const forwardDist = (CIFTCI_TARGET_FILTER_INDEX - currentIndex + total) % total; // sol tık (aşağı)
1898
- const backwardDist = (currentIndex - CIFTCI_TARGET_FILTER_INDEX + total) % total; // sağ tık (yukarı)
1899
 
1900
  const useLeftClick = forwardDist <= backwardDist;
1901
- const mouseButton = useLeftClick ? 0 : 1; // 0 = left, 1 = right
1902
 
1903
  logger.info(`[Çiftçi Filtre] Mevcut: "${CIFTCI_FILTER_MODES[currentIndex]}" -> Hedef: "${CIFTCI_FILTER_MODES[CIFTCI_TARGET_FILTER_INDEX]}". ${useLeftClick ? "Sol tık (aşağı)" : "Sağ tık (yukarı)"} kullanılacak.`);
1904
 
@@ -1908,8 +1870,6 @@ function activateEntityAtNoLook(entity, position) {
1908
  logger.error(`[Çiftçi Filtre] Tıklama hatası: ${e && e.message ? e.message : e}`);
1909
  return false;
1910
  }
1911
-
1912
- // bir sonraki turda waitForFilterItem zaten bekleyecek
1913
  }
1914
 
1915
  logger.warn("[Çiftçi Filtre] Azami deneme sayısına ulaşıldı, Jeneratör materyallerine geçilemedi.");
@@ -2008,6 +1968,349 @@ function activateEntityAtNoLook(entity, position) {
2008
  }
2009
  };
2010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2011
  function startStorageScanPeriodic() {
2012
  if (storageScanIntervalHandle) return;
2013
  storageScanIntervalHandle = setInterval(() => {
@@ -2016,7 +2319,6 @@ function activateEntityAtNoLook(entity, position) {
2016
  scanStorageInfo();
2017
  }, STORAGE_SCAN_INTERVAL_MS);
2018
  logger.info(`[Storage Tarama] Bağımsız döngü başlatıldı (her ${formatDurationMs(STORAGE_SCAN_INTERVAL_MS)}).`);
2019
- // ilk taramayı biraz gecikmeli başlat ki spawn sonrası diğer işler önce otursun
2020
  setSafeTimeout(() => { scanStorageInfo(); }, 30 * 1000);
2021
  }
2022
 
@@ -2101,6 +2403,7 @@ function activateEntityAtNoLook(entity, position) {
2101
  botActions.antiBotMove = antiBotMove;
2102
  botActions.sendMoneyToNick = sendMoneyToNick;
2103
  botActions.scanStorageInfoManual = scanStorageInfoManual;
 
2104
 
2105
  startKaziciPeriodic();
2106
  startCiftciPeriodic();
@@ -2171,12 +2474,14 @@ function activateEntityAtNoLook(entity, position) {
2171
  (matchesAnyName(titleRaw, TARGET_CIFTCI_NORMS) || windowMatchesLoreKeyword(window, CIFTCI_LORE_FALLBACK_KEYWORDS));
2172
 
2173
  if (!isBesleyiciWindow && !isKaziciWindow && !isCiftciWindow) {
2174
- logger.info(`[${currentBotUsername}] Bi chest açıldı ama window title ı uyuşmadığı için kapatıldı. ${titleRaw}`);
2175
- try { bot.closeWindow(window); } catch(e){}
2176
- return;
2177
- }
2178
-
2179
- if (isKaziciWindow) {
 
 
2180
  try {
2181
  logger.info(`[${currentBotUsername}] Kazıcı minyon paneli açıldı. Depo aktarım slotuna (oyun içi 18. slot / mineflayer idx ${KAZICI_STORAGE_TRANSFER_SLOT}) tıklanıyor...`);
2182
  await bot.clickWindow(KAZICI_STORAGE_TRANSFER_SLOT, 0, 0);
@@ -2189,9 +2494,9 @@ function activateEntityAtNoLook(entity, position) {
2189
  try { bot.closeWindow(window); } catch(e){}
2190
 
2191
  } else if (isCiftciWindow) {
2192
- if (ciftciWindowPurpose === "scan") {
2193
- // Storage tarama modu: burada otomatik tıklama/kapatma yapma,
2194
- // scanStorageInfoCore kendi akışını yönetiyor. Sadece resolver'ı tetikle.
2195
  } else {
2196
  try {
2197
  logger.info(`[${currentBotUsername}] Çiftçi (Hepsini Sat) menüsü açıldı. ${formatDurationMs(CIFTCI_CLICK_DELAY_AFTER_OPEN_MS)} bekleniyor, sonra slot ${CIFTCI_SELL_ALL_SLOT}'e ${CIFTCI_CLICK_REPEAT_COUNT} kez tıklanacak...`);
@@ -2274,6 +2579,7 @@ function activateEntityAtNoLook(entity, position) {
2274
  }
2275
  });
2276
 
 
2277
  bot.on("end", () => {
2278
  try {
2279
  logger.warn(manualStopRequested ? "Bağlantı koptu. Manuel durdurma istendiği için yeniden bağlanılmayacak." : "Bağlantı koptu. Tüm zamanlayıcılar sıfırlanıyor ve YENİDEN BAĞLANMA SÜRECİ BAŞLIYOR...");
@@ -2298,6 +2604,7 @@ function activateEntityAtNoLook(entity, position) {
2298
  botActions.antiBotMove = null;
2299
  botActions.sendMoneyToNick = null;
2300
  botActions.scanStorageInfoManual = null;
 
2301
 
2302
  safeDestroyAllConnections();
2303
 
@@ -2379,7 +2686,6 @@ function triggerSafeReconnect() {
2379
  }, delay);
2380
  }
2381
 
2382
- // --- MANUEL BOT KONTROLÜ (stop/start/restart) ---
2383
  let pendingHardRestartTimeout = null;
2384
 
2385
  function stopBotHard(reason) {
@@ -2566,6 +2872,7 @@ app.get("/status", (req, res) => {
2566
  next_kazici_check: nextKaziciTimeStr,
2567
  last_ciftci_sell: lastCiftciSellTimeStr,
2568
  next_ciftci_sell: nextCiftciTimeStr,
 
2569
  gui_lock_busy: guiMutex.isLocked(),
2570
  manually_stopped: manualStopRequested,
2571
  is_connecting: isConnecting,
@@ -2582,7 +2889,6 @@ app.get("/storageInfo", (req, res) => {
2582
  });
2583
  });
2584
 
2585
- // --- MANUEL BOT KONTROLÜ ENDPOINT'LERİ ---
2586
  app.get("/bot/stop", (req, res) => {
2587
  stopBotHard("Web paneli üzerinden /bot/stop isteği");
2588
  res.send({ success: true, message: "Bot durduruldu. Tekrar başlatmak için /bot/start kullan." });
@@ -2707,6 +3013,26 @@ app.get("/bot/sendmoney", (req, res) => {
2707
  });
2708
  });
2709
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2710
  app.get("/", (req, res) => res.send("Bot Aktif"));
2711
 
2712
  app.get("/messages", (req, res) => {
@@ -2942,4 +3268,4 @@ process.stderr.write = function (chunk, encoding, callback) {
2942
  return true;
2943
  }
2944
  return originalStderrWrite.apply(process.stderr, arguments);
2945
- };
 
44
  const CIFTCI_COMMAND = "/çiftçi menü";
45
  const CIFTCI_WINDOW_TIMEOUT_MS = 6000;
46
  const CIFTCI_LORE_FALLBACK_KEYWORDS = ["hepsini sat"];
 
 
47
  const CIFTCI_CLICK_DELAY_AFTER_OPEN_MS = 1000;
48
  const CIFTCI_CLICK_REPEAT_COUNT = 3;
49
  const CIFTCI_CLICK_REPEAT_GAP_MS = 350;
50
 
51
+ const KAZICI_CYCLE_INTERVAL_MS = 5 * 60 * 1000;
52
+ const CIFTCI_CYCLE_INTERVAL_MS = 60 * 1000;
53
 
 
 
 
 
54
  const CIFTCI_FILTER_MODES = [
55
  "Standart",
56
  "Favoriler",
 
59
  "Satışı açık olanlar",
60
  "Toplaması açık olanlar"
61
  ];
62
+ const CIFTCI_TARGET_FILTER_INDEX = 3;
63
  const CIFTCI_ACTIVE_FILTER_COLOR = "#FCF988";
64
  const CIFTCI_FILTER_ITEM_NAME_KEYWORD = "Filtre";
65
+ const CIFTCI_FILTER_STEP_WAIT_MS = 1000;
66
+ const CIFTCI_FILTER_RETRY_WAIT_MS = 1000;
67
+ const CIFTCI_FILTER_MAX_RETRIES = 10;
68
+ const STORAGE_SCAN_INTERVAL_MS = 15 * 60 * 1000;
69
+ const STORAGE_TRACKED_ITEMS = ["diamond", "emerald", "iron_block"];
70
+
71
+ // --- SİPARİŞ (ORDER) SİSTEMİ AYARLARI ---
72
+ const ORDER_COMMAND_PREFIX = "/order";
73
+ const ORDER_WINDOW_TIMEOUT_MS = 8000;
74
+ const ORDER_WINDOW_SETTLE_DELAY_MS = 500;
75
+ const ORDER_AFTER_SELECT_DELAY_MS = 500;
76
+ const ORDER_IS_GO_SECOND_DELAY_MS = 5000;
77
+ const ORDER_ALLOWED_ITEMS = ["diamond", "emerald"];
78
+ const ORDER_LIST_TITLE_KEYWORD = "ѕiᴘᴀʀişʟᴇʀ";
79
+ const ORDER_DELIVERY_TITLE_KEYWORD = "ᴛᴇѕʟiᴍ ᴇᴛᴍᴇ";
80
+ // Nick seçildikten sonra Teslim Etme penceresinin gerçekten açılmasını beklemek için
81
+ // kullanılan zaman aşımı (sabit sleep yerine).
82
+ const ORDER_DELIVERY_WINDOW_WAIT_MS = 8000;
83
 
84
  let storageInfoCache = {
85
  diamond: null,
 
89
  };
90
  let storageScanIntervalHandle = null;
91
 
 
 
92
  let ciftciWindowPurpose = "sell";
93
 
94
+ const STALL_CHECK_INTERVAL_MS = 15 * 1000;
95
+ const STALL_TIMEOUT_MS = 60 * 1000;
96
+ const FAILOVER_HOME_ARRIVAL_DELAY_MS = 4000;
 
97
  const FAILOVER_LOGIN_DELAY_MS = 2500;
98
  const FAILOVER_SKYBLOCK_DELAY_MS = 7500;
99
  const FAILOVER_ISGO_DELAY_MS = 12500;
100
+ const FAILOVER_RECHECK_INTERVAL_MS = 20 * 1000;
101
+ const FAILOVER_MAX_WAIT_MS = 60 * 60 * 1000;
102
+ const FAILOVER_SPAWN_TIMEOUT_MS = 30 * 1000;
103
 
 
 
104
  const WATCHED_KAZICI_SKIN_HASHES = new Set([
105
  "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNDQ4ODcwY2E3N2FhNjk5ZDAxNzA5M2I4Mjc3OWQwYTU5OGRjNGYzZjQ5ZDM1MTUzMmFlNGQ5NjMzZGNjMmE1YSJ9fX0=",
106
  ]);
 
115
  let isListeningChat = false;
116
  const ansiToHtmlConvert = new (require('ansi-to-html'))({ newline: true });
117
 
 
118
  let isConnecting = false;
119
  let isDestroying = false;
120
  let reconnectTimeout = null;
 
123
  let currentSocket = null;
124
  let windowOpenResolvers = [];
125
 
 
126
  let botUptimeStart = null;
127
  let lastFullFeedTimeStr = "Henüz besleme yapılmadı";
128
  let lastCheckTimeStr = "Henüz kontrol yapılmadı";
129
  let nextScheduledCheckTimeStr = "Botun spawn olması bekleniyor...";
130
 
 
131
  let lastKaziciCheckTimeStr = "Henüz kazıcı kontrolü yapılmadı";
132
  let nextKaziciTimeStr = "Botun spawn olması bekleniyor...";
133
  let nextKaziciAtMs = null;
134
 
 
135
  let lastCiftciSellTimeStr = "Henüz çiftçi satışı yapılmadı";
136
  let nextCiftciTimeStr = "Botun spawn olması bekleniyor...";
137
  let nextCiftciAtMs = null;
138
 
139
+ let lastOrderTimeStr = "Henüz sipariş işlemi yapılmadı";
140
+
141
+ let lastCheckAtMs = null;
142
+ let nextScheduledCheckAtMs = null;
143
+ let kaziciIntervalHandle = null;
144
+ let ciftciIntervalHandle = null;
145
+ let isMainCycleRunning = false;
146
 
147
+ let poseTracker = new Map();
 
148
  let stallCheckIntervalHandle = null;
149
+ let failoverModeActive = false;
150
+ let failoverBot = null;
151
+ let failoverInProgress = false;
152
 
 
153
  let activeConnectionIp = "Bilinmiyor";
154
  let activeConnectionLocation = "Bilinmiyor";
155
  let localExternalIp = "Bilinmiyor";
156
 
 
157
  let periodicTimeoutHandle = null;
158
  let activeTimeouts = [];
159
 
 
163
  return t;
164
  }
165
 
 
166
  class PriorityGuiMutex {
167
  constructor() {
168
  this._locked = false;
 
202
  sendSkyblockManual: null,
203
  antiBotMove: null,
204
  sendMoneyToNick: null,
205
+ scanStorageInfoManual: null,
206
+ processOrderManual: null
207
  };
208
 
209
  function formatDurationMs(ms) {
 
257
  nextCiftciTimeStr = "Zamanlama durduruldu.";
258
  }
259
 
 
260
  let manualStopRequested = false;
261
 
262
  async function getIpLocation(ip) {
 
305
  });
306
  }).on('error', () => {});
307
 
 
 
 
 
 
 
 
 
308
  function getEntitySkinHash(entity) {
309
  try {
310
  const equipment = entity.equipment || [];
 
324
  return null;
325
  }
326
 
 
327
  function hasIronPickaxeEquipped(entity) {
328
  try {
329
  const equipment = entity.equipment || [];
 
334
  }
335
  }
336
 
 
337
  function isWatchedKaziciEntity(entity) {
338
  if (!entity || entity.name !== "armor_stand") return false;
339
  const skinHash = getEntitySkinHash(entity);
 
341
  return hasIronPickaxeEquipped(entity);
342
  }
343
 
 
344
  function getPoseKey(entity) {
345
  try {
346
  const md = entity.metadata || [];
 
359
  }
360
  }
361
 
 
 
362
  function trackKaziciPoseIfWatched(entity) {
363
  if (!entity) return;
364
  if (!isWatchedKaziciEntity(entity)) return;
 
376
  prev.poseKey = poseKey;
377
  prev.lastChangeAt = Date.now();
378
  }
 
379
  }
380
 
 
381
  function pruneStaleTrackedEntities() {
382
  if (!bot || !bot.entities) return;
383
  for (const id of poseTracker.keys()) {
 
418
  poseTracker.clear();
419
  }
420
 
 
 
 
421
  async function triggerFailoverSequence() {
422
  if (failoverInProgress) return;
423
  failoverInProgress = true;
 
428
 
429
  logger.warn(`[Failover] İzlenen kazıcı(lar) durdu. Ana hesap (${mainUsername}) geçici olarak düşürülüp yedek hesap (${backupUsername}) devreye alınıyor.`);
430
 
431
+ manualStopRequested = true;
432
  stopPeriodicHomeChecks();
433
  safeDestroyAllConnections();
434
 
 
447
  failoverInProgress = false;
448
  }
449
 
 
 
 
450
  function runBackupAccountAndWaitForRecovery(backupUsername) {
451
  return new Promise((resolve) => {
452
  const backupPoseTracker = new Map();
 
509
  logger.info(`[Failover - Yedek Hesap] ${GO_ISLAND_COMMAND} gönderildi, izlenen minyonların tekrar hareket etmesi bekleniyor...`);
510
  }, FAILOVER_ISGO_DELAY_MS);
511
 
 
512
  setTimeout(() => {
513
  recheckHandle = setInterval(() => {
514
  try {
 
525
 
526
  if (!prev) {
527
  backupPoseTracker.set(e.id, { poseKey, lastChangeAt: Date.now() });
528
+ allRecovered = false;
529
  continue;
530
  }
531
 
 
533
  prev.poseKey = poseKey;
534
  prev.lastChangeAt = Date.now();
535
  } else if (Date.now() - prev.lastChangeAt < STALL_TIMEOUT_MS) {
536
+ // ok
537
  } else {
538
  allRecovered = false;
539
  }
 
564
  }
565
  });
566
 
 
567
  safetyTimeoutHandle = setTimeout(() => {
568
  logger.warn(`[Failover - Yedek Hesap] Azami bekleme süresi (${formatDurationMs(FAILOVER_MAX_WAIT_MS)}) doldu, ana hesaba geri dönülüyor.`);
569
  finish();
 
925
  } catch (e) { return undefined; }
926
  };
927
 
928
+ function getComponentData(slot, type) {
929
+ try {
930
+ if (!slot || !Array.isArray(slot.components)) return undefined;
931
+ const comp = slot.components.find(c => c && c.type === type);
932
+ return comp ? comp.data : undefined;
933
+ } catch (e) { return undefined; }
 
 
 
 
 
 
 
934
  }
 
 
935
 
936
+ function nbtUnwrap(node) {
937
+ if (node && typeof node === "object" && "type" in node && "value" in node) {
938
+ return node.value;
939
+ }
940
+ return node;
941
+ };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
942
 
943
+ function flattenTextComponent(node) {
944
+ if (node == null) return "";
945
+ if (typeof node === "string") return node;
946
+ if (Array.isArray(node)) return node.map(flattenTextComponent).join("");
947
 
 
 
 
 
948
  if (typeof node === "object") {
949
  if ("type" in node && "value" in node) {
950
  const t = node.type, v = node.value;
951
+ if (t === "string") return typeof v === "string" ? v : "";
952
+ if (t === "list" || t === "compound") return flattenTextComponent(v);
953
+ return "";
954
  }
955
+ let out = "";
956
+ if ("text" in node) out += flattenTextComponent(node.text);
957
+ if ("extra" in node) out += flattenTextComponent(node.extra);
958
+ return out;
959
+ }
960
+ return "";
961
+ };
962
+
963
+ function parseComponentLoreLine(lineNode) {
964
+ let text = "";
965
+ let color = null;
966
+
967
+ function walk(node) {
968
+ if (node == null) return;
969
+ if (typeof node === "string") { text += node; return; }
970
+ if (Array.isArray(node)) { node.forEach(walk); return; }
971
+ if (typeof node === "object") {
972
+ if ("type" in node && "value" in node) {
973
+ const t = node.type, v = node.value;
974
+ if (t === "string") { text += (typeof v === "string" ? v : ""); return; }
975
+ if (t === "list" || t === "compound") { walk(v); return; }
976
+ return;
977
+ }
978
+ if ("color" in node) {
979
+ const colVal = nbtUnwrap(node.color);
980
+ if (color == null && typeof colVal === "string") color = colVal;
981
+ }
982
+ if ("text" in node) walk(node.text);
983
+ if ("extra" in node) walk(node.extra);
984
  }
 
 
985
  }
 
986
 
987
+ walk(lineNode);
988
+ return { text: text.trim(), color };
989
+ };
990
 
991
  function deepSearchForString(root, targetVariantsList) {
992
  const results = [];
 
1060
  const texts = [];
1061
  try {
1062
  if (!slot) return texts;
1063
+
 
1064
  const customNameData = getComponentData(slot, "custom_name");
1065
  if (customNameData !== undefined) {
1066
  const nameTxt = flattenTextComponent(customNameData);
 
1074
  }
1075
  }
1076
  if (texts.length > 0) return texts;
1077
+
 
1078
  function extractPlain(raw) {
1079
  if (!raw || typeof raw !== "string") return null;
1080
  try {
 
1089
  } catch (e) {}
1090
  return raw;
1091
  }
1092
+
1093
  if (slot.nbt) {
1094
  const name = safeGet(slot.nbt, ["value", "display", "value", "Name", "value"]);
1095
  const plainName = extractPlain(name);
1096
  if (plainName) texts.push(plainName);
1097
+
1098
  const lore = safeGet(slot.nbt, ["value", "display", "value", "Lore", "value"]);
1099
  if (Array.isArray(lore)) {
1100
  for (const line of lore) {
 
1103
  }
1104
  }
1105
  }
1106
+
1107
  if (texts.length === 0) {
1108
  texts.push(util.inspect(slot, { depth: null }));
1109
  }
 
1146
  }
1147
  }
1148
 
 
1149
  const MONEY_BALANCE_REGEX = /bakiyen:\s*([\d.,]+)\s*TL/i;
1150
  const MONEY_RESPONSE_TIMEOUT_MS = 8000;
1151
 
1152
  function parseBalanceToAdjustedAmount(rawBalanceStr) {
 
1153
  const noCommas = rawBalanceStr.replace(/,/g, "");
1154
  const beforeDot = noCommas.split(".")[0];
1155
  const intValue = parseInt(beforeDot, 10);
 
1231
  if (!bot || !botIsReady) return;
1232
  try {
1233
  const moves = ['forward', 'left', 'right', 'jump'];
1234
+
1235
+ const moveCount = Math.floor(Math.random() * 4) + 2;
1236
+
1237
  for (let i = 0; i < moveCount; i++) {
1238
  const move = moves[Math.floor(Math.random() * moves.length)];
1239
  const duration = 150 + Math.floor(Math.random() * 500);
1240
+
1241
  bot.setControlState(move, true);
1242
  await new Promise(r => setTimeout(r, duration));
1243
  bot.setControlState(move, false);
1244
+
1245
  await new Promise(r => setTimeout(r, 100 + Math.random() * 300));
1246
+
1247
  }
1248
+
 
1249
  await bot.look(
1250
  bot.entity.yaw + ((Math.random() - 0.5) * 1.5),
1251
  bot.entity.pitch + ((Math.random() - 0.5) * 0.3),
 
1701
  }
1702
  }
1703
 
 
 
 
 
1704
  function stripColorAndGetLoreLines(window) {
1705
  if (!window || !Array.isArray(window.slots)) return null;
1706
  for (const slot of window.slots) {
1707
  if (!slot) continue;
1708
+
1709
  let nameTxt = "";
1710
+
 
1711
  const customNameData = getComponentData(slot, "custom_name");
1712
  if (customNameData !== undefined) {
1713
  nameTxt = flattenTextComponent(customNameData);
1714
  }
1715
+
 
1716
  if (!nameTxt && slot.nbt) {
1717
  const nameRaw = safeGet(slot.nbt, ["value", "display", "value", "Name", "value"]);
1718
  try {
 
1721
  else if (maybe && maybe.text) nameTxt = maybe.text;
1722
  } catch (e) { nameTxt = nameRaw || ""; }
1723
  }
1724
+
1725
  if (nameTxt.includes(CIFTCI_FILTER_ITEM_NAME_KEYWORD)) {
1726
  return { slot, index: window.slots.indexOf(slot) };
1727
  }
 
1731
 
1732
  function getFilterItemLoreEntries(filterSlot) {
1733
  const entries = [];
1734
+
 
1735
  const loreData = getComponentData(filterSlot, "lore");
1736
  if (Array.isArray(loreData)) {
1737
  for (const line of loreData) {
 
1739
  }
1740
  if (entries.length > 0) return entries;
1741
  }
1742
+
 
1743
  try {
1744
  const lore = safeGet(filterSlot.nbt, ["value", "display", "value", "Lore", "value"]);
1745
  if (!Array.isArray(lore)) return entries;
 
1775
  );
1776
  if (match) return i;
1777
  }
 
1778
  const colorMatch = loreEntries.find(e => e.color === CIFTCI_ACTIVE_FILTER_COLOR);
1779
  if (colorMatch) {
1780
  for (let i = 0; i < CIFTCI_FILTER_MODES.length; i++) {
 
1785
  }
1786
 
1787
  async function waitForFilterItem(maxRetries) {
 
1788
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
1789
  await new Promise(r => setTimeout(r, attempt === 0 ? CIFTCI_FILTER_STEP_WAIT_MS : CIFTCI_FILTER_RETRY_WAIT_MS));
1790
  if (!bot || !bot.currentWindow) return null;
 
1820
  };
1821
  }
1822
 
1823
+ function findSlotByInternalName(window, internalName) {
1824
+ if (!window || !Array.isArray(window.slots)) return -1;
1825
+ for (let i = 0; i < window.slots.length; i++) {
1826
+ const s = window.slots[i];
1827
+ if (s && s.name === internalName) return i;
1828
+ }
1829
+ return -1;
1830
+ }
1831
+
1832
  async function navigateCiftciFilterToGenerator() {
1833
  if (!bot || !bot.currentWindow) return false;
1834
 
 
1856
  }
1857
 
1858
  const total = CIFTCI_FILTER_MODES.length;
1859
+ const forwardDist = (CIFTCI_TARGET_FILTER_INDEX - currentIndex + total) % total;
1860
+ const backwardDist = (currentIndex - CIFTCI_TARGET_FILTER_INDEX + total) % total;
1861
 
1862
  const useLeftClick = forwardDist <= backwardDist;
1863
+ const mouseButton = useLeftClick ? 0 : 1;
1864
 
1865
  logger.info(`[Çiftçi Filtre] Mevcut: "${CIFTCI_FILTER_MODES[currentIndex]}" -> Hedef: "${CIFTCI_FILTER_MODES[CIFTCI_TARGET_FILTER_INDEX]}". ${useLeftClick ? "Sol tık (aşağı)" : "Sağ tık (yukarı)"} kullanılacak.`);
1866
 
 
1870
  logger.error(`[Çiftçi Filtre] Tıklama hatası: ${e && e.message ? e.message : e}`);
1871
  return false;
1872
  }
 
 
1873
  }
1874
 
1875
  logger.warn("[Çiftçi Filtre] Azami deneme sayısına ulaşıldı, Jeneratör materyallerine geçilemedi.");
 
1968
  }
1969
  };
1970
 
1971
+ // =====================================================================
1972
+ // SİPARİŞ (ORDER) SİSTEMİ
1973
+ // =====================================================================
1974
+
1975
+ async function waitForNextWindowOpen(timeoutMs) {
1976
+ return new Promise((resolve) => {
1977
+ let timeoutHandle = null;
1978
+ const cleanFinish = (opened) => {
1979
+ clearTimeout(timeoutHandle);
1980
+ windowOpenResolvers = [];
1981
+ resolve(opened);
1982
+ };
1983
+
1984
+ windowOpenResolvers.push(() => cleanFinish(true));
1985
+
1986
+ timeoutHandle = setTimeout(() => {
1987
+ cleanFinish(false);
1988
+ }, timeoutMs);
1989
+ });
1990
+ }
1991
+
1992
+ function findSlotContainingNick(window, nickNorm, itemInternalName) {
1993
+ if (!window || !Array.isArray(window.slots)) return -1;
1994
+ for (let i = 0; i < window.slots.length; i++) {
1995
+ const slot = window.slots[i];
1996
+ if (!slot) continue;
1997
+
1998
+ // ÖNEMLİ: hem item tipi hem de nick eşleşmeli.
1999
+ // itemInternalName verilmişse (örn. "diamond"), slotun gerçek
2000
+ // Minecraft item id'si ile karşılaştırıyoruz (dilden bağımsız, kesin).
2001
+ if (itemInternalName && slot.name !== itemInternalName) continue;
2002
+
2003
+ const texts = getItemDisplayTexts(slot);
2004
+ for (const t of texts) {
2005
+ if (matchesAnyName(t, [nickNorm])) return i;
2006
+ }
2007
+ }
2008
+ return -1;
2009
+ }
2010
+
2011
+ async function processOrderCore(itemInternalName, nick) {
2012
+ if (!bot || !botIsReady) return { success: false, message: "Bot hazır değil." };
2013
+ if (!guiMutex.isLocked()) {
2014
+ logger.error("[GÜVENLİK İHLALİ] processOrderCore kilitsiz çağrıldı! İşlem iptal ediliyor.");
2015
+ return { success: false, message: "Kilitsiz çağrı engellendi." };
2016
+ }
2017
+ if (!ORDER_ALLOWED_ITEMS.includes(itemInternalName)) {
2018
+ return { success: false, message: `Geçersiz item: ${itemInternalName}. İzin verilenler: ${ORDER_ALLOWED_ITEMS.join(", ")}` };
2019
+ }
2020
+ if (!nick || typeof nick !== "string" || nick.trim().length === 0) {
2021
+ return { success: false, message: "nick parametresi zorunlu." };
2022
+ }
2023
+
2024
+ // --- 1) Çiftçi menüsünü aç, jeneratör materyalleri filtresine geç ---
2025
+ ciftciWindowPurpose = "order";
2026
+ logger.info(`[Sipariş] Çiftçi menüsü açılıyor (${CIFTCI_COMMAND})...`);
2027
+
2028
+ if (bot.currentWindow != null) {
2029
+ try { bot.closeWindow(bot.currentWindow); } catch (e) {}
2030
+ await new Promise(r => setTimeout(r, 300));
2031
+ }
2032
+
2033
+ let windowOpened = false;
2034
+ await new Promise((resolve) => {
2035
+ let timeoutHandle = null;
2036
+ const cleanFinish = () => { clearTimeout(timeoutHandle); windowOpenResolvers = []; resolve(); };
2037
+ windowOpenResolvers.push(() => { windowOpened = true; cleanFinish(); });
2038
+ timeoutHandle = setTimeout(() => {
2039
+ logger.warn("[Sipariş] Çiftçi menüsü açılamadı (zaman aşımı).");
2040
+ cleanFinish();
2041
+ }, CIFTCI_WINDOW_TIMEOUT_MS);
2042
+ try { bot.chat(CIFTCI_COMMAND); } catch (e) {}
2043
+ });
2044
+
2045
+ if (!windowOpened || !bot.currentWindow) {
2046
+ ciftciWindowPurpose = "sell";
2047
+ return { success: false, message: "Çiftçi menüsü açılamadı." };
2048
+ }
2049
+
2050
+ const reached = await navigateCiftciFilterToGenerator();
2051
+ if (!reached || !bot.currentWindow) {
2052
+ try { if (bot.currentWindow) bot.closeWindow(bot.currentWindow); } catch (e) {}
2053
+ ciftciWindowPurpose = "sell";
2054
+ return { success: false, message: "Jeneratör materyalleri filtresine ulaşılamadı." };
2055
+ }
2056
+
2057
+ // --- 2) İstenen item'ın slotuna shift+sağ tık (envanter dolana kadar verir) ---
2058
+ const itemSlotIndex = findSlotByInternalName(bot.currentWindow, itemInternalName);
2059
+ if (itemSlotIndex === -1) {
2060
+ try { bot.closeWindow(bot.currentWindow); } catch (e) {}
2061
+ ciftciWindowPurpose = "sell";
2062
+ return { success: false, message: `'${itemInternalName}' slotu jeneratör materyalleri filtresinde bulunamadı.` };
2063
+ }
2064
+
2065
+ try {
2066
+ logger.info(`[Sipariş] '${itemInternalName}' slotuna (idx:${itemSlotIndex}) shift+sağ tık gönderiliyor...`);
2067
+ await bot.clickWindow(itemSlotIndex, 1, 1); // mouseButton=1 (sağ), mode=1 (shift)
2068
+ await new Promise(r => setTimeout(r, KAZICI_ACTION_SETTLE_DELAY_MS));
2069
+ } catch (e) {
2070
+ logger.error(`[Sipariş] Shift+sağ tık hatası: ${e && e.message ? e.message : e}`);
2071
+ }
2072
+
2073
+ // --- YENİ: Çiftçiden gerçekten item alınmış mı doğrula ---
2074
+ // clickWindow hata fırlatmasa bile sunucu isteği görmezden gelmiş olabilir.
2075
+ // Envanterde ilgili item yoksa devam etmenin anlamı yok (Teslim Etme'ye zaten
2076
+ // aktarılacak bir şey olmaz), bu yüzden burada erkenden kontrol edip
2077
+ // anlamlı bir hata dönüyoruz.
2078
+ const itemsAfterWithdraw = bot.inventory.items().filter(it => it && it.name === itemInternalName);
2079
+ const withdrawnCount = itemsAfterWithdraw.reduce((sum, it) => sum + (it.count || 0), 0);
2080
+ logger.info(`[Sipariş] Çiftçiden çekildikten sonra envanterde '${itemInternalName}': ${withdrawnCount} adet.`);
2081
+
2082
+ if (withdrawnCount === 0) {
2083
+ logger.warn(`[Sipariş] Çiftçi menüsünden '${itemInternalName}' envantere aktarılamadı (0 adet). İşlem iptal ediliyor.`);
2084
+ try { if (bot.currentWindow) bot.closeWindow(bot.currentWindow); } catch (e) {}
2085
+ ciftciWindowPurpose = "sell";
2086
+ return { success: false, message: `Çiftçiden '${itemInternalName}' alınamadı (envanterde 0 adet). Depoda yeterli stok olmayabilir ya da tıklama sunucu tarafından işlenmedi.` };
2087
+ }
2088
+
2089
+ // --- 3) Menüyü kapat ---
2090
+ try { if (bot.currentWindow) bot.closeWindow(bot.currentWindow); } catch (e) {}
2091
+ // ÖNEMLİ: purpose burada "sell"e ÇEVRİLMEZ! /order akışı (Siparişler +
2092
+ // Teslim Etme pencereleri) henüz açılmadı. purpose "order" kaldığı sürece
2093
+ // windowOpen handler bu pencereleri otomatik kapatmayacak.
2094
+ await new Promise(r => setTimeout(r, 300));
2095
+
2096
+ // --- 4) antiBotMove -> /is go -> 5sn -> /is go ---
2097
+ try { await antiBotMove(); } catch (e) {}
2098
+ try { bot.chat(GO_ISLAND_COMMAND); } catch (e) {}
2099
+ await new Promise(r => setTimeout(r, ORDER_IS_GO_SECOND_DELAY_MS));
2100
+ try { bot.chat(GO_ISLAND_COMMAND); } catch (e) {}
2101
+ await new Promise(r => setTimeout(r, HOME_ARRIVAL_DELAY_MS));
2102
+
2103
+ // --- 5) /order <nick> gönder ---
2104
+ logger.info(`[Sipariş] ${ORDER_COMMAND_PREFIX} ${nick} komutu gönderiliyor...`);
2105
+
2106
+ let orderWindowOpened = false;
2107
+ await new Promise((resolve) => {
2108
+ let timeoutHandle = null;
2109
+ const cleanFinish = () => { clearTimeout(timeoutHandle); windowOpenResolvers = []; resolve(); };
2110
+ windowOpenResolvers.push(() => { orderWindowOpened = true; cleanFinish(); });
2111
+ timeoutHandle = setTimeout(() => {
2112
+ logger.warn("[Sipariş] /order penceresi açılamadı (zaman aşımı).");
2113
+ cleanFinish();
2114
+ }, ORDER_WINDOW_TIMEOUT_MS);
2115
+ try { bot.chat(`${ORDER_COMMAND_PREFIX} ${nick}`); } catch (e) {}
2116
+ });
2117
+
2118
+ if (!orderWindowOpened || !bot.currentWindow) {
2119
+ ciftciWindowPurpose = "sell";
2120
+ return { success: false, message: "/order penceresi açılmadı." };
2121
+ }
2122
+
2123
+ // --- 6) +500ms bekle, güncel pencereyi oku (windowOpen anındaki değil) ---
2124
+ await new Promise(r => setTimeout(r, ORDER_WINDOW_SETTLE_DELAY_MS));
2125
+ if (!bot.currentWindow) {
2126
+ ciftciWindowPurpose = "sell";
2127
+ return { success: false, message: "Pencere beklenmedik şekilde kapandı." };
2128
+ }
2129
+
2130
+ // --- 7) Lore'da nick geçen slotu bul, sol tık ile seç ---
2131
+ const nickVariants = normalizeVariants(nick);
2132
+ let targetSlotIndex = -1;
2133
+
2134
+ // 1. ÖNCELİK: hem item tipi hem nick birlikte eşleşsin
2135
+ for (const nv of nickVariants) {
2136
+ targetSlotIndex = findSlotContainingNick(bot.currentWindow, nv, itemInternalName);
2137
+ if (targetSlotIndex !== -1) break;
2138
+ }
2139
+
2140
+ if (targetSlotIndex === -1) {
2141
+ logger.warn(`[Sipariş] '${nick}' + '${itemInternalName}' eşleşen item bulunamadı, pencere kapatılıyor.`);
2142
+ try { bot.closeWindow(bot.currentWindow); } catch (e) {}
2143
+ ciftciWindowPurpose = "sell";
2144
+ return { success: false, message: `'${nick}' kullanıcısının '${itemInternalName}' siparişi bulunamadı (belki farklı item için sipariş vermiş, ya da hiç sipariş yok).` };
2145
+ }
2146
+
2147
+ logger.info(`[Sipariş] '${nick}' içeren item bulundu (idx:${targetSlotIndex}), sol tık gönderiliyor...`);
2148
+
2149
+ // --- YENİ: nick'e tıkladıktan sonra sabit 500ms yerine GERÇEK yeni
2150
+ // pencere açılışını (Teslim Etme) bekliyoruz. Bu, mevcut buğun ana
2151
+ // sebebiydi: sunucu 500ms'den geç yanıt verirse eski (Siparişler)
2152
+ // penceresine göre hesaplanmış slotlara tıklanıyor ve hiçbir şey
2153
+ // taşınmıyordu (sunucu paketi reddetmediği için hata da görünmüyordu).
2154
+ const windowBeforeSelect = bot.currentWindow;
2155
+ try {
2156
+ await bot.clickWindow(targetSlotIndex, 0, 0);
2157
+ } catch (e) {
2158
+ logger.error(`[Sipariş] Slot seçim tıklaması hatası: ${e && e.message ? e.message : e}`);
2159
+ }
2160
+
2161
+ // --- 8) Teslim Etme penceresinin gerçekten açılmasını bekle ---
2162
+ const deliveryOpened = await waitForNextWindowOpen(ORDER_DELIVERY_WINDOW_WAIT_MS);
2163
+
2164
+ if (!deliveryOpened || !bot.currentWindow) {
2165
+ logger.warn("[Sipariş] Teslim Etme penceresi zaman aşımına uğradı ya da açılmadı, işlem yarım kalmış olabilir.");
2166
+ ciftciWindowPurpose = "sell";
2167
+ return { success: false, message: "Teslim Etme penceresi açılmadı (zaman aşımı)." };
2168
+ }
2169
+
2170
+ // Pencere objesinin gerçekten DEĞİŞTİĞİNİ doğrula (bazı sunucular aynı id'yi
2171
+ // update edip windowOpen yerine sadece slot update gönderebilir; bu durumda
2172
+ // en azından title kontrolüyle devam ediyoruz).
2173
+ if (bot.currentWindow === windowBeforeSelect) {
2174
+ logger.warn("[Sipariş] windowOpen tetiklendi ama pencere referansı değişmedi, dikkatli devam ediliyor.");
2175
+ }
2176
+
2177
+ const currentTitle = parseWindowTitleToString(bot.currentWindow.title);
2178
+ const looksLikeDelivery = matchesAnyName(currentTitle, normalizeVariants(ORDER_DELIVERY_TITLE_KEYWORD));
2179
+ logger.info(`[Sipariş] Yeni pencere açıldı: "${currentTitle}" (Teslim Etme eşleşmesi: ${looksLikeDelivery}). Envanterdeki '${itemInternalName}' item'ları aktarılıyor...`);
2180
+
2181
+ if (!looksLikeDelivery) {
2182
+ logger.warn(`[Sipariş] Açılan pencere Teslim Etme'ye benzemiyor, yine de mevcut pencereye aktarım denenecek: "${currentTitle}"`);
2183
+ }
2184
+
2185
+ // Ek güvenlik: envanterde gerçekten aktarılacak item var mı, tekrar kontrol et
2186
+ // (nick seçme / /is go arasında item'lar herhangi bir sebeple kaybolmuş olabilir).
2187
+ const invStartCheck = bot.currentWindow.inventoryStart;
2188
+ const invCheckBeforeTransfer = bot.currentWindow.slots
2189
+ .slice(invStartCheck)
2190
+ .filter(it => it && it.name === itemInternalName);
2191
+ if (invCheckBeforeTransfer.length === 0) {
2192
+ logger.warn(`[Sipariş] Aktarım öncesi envanterde '${itemInternalName}' bulunamadı, aktarım atlanıyor.`);
2193
+ try { if (bot.currentWindow) bot.closeWindow(bot.currentWindow); } catch (e) {}
2194
+ ciftciWindowPurpose = "sell";
2195
+ return { success: false, message: `Envanterde '${itemInternalName}' kalmamış, Teslim Etme'ye aktarılacak item yok.` };
2196
+ }
2197
+
2198
+ const windowAtTransferStart = bot.currentWindow;
2199
+ let transferredCount = 0;
2200
+ let keepGoing = true;
2201
+ let safetyCounter = 0;
2202
+ let stuckSlot = null;
2203
+ let stuckSlotRepeatCount = 0;
2204
+
2205
+ while (keepGoing && safetyCounter < 40) {
2206
+ safetyCounter++;
2207
+
2208
+ // Pencere döngü sırasında değişti/kapandıysa (ör. sunucu Teslim Etme'yi
2209
+ // kapattıysa) devam etmenin bir anlamı yok, güvenle çık.
2210
+ if (!bot.currentWindow || bot.currentWindow !== windowAtTransferStart) {
2211
+ logger.warn("[Sipariş] Aktarım sırasında pencere değişti/kapandı, döngü durduruluyor.");
2212
+ break;
2213
+ }
2214
+
2215
+ // ÖNEMLİ FIX: bot.inventory.items() custom pencere açıkken YANLIŞ slot
2216
+ // numarası döndürebiliyor (inventoryStart offsetini hesaba katmıyor).
2217
+ // Bunun yerine doğrudan currentWindow.slots üzerinden, gerçek (offsetli)
2218
+ // slot index'ini buluyoruz.
2219
+ const invStart = bot.currentWindow.inventoryStart;
2220
+ const winSlots = bot.currentWindow.slots;
2221
+ let realSlotIndex = -1;
2222
+
2223
+ for (let i = invStart; i < winSlots.length; i++) {
2224
+ if (winSlots[i] && winSlots[i].name === itemInternalName) {
2225
+ realSlotIndex = i;
2226
+ break;
2227
+ }
2228
+ }
2229
+
2230
+ if (realSlotIndex === -1) { keepGoing = false; break; }
2231
+
2232
+ if (stuckSlot === realSlotIndex) {
2233
+ stuckSlotRepeatCount++;
2234
+ if (stuckSlotRepeatCount >= 3) {
2235
+ logger.warn(`[Sipariş] Slot ${realSlotIndex} 3 kez üst üste taşınamadı (Teslim Etme dolu/limitli olabilir), aktarım durduruluyor.`);
2236
+ keepGoing = false;
2237
+ break;
2238
+ }
2239
+ } else {
2240
+ stuckSlot = realSlotIndex;
2241
+ stuckSlotRepeatCount = 0;
2242
+ }
2243
+
2244
+ try {
2245
+ await bot.clickWindow(realSlotIndex, 0, 1); // mouseButton=0 (sol), mode=1 (shift)
2246
+ await new Promise(r => setTimeout(r, 1000 + Math.floor(Math.random() * 200)));
2247
+
2248
+ const stillThere = bot.currentWindow.slots[realSlotIndex];
2249
+ if (!stillThere || stillThere.name !== itemInternalName) {
2250
+ transferredCount++;
2251
+ } else {
2252
+ logger.warn(`[Sipariş] Slot ${realSlotIndex} tıklandı ama item hâlâ envanterde, taşınmamış olabilir.`);
2253
+ }
2254
+ } catch (e) {
2255
+ logger.error(`[Sipariş] Envanterden aktarım tıklaması hatası: ${e && e.message ? e.message : e}`);
2256
+ keepGoing = false;
2257
+ }
2258
+ }
2259
+
2260
+ if (safetyCounter >= 40) {
2261
+ logger.warn(`[Sipariş] Güvenlik limitine (40 deneme) ulaşıldı. Teslim Etme kutusu dolu/limitli olabilir, transfer yarım kalmış olabilir.`);
2262
+ }
2263
+
2264
+ // --- 9) Pencereyi önce kapat, sonra sayım yap (pencere açıkken bot.inventory.items()
2265
+ // yanlış slot offseti hesaplayabildiği için, güvenilir sayım için kapanmasını bekliyoruz) ---
2266
+ try { if (bot.currentWindow) bot.closeWindow(bot.currentWindow); } catch (e) {}
2267
+ ciftciWindowPurpose = "sell"; // akış tamamen bitti, artık normal davranışa dön
2268
+
2269
+ await new Promise(r => setTimeout(r, 300)); // pencere kapanışının client tarafında senkronize olmasını bekle
2270
+
2271
+ const remainingAfterTransfer = bot.inventory.items()
2272
+ .filter(it => it && it.name === itemInternalName)
2273
+ .reduce((sum, it) => sum + (it.count || 0), 0);
2274
+
2275
+ const stoppedReason = safetyCounter >= 40
2276
+ ? "güvenlik limiti (40 deneme)"
2277
+ : (remainingAfterTransfer > 0 ? "Teslim Etme dolu/limitli olabilir" : "envanter boşaldı");
2278
+
2279
+ logger.info(
2280
+ `[Sipariş] Envanterden Teslim Etme'ye aktarım tamamlandı: ` +
2281
+ `${transferredCount} yığın (stack) gönderildi, ` +
2282
+ `envanterde '${itemInternalName}' kaldı: ${remainingAfterTransfer} adet ` +
2283
+ `(durma sebebi: ${stoppedReason}).`
2284
+ );
2285
+
2286
+
2287
+ return {
2288
+ success: transferredCount > 0,
2289
+ message: transferredCount > 0 ? "Sipariş işlemi tamamlandı." : "Hiçbir yığın Teslim Etme'ye aktarılamadı.",
2290
+ item: itemInternalName,
2291
+ nick,
2292
+ withdrawn_from_ciftci: withdrawnCount,
2293
+ inventory_transferred_batches: transferredCount,
2294
+ remaining_in_inventory: remainingAfterTransfer
2295
+ };
2296
+ }
2297
+
2298
+ async function processOrderManual(itemInternalName, nick) {
2299
+ logger.info(`[Sipariş - Manuel] Panelden istek geldi (item:${itemInternalName}, nick:${nick}), sırasını bekliyor (öncelikli)...`);
2300
+ await guiMutex.acquire();
2301
+ try {
2302
+ logger.info("[Sipariş - Manuel] Kilit alındı, işlem başlıyor.");
2303
+ const result = await processOrderCore(itemInternalName, nick);
2304
+ lastOrderTimeStr = `${getExtendedDateTimeString()} (item:${itemInternalName}, nick:${nick}, sonuç:${result.success ? "başarılı" : "başarısız"})`;
2305
+ return result;
2306
+ } catch (err) {
2307
+ logger.error(`[processOrderManual Hatası] ${err && err.stack ? err.stack : err}`);
2308
+ return { success: false, message: "Beklenmeyen bir hata oluştu." };
2309
+ } finally {
2310
+ guiMutex.release();
2311
+ }
2312
+ }
2313
+
2314
  function startStorageScanPeriodic() {
2315
  if (storageScanIntervalHandle) return;
2316
  storageScanIntervalHandle = setInterval(() => {
 
2319
  scanStorageInfo();
2320
  }, STORAGE_SCAN_INTERVAL_MS);
2321
  logger.info(`[Storage Tarama] Bağımsız döngü başlatıldı (her ${formatDurationMs(STORAGE_SCAN_INTERVAL_MS)}).`);
 
2322
  setSafeTimeout(() => { scanStorageInfo(); }, 30 * 1000);
2323
  }
2324
 
 
2403
  botActions.antiBotMove = antiBotMove;
2404
  botActions.sendMoneyToNick = sendMoneyToNick;
2405
  botActions.scanStorageInfoManual = scanStorageInfoManual;
2406
+ botActions.processOrderManual = processOrderManual;
2407
 
2408
  startKaziciPeriodic();
2409
  startCiftciPeriodic();
 
2474
  (matchesAnyName(titleRaw, TARGET_CIFTCI_NORMS) || windowMatchesLoreKeyword(window, CIFTCI_LORE_FALLBACK_KEYWORDS));
2475
 
2476
  if (!isBesleyiciWindow && !isKaziciWindow && !isCiftciWindow) {
2477
+ if (ciftciWindowPurpose === "order") {
2478
+ logger.info(`[${currentBotUsername}] Sipariş (/order) penceresi açıldı: ${titleRaw}`);
2479
+ } else {
2480
+ logger.info(`[${currentBotUsername}] Bi chest açıldı ama window title ı uyuşmadığı için kapatıldı. ${titleRaw}`);
2481
+ try { bot.closeWindow(window); } catch(e){}
2482
+ return;
2483
+ }
2484
+ } else if (isKaziciWindow) {
2485
  try {
2486
  logger.info(`[${currentBotUsername}] Kazıcı minyon paneli açıldı. Depo aktarım slotuna (oyun içi 18. slot / mineflayer idx ${KAZICI_STORAGE_TRANSFER_SLOT}) tıklanıyor...`);
2487
  await bot.clickWindow(KAZICI_STORAGE_TRANSFER_SLOT, 0, 0);
 
2494
  try { bot.closeWindow(window); } catch(e){}
2495
 
2496
  } else if (isCiftciWindow) {
2497
+ if (ciftciWindowPurpose === "scan" || ciftciWindowPurpose === "order") {
2498
+ // Storage tarama / sipariş modu: burada otomatik tıklama/kapatma yapma,
2499
+ // ilgili core fonksiyon kendi akışını yönetiyor. Sadece resolver'ı tetikle.
2500
  } else {
2501
  try {
2502
  logger.info(`[${currentBotUsername}] Çiftçi (Hepsini Sat) menüsü açıldı. ${formatDurationMs(CIFTCI_CLICK_DELAY_AFTER_OPEN_MS)} bekleniyor, sonra slot ${CIFTCI_SELL_ALL_SLOT}'e ${CIFTCI_CLICK_REPEAT_COUNT} kez tıklanacak...`);
 
2579
  }
2580
  });
2581
 
2582
+
2583
  bot.on("end", () => {
2584
  try {
2585
  logger.warn(manualStopRequested ? "Bağlantı koptu. Manuel durdurma istendiği için yeniden bağlanılmayacak." : "Bağlantı koptu. Tüm zamanlayıcılar sıfırlanıyor ve YENİDEN BAĞLANMA SÜRECİ BAŞLIYOR...");
 
2604
  botActions.antiBotMove = null;
2605
  botActions.sendMoneyToNick = null;
2606
  botActions.scanStorageInfoManual = null;
2607
+ botActions.processOrderManual = null;
2608
 
2609
  safeDestroyAllConnections();
2610
 
 
2686
  }, delay);
2687
  }
2688
 
 
2689
  let pendingHardRestartTimeout = null;
2690
 
2691
  function stopBotHard(reason) {
 
2872
  next_kazici_check: nextKaziciTimeStr,
2873
  last_ciftci_sell: lastCiftciSellTimeStr,
2874
  next_ciftci_sell: nextCiftciTimeStr,
2875
+ last_order: lastOrderTimeStr,
2876
  gui_lock_busy: guiMutex.isLocked(),
2877
  manually_stopped: manualStopRequested,
2878
  is_connecting: isConnecting,
 
2889
  });
2890
  });
2891
 
 
2892
  app.get("/bot/stop", (req, res) => {
2893
  stopBotHard("Web paneli üzerinden /bot/stop isteği");
2894
  res.send({ success: true, message: "Bot durduruldu. Tekrar başlatmak için /bot/start kullan." });
 
3013
  });
3014
  });
3015
 
3016
+ app.get("/bot/order", (req, res) => {
3017
+ if (!bot || !botIsReady || !botActions.processOrderManual) {
3018
+ return res.status(503).send({ success: false, message: "Bot hazır değil." });
3019
+ }
3020
+
3021
+ const item = req.query.item;
3022
+ const nick = req.query.nick;
3023
+
3024
+ if (!item || typeof item !== "string" || !ORDER_ALLOWED_ITEMS.includes(item)) {
3025
+ return res.status(400).send({ success: false, message: `item query parametresi zorunlu ve şunlardan biri olmalı: ${ORDER_ALLOWED_ITEMS.join(", ")}` });
3026
+ }
3027
+ if (!nick || typeof nick !== "string" || nick.trim().length === 0) {
3028
+ return res.status(400).send({ success: false, message: "nick query parametresi zorunlu." });
3029
+ }
3030
+
3031
+ res.send({ success: true, message: "Sipariş işlemi öncelikli olarak kuyruğa alındı, işleniyor." });
3032
+ botActions.processOrderManual(item, nick)
3033
+ .catch(e => logger.error(`[/bot/order Hatası] ${e && e.stack ? e.stack : e}`));
3034
+ });
3035
+
3036
  app.get("/", (req, res) => res.send("Bot Aktif"));
3037
 
3038
  app.get("/messages", (req, res) => {
 
3268
  return true;
3269
  }
3270
  return originalStderrWrite.apply(process.stderr, arguments);
3271
+ };