-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutoManager.py
More file actions
526 lines (467 loc) · 19.7 KB
/
Copy pathAutoManager.py
File metadata and controls
526 lines (467 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
from phBot import *
import QtBind
import json
import os
import time
from datetime import datetime
# Global variables
config = {}
last_check_time = 0
is_processing = False
town_step = 0
in_game = False
in_game_since = 0
first_join_in_town = False
plugin_name = "AutoManager"
log_file_path = os.path.join(os.path.dirname(__file__), "AutoManager_Log.txt")
# Items to NEVER sell - Built-in list!
NEVER_SELL_KEYWORDS = [
"hp", "mp", "potion", "vigor", "scroll", "return", "repair", "speed",
"rare", "legend", "nova", "soul", "stone", "gem", "ring", "necklace",
"earring", "belt", "guardian", "devil", "angel"
]
# Default config - exactly as requested
DEFAULT_CONFIG = {
"enabled": True,
"check_interval": 20,
"inventory_free_slots": 5,
"pet_free_slots": 2,
"durability_threshold": 10, # Only return when durability is RED (10% or less)
"enable_low_durability": True,
"enable_inventory_check": True,
"enable_pet_check": True,
"sell_normal_items": True,
"repair_equipment": True,
"buy_return_scrolls": True,
"return_scroll_target": 50,
"return_scroll_buy_method": "npc",
"buy_repair_scrolls": True,
"repair_scroll_target": 50,
"repair_scroll_buy_method": "npc",
"buy_speed_scrolls": True,
"speed_scroll_target": 50,
"speed_scroll_buy_method": "npc",
"use_repair_scroll": True,
"return_to_town_method": "scroll",
"return_to_training_method": "reverse"
}
# Initialize UI
gui = QtBind.init(__name__, plugin_name)
# Create UI Elements
QtBind.createLabel(gui, "AutoManager - Auto Town Plugin", 10, 10)
# --- Left Column ---
QtBind.createLabel(gui, "--- Main & Checks ---", 10, 40)
chk_enabled = QtBind.createCheckBox(gui, "toggle_enabled", "Enable Plugin", 10, 60)
chk_inv = QtBind.createCheckBox(gui, "toggle_inv_check", "Check Inventory", 10, 85)
chk_pet = QtBind.createCheckBox(gui, "toggle_pet_check", "Check Pet", 10, 110)
chk_dur = QtBind.createCheckBox(gui, "toggle_dur_check", "Check Durability", 10, 135)
chk_repair_scroll_use = QtBind.createCheckBox(gui, "toggle_repair_scroll_use", "Use Repair Scroll First", 10, 160)
# --- Right Column ---
QtBind.createLabel(gui, "--- Town Actions ---", 220, 40)
chk_sell = QtBind.createCheckBox(gui, "toggle_sell", "Sell Normal Items", 220, 60)
chk_repair = QtBind.createCheckBox(gui, "toggle_repair", "Repair Equip", 220, 85)
# Buy Scrolls
chk_buy_return = QtBind.createCheckBox(gui, "toggle_buy_return", "Buy Return Scrolls", 220, 110)
QtBind.createLabel(gui, "Target:", 350, 112)
le_return_target = QtBind.createLineEdit(gui, "50", 395, 110, 40, 20)
cb_return_buy = QtBind.createCombobox(gui, 445, 108, 60, 20)
QtBind.append(gui, cb_return_buy, "NPC")
QtBind.append(gui, cb_return_buy, "F10")
chk_buy_repair = QtBind.createCheckBox(gui, "toggle_buy_repair", "Buy Repair Scrolls", 220, 135)
QtBind.createLabel(gui, "Target:", 350, 137)
le_repair_target = QtBind.createLineEdit(gui, "50", 395, 135, 40, 20)
cb_repair_buy = QtBind.createCombobox(gui, 445, 133, 60, 20)
QtBind.append(gui, cb_repair_buy, "NPC")
QtBind.append(gui, cb_repair_buy, "F10")
chk_buy_speed = QtBind.createCheckBox(gui, "toggle_buy_speed", "Buy Speed Scrolls", 220, 160)
QtBind.createLabel(gui, "Target:", 350, 162)
le_speed_target = QtBind.createLineEdit(gui, "50", 395, 160, 40, 20)
cb_speed_buy = QtBind.createCombobox(gui, 445, 158, 60, 20)
QtBind.append(gui, cb_speed_buy, "NPC")
QtBind.append(gui, cb_speed_buy, "F10")
# Movement
QtBind.createLabel(gui, "--- Movement ---", 220, 190)
QtBind.createLabel(gui, "Return to Town:", 220, 215)
cb_return_town = QtBind.createCombobox(gui, 320, 213, 120, 20)
QtBind.append(gui, cb_return_town, "Return Scroll")
QtBind.append(gui, cb_return_town, "F10 - Town")
QtBind.append(gui, cb_return_town, "Walk")
QtBind.createLabel(gui, "Return to Training:", 220, 240)
cb_return_train = QtBind.createCombobox(gui, 320, 238, 120, 20)
QtBind.append(gui, cb_return_train, "Reverse Return")
QtBind.append(gui, cb_return_train, "Walk")
# Save Button
QtBind.createButton(gui, "save_settings", "Save Settings", 10, 270)
# --- Logging Function to File ---
def write_log(message):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_message = f"[{timestamp}] {message}"
log(f"[{plugin_name}] {message}")
try:
with open(log_file_path, "a", encoding="utf-8") as f:
f.write(log_message + "\n")
except Exception as e:
print(f"Failed to write log: {e}")
# --- Config Functions ---
def load_config():
global config
config_path = os.path.join(os.path.dirname(__file__), "config.json")
try:
if os.path.exists(config_path):
with open(config_path, "r", encoding="utf-8") as f:
config = json.load(f)
for key, value in DEFAULT_CONFIG.items():
if key not in config:
config[key] = value
else:
config = DEFAULT_CONFIG.copy()
save_config()
except Exception:
config = DEFAULT_CONFIG.copy()
update_ui()
write_log(f"Config loaded successfully. Log file at: {log_file_path}")
write_log(f"Items that will NEVER be sold: {', '.join(NEVER_SELL_KEYWORDS)}")
def save_config():
config_path = os.path.join(os.path.dirname(__file__), "config.json")
try:
with open(config_path, "w", encoding="utf-8") as f:
json.dump(config, f, indent=2, ensure_ascii=False)
except Exception:
pass
def update_ui():
QtBind.setChecked(gui, chk_enabled, config.get("enabled", True))
QtBind.setChecked(gui, chk_inv, config.get("enable_inventory_check", True))
QtBind.setChecked(gui, chk_pet, config.get("enable_pet_check", True))
QtBind.setChecked(gui, chk_dur, config.get("enable_low_durability", True))
QtBind.setChecked(gui, chk_repair_scroll_use, config.get("use_repair_scroll", True))
QtBind.setChecked(gui, chk_sell, config.get("sell_normal_items", True))
QtBind.setChecked(gui, chk_repair, config.get("repair_equipment", True))
QtBind.setChecked(gui, chk_buy_return, config.get("buy_return_scrolls", True))
QtBind.setChecked(gui, chk_buy_repair, config.get("buy_repair_scrolls", True))
QtBind.setChecked(gui, chk_buy_speed, config.get("buy_speed_scrolls", True))
QtBind.setText(gui, le_return_target, str(config.get("return_scroll_target", 50)))
QtBind.setText(gui, le_repair_target, str(config.get("repair_scroll_target", 50)))
QtBind.setText(gui, le_speed_target, str(config.get("speed_scroll_target", 50)))
# --- UI Callbacks ---
def toggle_enabled(checked):
global config
config["enabled"] = checked
write_log(f"Plugin {'enabled' if checked else 'disabled'}!")
def toggle_inv_check(checked): config["enable_inventory_check"] = checked
def toggle_pet_check(checked): config["enable_pet_check"] = checked
def toggle_dur_check(checked): config["enable_low_durability"] = checked
def toggle_repair_scroll_use(checked): config["use_repair_scroll"] = checked
def toggle_sell(checked): config["sell_normal_items"] = checked
def toggle_repair(checked): config["repair_equipment"] = checked
def toggle_buy_return(checked): config["buy_return_scrolls"] = checked
def toggle_buy_repair(checked): config["buy_repair_scrolls"] = checked
def toggle_buy_speed(checked): config["buy_speed_scrolls"] = checked
def save_settings():
global config
try:
config["return_scroll_target"] = int(QtBind.text(gui, le_return_target)) if QtBind.text(gui, le_return_target).isdigit() else 50
config["repair_scroll_target"] = int(QtBind.text(gui, le_repair_target)) if QtBind.text(gui, le_repair_target).isdigit() else 50
config["speed_scroll_target"] = int(QtBind.text(gui, le_speed_target)) if QtBind.text(gui, le_speed_target).isdigit() else 50
config["return_scroll_buy_method"] = "npc" if QtBind.text(gui, cb_return_buy) == "NPC" else "f10"
config["repair_scroll_buy_method"] = "npc" if QtBind.text(gui, cb_repair_buy) == "NPC" else "f10"
config["speed_scroll_buy_method"] = "npc" if QtBind.text(gui, cb_speed_buy) == "NPC" else "f10"
return_town_text = QtBind.text(gui, cb_return_town)
if "F10" in return_town_text:
config["return_to_town_method"] = "f10"
elif "Walk" in return_town_text:
config["return_to_town_method"] = "walk"
else:
config["return_to_town_method"] = "scroll"
config["return_to_training_method"] = "reverse" if "Reverse" in QtBind.text(gui, cb_return_train) else "walk"
save_config()
write_log("Settings saved successfully!")
except Exception as e:
write_log(f"Error saving settings: {e}")
# --- Helper Functions ---
def count_free_inventory_slots():
try:
inv = get_inventory()
write_log(f"Debug - Full inventory data received: {type(inv)}, keys: {list(inv.keys() if inv else [])}")
if inv and "items" in inv:
items = inv["items"]
free = 0
item_list = []
for i, slot in enumerate(items):
if slot is None or not slot:
free += 1
else:
name = slot.get('name', 'Unknown')
servername = slot.get('servername', 'Unknown')
should_keep = False
for keyword in NEVER_SELL_KEYWORDS:
if keyword in name.lower() or keyword in servername.lower():
should_keep = True
break
item_list.append(f"Slot {i}: {name} (keep: {should_keep})")
write_log(f"Items in inventory: {'; '.join(item_list)}")
write_log(f"Inventory free slots: {free}")
return free
write_log("Failed to get inventory items!")
return -1
except Exception as e:
write_log(f"Error counting inventory slots: {e}")
import traceback
write_log(f"Traceback: {traceback.format_exc()}")
return -1
def count_free_pet_slots():
try:
pets = get_pets()
write_log(f"Debug - Full pets data received: {pets}")
if pets:
for pet_id, pet_data in pets.items():
if "items" in pet_data:
items = pet_data["items"]
free = 0
item_list = []
for i, slot in enumerate(items):
if slot is None or not slot:
free += 1
else:
name = slot.get('name', 'Unknown')
should_keep = False
for keyword in NEVER_SELL_KEYWORDS:
if keyword in name.lower():
should_keep = True
break
item_list.append(f"Pet Slot {i}: {name} (keep: {should_keep})")
write_log(f"Items in pet inventory: {'; '.join(item_list)}")
write_log(f"Pet inventory free slots: {free}")
return free
write_log("No pet found, defaulting to 10 free slots")
return 10
except Exception as e:
write_log(f"Error counting pet slots: {e}")
import traceback
write_log(f"Traceback: {traceback.format_exc()}")
return 10
def count_scrolls(keyword):
try:
inv = get_inventory()
count = 0
if inv and "items" in inv:
for item in inv["items"]:
if item:
name = item.get("name", "").lower()
servername = item.get("servername", "").lower()
if keyword in name or keyword in servername:
count += item.get("quantity", 1)
write_log(f"{keyword.capitalize()} scrolls count: {count}")
return count
except Exception as e:
write_log(f"Error counting {keyword} scrolls: {e}")
return 999
def use_scroll(keyword):
try:
inv = get_inventory()
if inv and "items" in inv:
for i, item in enumerate(inv["items"]):
if item:
name = item.get("name", "").lower()
servername = item.get("servername", "").lower()
if keyword in name or keyword in servername:
use_item(i)
write_log(f"Used {keyword} scroll!")
return True
return False
except Exception as e:
write_log(f"Error using {keyword} scroll: {e}")
return False
def check_low_durability():
try:
inv = get_inventory()
if inv and "items" in inv:
for item in inv["items"]:
if item and "durability" in item and item["durability"] > 0:
durability = item["durability"]
item_name = item.get("name", "Unknown")
write_log(f"Item: {item_name}, Durability: {durability}%")
if durability <= 10:
write_log(f"CRITICAL: {item_name} durability is {durability}% (RED)!")
return True
return False
except Exception as e:
write_log(f"Error checking durability: {e}")
return False
def is_in_town():
try:
char_data = get_character_data()
if char_data and "region" in char_data:
zone_name = get_zone_name(char_data["region"])
towns = ["Jangan", "Donwhang", "Hotan", "Samarkand", "Constantinople", "Alexandria"]
in_town_flag = zone_name in towns
write_log(f"Current zone: {zone_name}, In town: {in_town_flag}")
return in_town_flag
return False
except Exception as e:
write_log(f"Error checking town: {e}")
return False
def has_speed_buff():
try:
active_skills = get_active_skills()
if active_skills:
for skill_id, skill_data in active_skills.items():
name = skill_data.get("name", "").lower()
if "speed" in name or "move" in name:
return True
return False
except Exception:
return False
# --- Process Functions ---
def start_town_process():
global is_processing, town_step
if is_processing or is_in_town():
return
is_processing = True
town_step = 0
stop_bot()
write_log("Starting town process...")
if not has_speed_buff():
use_scroll("speed")
method = config.get("return_to_town_method", "scroll")
if method == "scroll":
use_return_scroll()
elif method == "f10":
town()
def run_town_script():
global town_step
write_log("Running town script...")
script = ["wait,5000"]
if config.get("repair_equipment", True):
script.append("DoBlacksmith")
script.append("wait,10000")
if config.get("sell_normal_items", True):
script.append("DoGroceryTrader")
script.append("wait,10000")
if config.get("buy_return_scrolls", True) or config.get("buy_repair_scrolls", True) or config.get("buy_speed_scrolls", True):
script.append("DoGroceryTrader")
script.append("wait,10000")
script.append("wait,3000")
full_script = "\n".join(script)
write_log(f"Town script:\n{full_script}")
start_script(full_script)
town_step = 2
def return_to_training():
global is_processing, town_step
write_log("Returning to training area...")
if not has_speed_buff():
use_scroll("speed")
if config.get("return_to_training_method", "reverse") == "reverse":
reverse_return(0, "")
time.sleep(5)
is_processing = False
town_step = 0
write_log("Starting bot...")
start_bot()
# --- Game Events ---
def joined_game():
global in_game, in_game_since, first_join_in_town
load_config()
in_game = True
in_game_since = time.time()
first_join_in_town = is_in_town()
if first_join_in_town:
write_log("Character joined in TOWN! Will process town tasks after 15 seconds...")
else:
write_log("Character joined in TRAINING AREA! Waiting 45 seconds before starting checks...")
def disconnected():
global in_game, is_processing, town_step, in_game_since, first_join_in_town
in_game = False
in_game_since = 0
first_join_in_town = False
is_processing = False
town_step = 0
write_log("Disconnected! Resetting state.")
def teleported():
global is_processing, town_step, in_game
if not in_game:
return
write_log("Teleported successfully!")
if is_processing and town_step == 0 and is_in_town():
town_step = 1
time.sleep(2)
run_town_script()
# --- Main Event Loop ---
def event_loop():
global last_check_time, is_processing, town_step, in_game, in_game_since, first_join_in_town
# --- 1. Check if Plugin is Disabled ---
if not config.get("enabled", True):
return
# --- 2. Check if Not In Game ---
if not in_game:
return
# --- 3. Check if First Join In Town ---
if first_join_in_town and not is_processing:
if (time.time() - in_game_since) > 15: # Wait 15 sec after joining in town
write_log("First join in town: Starting town tasks...")
is_processing = True
town_step = 1
run_town_script()
first_join_in_town = False # Mark as done
return
# --- 4. Check if Still Waiting After Join ---
if (time.time() - in_game_since) < 45:
return
# --- 5. Check if In Town And Not Processing ---
if is_in_town() and not is_processing:
return
# --- 6. Normal Processing ---
now = time.time()
interval = config.get("check_interval", 20)
if now - last_check_time < interval and not is_processing:
return
last_check_time = now
if is_processing:
if town_step == 0 and is_in_town():
town_step = 1
time.sleep(2)
run_town_script()
elif town_step == 2:
return_to_training()
return
# --- Check Durability ---
if config.get("enable_low_durability", True):
if check_low_durability():
if config.get("use_repair_scroll", True) and count_scrolls("repair") > 0:
if use_scroll("repair"):
return
write_log("Returning to town due to LOW DURABILITY (RED)")
start_town_process()
return
# --- Check Inventory ---
if config.get("enable_inventory_check", True):
free = count_free_inventory_slots()
if free != -1 and free <= config.get("inventory_free_slots", 5):
write_log(f"Returning to town due to INVENTORY FULL (Free slots: {free})")
start_town_process()
return
# --- Check Pet ---
if config.get("enable_pet_check", True):
free = count_free_pet_slots()
if free <= config.get("pet_free_slots", 2):
write_log(f"Returning to town due to PET INVENTORY FULL (Free slots: {free})")
start_town_process()
return
# --- Check Scrolls ---
scroll_checks = [
("buy_return_scrolls", "return", "return_scroll_target"),
("buy_repair_scrolls", "repair", "repair_scroll_target"),
("buy_speed_scrolls", "speed", "speed_scroll_target"),
]
for enable_key, keyword, target_key in scroll_checks:
if config.get(enable_key, True):
count = count_scrolls(keyword)
if count <= 5:
write_log(f"Returning to town due to LOW {keyword.upper()} SCROLLS (Count: {count})")
start_town_process()
return
# --- Initialize ---
write_log("=" * 50)
write_log("AutoManager Plugin Starting...")
write_log("=" * 50)
load_config()
write_log("Plugin loaded successfully!")