forked from BrenoHenrike/Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoreBots.cs
More file actions
3294 lines (2887 loc) · 124 KB
/
CoreBots.cs
File metadata and controls
3294 lines (2887 loc) · 124 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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.DependencyInjection;
using Newtonsoft.Json;
using Skua.Core.Interfaces;
using Skua.Core.Models;
using Skua.Core.Models.Items;
using Skua.Core.Models.Monsters;
using Skua.Core.Models.Quests;
using Skua.Core.Models.Servers;
using Skua.Core.Models.Shops;
using Skua.Core.Models.Skills;
using Skua.Core.Options;
using Skua.Core.Utils;
public class CoreBots
{
#region Declerations
// [Can Change] Delay between common actions, 700 is the safe number
public int ActionDelay { get; set; } = 700;
// [Can Change] Delay used to get out of combat, 1600 is the safe number
public int ExitCombatDelay { get; set; } = 1600;
// [Can Change] Delay between jumping rooms after hunting a monster, increase if you think it is jumping too much
public int HuntDelay { get; set; } = 1000;
// [Can Change] How many tries to accept/complete the quest will be sent
public int AcceptandCompleteTries { get; set; } = 20;
// [Can Change] How many quests the bot should be able to have loaded at once
public int LoadedQuestLimit { get; set; } = 150;
// [Can Change] Whether the bots should also log in AQW's chat
public bool LoggerInChat { get; set; } = true;
// [Can Change] When enabled, no message boxes will be shown unless absolutely necessary
public bool ForceOffMessageboxes { get; set; } = false;
// [Can Change] Whether the bots will use private rooms
public bool PrivateRooms { get; set; } = true;
// [Can Change] What private room number the bot should use, if > 99999 it will pick a random room
public int PrivateRoomNumber { get; set; } = 100000;
// [Can Change] Use public rooms if the enemy is tough
public bool PublicDifficult { get; set; } = false;
// [Can Change] If StopLocations.Custom is selected, where to go
public string CustomStopLocation { get; set; } = "whitemap";
// [Can Change] Whether the player should rest after killing a monster
public bool ShouldRest { get; set; } = false;
// [Can Change] Whether the bot should attempt to clean your inventory by banking Misc. AC Items before starting the bot
public bool BankMiscAC { get; set; } = false;
// [Can Change] Whether you want anti lag features (lag killer, invisible monsters, set to 10 FPS)
public bool AntiLag { get; set; } = true;
// [Can Change] Name of your soloing class
public string SoloClass { get; set; } = "Generic";
// [Can Change] Mode of soloing class, if it has multiple.
public ClassUseMode SoloUseMode { get; set; } = ClassUseMode.Base;
// [Can Change] Whether you wish to equip solo equipment
public bool SoloGearOn { get; set; } = true;
// [Can Change] Names of your soloing equipment
public string[] SoloGear { get; set; } = { "Weapon", "Headpiece", "Cape" };
// [Can Change] Name of your farming class
public string FarmClass { get; set; } = "Generic";
// [Can Change] Mode of farming class, if it has multiple.
public ClassUseMode FarmUseMode { get; set; } = ClassUseMode.Base;
// [Can Change] Whether you wish to equip farm equipment
public bool FarmGearOn { get; set; } = true;
// [Can Change] Names of your farming equipment
public string[] FarmGear { get; set; } = { "Weapon", "Headpiece", "Cape" };
// [Can Change] Some Sagas use the hero alignment to give extra reputation, change to your desired rep (Alignment.Evil or Alignment.Good).
public int HeroAlignment { get; set; } = (int)Alignment.Evil;
private static CoreBots _instance;
public static CoreBots Instance => _instance ??= new CoreBots();
private IScriptInterface Bot => IScriptInterface.Instance;
#endregion
#region Start/Stop
/// <summary>
/// Set common bot options to desired value
/// </summary>
/// <param name="changeTo">Value the options will be changed to</param>
public void SetOptions(bool changeTo = true, bool disableClassSwap = false)
{
if (changeTo)
{
Bot.Events.ScriptStopping += CrashDetector;
if (Bot.Config != null && Bot.Config.Options.Contains(SkipOptions) && !Bot.Config.Get<bool>(SkipOptions))
Bot.Config.Configure();
if (CBO_Active())
{
CBOList = File.ReadAllLines(AppPath + $@"\options\CBO_Storage({Username()}).txt").ToList();
ReadCBO();
}
if (AppPath != null)
{
loadedBot = Bot.Manager.LoadedScript.Replace(AppPath, string.Empty).Replace("\\Scripts\\", "").Replace(".cs", "");
Logger($"Bot Started [{loadedBot}]");
}
else Logger($"Bot Started");
SkuaVersionChecker("1.1.1.0");
if (Directory.Exists("options/Butler"))
{
if (File.Exists($"options/Butler/{Username().ToLower()}.txt"))
File.Delete($"options/Butler/{Username().ToLower()}.txt");
string[] files = Directory.GetFiles("options/Butler");
if (files.Any(x => x.Contains("~!") && x.Split("~!").First() == Username().ToLower()))
File.Delete(files.First(x => x.Contains("~!") && x.Split("~!").First() == Username().ToLower()));
}
if (!Bot.Player.LoggedIn)
{
if (Bot.Servers.CachedServers.Count() > 0)
{
Logger("Auto Login triggered");
if (!Bot.Servers.EnsureRelogin(Bot.Options.ReloginServer ?? Bot.Servers.CachedServers[0].Name))
Logger("Please log-in before starting the bot.\nIf you are already logged in but are receiving this message regardless, please re-install CleanFlash", messageBox: true, stopBot: true);
Bot.Sleep(5000);
}
else Logger("Please log-in before starting the bot.\nIf you are already logged in but are receiving this message regardless, please re-install CleanFlash", messageBox: true, stopBot: true);
}
IsMember = Bot.Player.IsMember;
ReadMe();
UpdateSkills();
}
// Common Options
Bot.Options.PrivateRooms = false;
Bot.Options.SafeTimings = changeTo;
Bot.Options.RestPackets = changeTo;
Bot.Options.AutoRelogin = changeTo;
Bot.Options.InfiniteRange = changeTo;
Bot.Options.SkipCutscenes = changeTo;
Bot.Options.QuestAcceptAndCompleteTries = AcceptandCompleteTries;
Bot.Drops.RejectElse = changeTo;
Bot.Lite.UntargetDead = changeTo;
Bot.Lite.UntargetSelf = changeTo;
Bot.Lite.ReacceptQuest = false;
Bot.Lite.Set("dOptions[\"disRed\"]", true);
CollectData(changeTo);
if (changeTo)
{
Bot.Options.HuntDelay = HuntDelay;
Bot.Events.ScriptStopping += StopBotEvent;
Bot.Send.Packet("%xt%zm%afk%1%false%");
Bot.Sleep(ActionDelay);
bool TimerRunning = false;
Bot.Handlers.RegisterHandler(5000, b =>
{
if (b.Player.AFK && !TimerRunning)
{
TimerRunning = true;
Bot.Sleep(300000);
if (b.Player.AFK)
{
b.Options.AutoRelogin = true;
b.Servers.Logout();
}
TimerRunning = false;
}
}, "AFK Handler");
Bot.Handlers.RegisterHandler(3000, b =>
{
if (Bot.Quests.Tree.Count() > LoadedQuestLimit)
{
Bot.Flash.SetGameObject("world.questTree", new ExpandoObject());
}
}, "Quest-Limit Handler");
if (loadedBot != "Tools/Butler")
{
Bot.Events.MapChanged += PrisonDetector;
void PrisonDetector(string map)
{
if (map.ToLower() == "prison" && !joinedPrison && !prisonListernerActive)
{
prisonListernerActive = true;
Bot.Options.AutoRelogin = false;
Bot.Servers.Logout();
string message = "You were teleported to /prison by someone other than the bot. We disconnected you and stopped the bot out of precaution.\n" +
"Be ware that you might have received a ban, as this is a method moderators use to see if you're botting." +
(!PrivateRooms || PrivateRoomNumber < 1000 || PublicDifficult ? "\nGuess you should have stayed out of public rooms!" : String.Empty);
Logger(message);
Bot.ShowMessageBox(message, "Unauthorized joining of /prison detected!", "Oh fuck!");
Bot.Stop(true);
}
}
}
Bot.Bank.Load();
Bot.Bank.Loaded = true;
if (BankMiscAC)
{
List<string> Whitelisted = new() { "Note", "Item", "Resource", "QuestItem" };
List<string> WhitelistedSU = new() { "Note", "Item", "Resource", "QuestItem", "ServerUse" };
List<string> MiscForBank = new();
bool boostsEnabled = Bot.Boosts.Enabled || (CBO_Active() && (
(CBOBool("doGoldBoost", out bool _doGoldBoost) && _doGoldBoost) ||
(CBOBool("doClassBoost", out bool _doClassBoost) && _doClassBoost) ||
(CBOBool("doRepBoost", out bool _doRepBoost) && _doRepBoost) ||
(CBOBool("doExpBoost", out bool _doExpBoost) && _doExpBoost)));
foreach (var item in Bot.Inventory.Items)
{
if (boostsEnabled ? !Whitelisted.Contains(item.Category.ToString()) : !WhitelistedSU.Contains(item.Category.ToString()))
continue;
if (item.Name != "Treasure Potion" && !BankingBlackList.Contains(item.Name) && item.Coins)
MiscForBank.Add(item.Name);
}
ToBank(MiscForBank.ToArray());
}
foreach (InventoryItem item in Bot.Inventory.Items.Where(i => i.Equipped))
EquipmentBeforeBot.Add(item.Name);
usingSoloGeneric = SoloClass.ToLower() == "generic";
usingFarmGeneric = FarmClass.ToLower() == "generic";
if (disableClassSwap)
usingSoloGeneric = true;
EquipClass(ClassType.Solo);
// Anti-lag option
if (AntiLag)
{
Bot.Options.LagKiller = true;
Bot.Flash.SetGameObject("stage.frameRate", 10);
if (!Bot.Flash.GetGameObject<bool>("ui.monsterIcon.redX.visible"))
Bot.Flash.CallGameFunction("world.toggleMonsters");
}
Bot.Options.CustomName = "SKUA BOT";
Bot.Options.CustomGuild = "HTTPS://AUQW.TK/";
Bot.Drops.Start();
Logger("Bot Configured");
}
}
public List<string> BankingBlackList = new();
private List<string> EquipmentBeforeBot = new();
private bool joinedPrison = false;
private bool prisonListernerActive = false;
public string loadedBot = String.Empty;
/// <summary>
/// Stops the bot and moves you back to /Battleon
/// </summary>
private bool StopBot(bool crashed)
{
CancelRegisteredQuests();
SavedState(false);
Bot.Handlers.Clear();
if (Bot.Player.LoggedIn)
{
JumpWait();
Bot.Sleep(ActionDelay);
if (EquipmentBeforeBot.Count() > 0)
Equip(EquipmentBeforeBot.ToArray());
if (!string.IsNullOrWhiteSpace(CustomStopLocation))
{
if (CustomStopLocation.Trim().ToLower() == "home")
{
if (Bot.House.Items.Count(h => h.Equipped) > 0)
Bot.Send.Packet($"%xt%zm%house%1%{Username()}%");
else
SendPackets($"%xt%zm%cmd%1%tfer%{Username()}%whitemap-{PrivateRoomNumber}%");
}
else if (new[] { "off", "disabled", "disable", "stop", "same", "currentmap", "bot.map.currentmap", String.Empty }
.Any(m => m.ToLower() == CustomStopLocation.ToLower())) { }
else
Bot.Send.Packet($"%xt%zm%cmd%1%tfer%{Username()}%{CustomStopLocation.ToLower()}-{PrivateRoomNumber}%");
}
}
if (AntiLag)
{
Bot.Flash.SetGameObject("stage.frameRate", 60);
if (Bot.Flash.GetGameObject<bool>("ui.monsterIcon.redX.visible"))
Bot.Flash.CallGameFunction("world.toggleMonsters");
}
Bot.Options.CustomName = Username().ToUpper();
string guild = Bot.Flash.GetGameObject<string>("world.myAvatar.objData.guild.Name");
Bot.Options.CustomGuild = guild != null ? $"< {guild} >" : "";
if (File.Exists($"options/Butler/{Username().ToLower()}.txt"))
File.Delete($"options/Butler/{Username().ToLower()}.txt");
if (crashed)
Logger("Bot Stopped due to crash.");
else if (!Bot.Player.LoggedIn)
Logger("Auto Relogin appears to have failed.");
else Logger("Bot Stopped Successfully.");
GC.KeepAlive(Instance);
return scriptFinished;
}
private bool scriptFinished = true;
private bool StopBotEvent(Exception e)
{
SetOptions(false);
return StopBot(e != null);
}
private bool CrashDetector(Exception e)
{
if (e == null)
return scriptFinished;
string eSlice = e.Message + "\n" + e.InnerException;
List<string> logs = Ioc.Default.GetRequiredService<ILogService>().GetLogs(LogType.Script);
logs = logs.Skip(logs.Count() > 5 ? (logs.Count() - 5) : logs.Count()).ToList();
if (Bot.ShowMessageBox("A crash has been detected, please fill in the report form (prefilled):\n\n" + eSlice,
"Script Crashed", "Open Form", "Close Window").Text == "Open Form")
{
string url = "\"https://docs.google.com/forms/d/e/1FAIpQLSeI_S99Q7BSKoUCY2O6o04KXF1Yh2uZtLp0ykVKsFD1bwAXUg/viewform?usp=pp_url&" +
"entry.2118425091=Bug+Report&" +
$"entry.290078150={Bot.Manager.LoadedScript.Split("Scripts").Last().Replace('/', '\\').Substring(1).Replace(".cs", "")}&" +
"entry.1803231651=It+stopped+at+the+wrong+time+(crash)&" +
$"entry.1954840906={logs.Join("%0A")}&" +
$"entry.285894207={eSlice}&\"";
url = url.Replace("\r\n", "%0A").Replace("\n", "").Replace(" ", "%20");
Process p = new();
p.StartInfo.FileName = "rundll32";
p.StartInfo.Arguments = "url,OpenURL " + url;
p.StartInfo.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.System).Split('\\').First() + "\\";
p.Start();
Logger("Thank you for reporting the crash. Below you will find the information you will need to report, in case it isn't being auto filled");
}
else Logger("A crash has occurred. Please report it in the form with the details below");
Bot.Log("--------------------------------------");
Logger("Last 5 Logs:");
Bot.Log(logs.Join('\n'));
Bot.Log("--------------------------------------");
Logger("Crash (Debug)");
Bot.Log(eSlice);
Bot.Log("--------------------------------------");
return false;
}
public void ScriptMain(IScriptInterface bot)
{
RunCore();
}
#endregion
#region Inventory, Bank and Shop
#nullable enable
/// <summary>
/// Check the Bank, Inventory and Temp Inventory for the item
/// </summary>
/// <param name="item">Name of the item</param>
/// <param name="quant">Desired quantity</param>
/// <param name="toInv">Whether or not send the item to Inventory</param>
/// <returns>Returns whether the item exists in the desired quantity in the bank and inventory</returns>
public bool CheckInventory(string item, int quant = 1, bool toInv = true)
{
if (Bot.TempInv.Contains(item, quant))
return true;
if (Bot.Inventory.Contains(item, quant))
return true;
if (Bot.Bank.Contains(item))
{
if (toInv)
Unbank(item);
if ((toInv && Bot.Inventory.GetQuantity(item) >= quant) ||
(!toInv && Bot.Bank.TryGetItem(item, out InventoryItem? _item) && _item != null && _item.Quantity >= quant))
return true;
}
if (Bot.House.Contains(item))
return true;
return false;
}
/// <summary>
/// Checks the Bank and Inventory for the item with it's ID
/// </summary>
/// <param name="itemID">ID of the item to verify</param>
/// <param name="quant">Desired quantity</param>
/// <param name="toInv">Whether or not send the item to Inventory</param>
/// <returns>Returns whether the item exists in the desired quantity in the Bank and Inventory</returns>
public bool CheckInventory(int itemID, int quant = 1, bool toInv = true)
{
if (Bot.TempInv.Contains(itemID, quant))
return true;
if (Bot.Inventory.Contains(itemID, quant))
return true;
if (Bot.Bank.Contains(itemID))
{
if (toInv)
Unbank(itemID);
if ((toInv && Bot.Inventory.GetQuantity(itemID) >= quant) ||
(!toInv && Bot.Bank.TryGetItem(itemID, out InventoryItem? _item) && _item != null && _item.Quantity >= quant))
return true;
}
if (Bot.House.Contains(itemID))
return true;
return false;
}
/// <summary>
/// Check if the Bank/Inventory has at least 1 of all listed items
/// </summary>
/// <param name="itemNames">Array of names of the items to be check</param>
/// <param name="toInv">Whether or not send the item to Inventory</param>
/// <param name="any">If any of the items exist, returns true</param>
/// <returns>Returns whether all the items exist in the Bank or Inventory</returns>
public bool CheckInventory(string[] itemNames, int quant = 1, bool any = false, bool toInv = true)
{
if (itemNames == null)
return true;
foreach (string name in itemNames)
{
if (CheckInventory(name, quant, toInv))
{
if (any)
return true;
else
continue;
}
if (!any)
return false;
}
return !any;
}
public bool CheckInventory(int[] itemIDs, int quant = 1, bool any = false, bool toInv = true)
{
if (itemIDs == null)
return true;
foreach (int id in itemIDs)
{
if (CheckInventory(id, quant, toInv))
{
if (any)
return true;
else
continue;
}
if (!any)
return false;
}
return !any;
}
public void CheckSpaces(ref int counter, params string[] items)
{
int count = 0;
foreach (string s in items)
{
if (CheckInventory(s, toInv: false))
count++;
}
if (Bot.Inventory.FreeSlots < (items.Count() - count))
Logger($"Not enough free slots, please clear {(items.Count() - count)} slot" + ((items.Count() - count) > 1 ? "s" : ""), messageBox: true, stopBot: true);
}
/// <summary>
/// Move items from bank to inventory
/// </summary>
/// <param name="items">Items to move</param>
public void Unbank(params string[] items)
{
if (items == null)
return;
JumpWait();
if (Bot.Flash.GetGameObject("ui.mcPopup.currentLabel") != "Bank")
Bot.Bank.Open();
foreach (string item in items)
{
if (Bot.Bank.Contains(item))
{
Bot.Sleep(ActionDelay);
if (Bot.Inventory.FreeSlots == 0)
Logger("Your inventory is full, please clean it and restart the bot", messageBox: true, stopBot: true);
if (!Bot.Bank.EnsureToInventory(item))
{
Logger($"Failed to unbank {item}, skipping it", messageBox: true);
continue;
}
Logger($"{item} moved from bank");
}
}
}
/// <summary>
/// Move items from bank to inventory
/// </summary>
/// <param name="items">Items to move</param>
public void Unbank(params int[] items)
{
if (items == null)
return;
JumpWait();
if (Bot.Flash.GetGameObject("ui.mcPopup.currentLabel") != "Bank")
Bot.Bank.Open();
foreach (int item in items)
{
if (Bot.Bank.Contains(item))
{
Bot.Sleep(ActionDelay);
if (Bot.Inventory.FreeSlots == 0)
Logger("Your inventory is full, please clean it and restart the bot", messageBox: true, stopBot: true);
if (!Bot.Bank.EnsureToInventory(item))
{
Logger($"Failed to unbank {item}, skipping it", messageBox: true);
continue;
}
Logger($"{Bot.Inventory.GetItem(item)?.Name ?? item.ToString()} moved from bank");
}
}
}
/// <summary>
/// Move items from inventory to bank
/// </summary>
/// <param name="items">Items to move</param>
public void ToBank(params string[] items)
{
if (items == null)
return;
JumpWait();
if (Bot.Flash.GetGameObject("ui.mcPopup.currentLabel") != "Bank")
Bot.Bank.Open();
foreach (string item in items)
{
if (Bot.Inventory.IsEquipped(item))
{
Logger("Can't bank an equipped item");
continue;
}
if (Bot.Inventory.Contains(item))
{
if (!Bot.Inventory.EnsureToBank(item))
{
Logger($"Failed to bank {item}, skipping it");
continue;
}
Logger($"{item} moved to bank");
}
}
}
/// <summary>
/// Move items from inventory to bank
/// </summary>
/// <param name="items">Items to move</param>
public void ToBank(params int[] items)
{
if (items == null)
return;
JumpWait();
if (Bot.Flash.GetGameObject("ui.mcPopup.currentLabel") != "Bank")
Bot.Bank.Open();
foreach (int item in items)
{
if (Bot.Inventory.IsEquipped(item))
{
Logger("Can't bank an equipped item");
continue;
}
if (Bot.Inventory.Contains(item))
{
if (!Bot.Inventory.EnsureToBank(item))
{
Logger($"Failed to bank {item}, skipping it");
continue;
}
Logger($"{item} moved to bank");
}
}
}
/// <summary>
/// Buys a item till you have the desired quantity
/// </summary>
/// <param name="map">Map of the shop</param>
/// <param name="shopID">ID of the shop</param>
/// <param name="itemName">Name of the item</param>
/// <param name="quant">Desired quantity</param>
/// <param name="shopQuant">How many items you get for 1 buy</param>
/// <param name="shopItemID">Use this for Merge shops that has 2 or more of the item with the same name and you need the second/third/etc., be aware that it will re-log you after to prevent ghost buy. To get the ShopItemID use the built in loader of Skua</param>
public void BuyItem(string map, int shopID, string itemName, int quant = 1, int shopItemID = 0)
{
if (CheckInventory(itemName, quant))
return;
ShopItem? item = parseShopItem(GetShopItems(map, shopID).Where(x => shopItemID == 0 ? x.Name.ToLower() == itemName.ToLower() : x.ShopItemID == shopItemID).ToList(), shopID, itemName, shopItemID);
_BuyItem(map, shopID, item, quant);
}
/// <summary>
/// Buys a item till it have the desired quantity
/// </summary>
/// <param name="map">Map of the shop</param>
/// <param name="shopID">ID of the shop</param>
/// <param name="itemID">ID of the item</param>
/// <param name="quant">Desired quantity</param>
/// <param name="shopQuant">How many items you get for 1 buy</param>
/// <param name="shopItemID">Use this for Merge shops that has 2 or more of the item with the same name and you need the second/third/etc., be aware that it will relog you after to prevent ghost buy. To get the ShopItemID use the built in loader of Skua</param>
public void BuyItem(string map, int shopID, int itemID, int quant = 1, int shopItemID = 0)
{
if (CheckInventory(itemID, quant))
return;
ShopItem? item = parseShopItem(GetShopItems(map, shopID).Where(x => shopItemID == 0 ? x.ID == itemID : x.ShopItemID == shopItemID).ToList(), shopID, itemID.ToString(), shopItemID);
_BuyItem(map, shopID, item, quant);
}
private void _BuyItem(string map, int shopID, ShopItem? item, int quant)
{
int buy_quant;
if (item == null || (buy_quant = _CalcBuyQuantity(item, quant)) == 0 || !_canBuy(shopID, item, buy_quant))
return;
Join(map);
Bot.Wait.ForMapLoad(map);
JumpWait();
Bot.Events.ExtensionPacketReceived += RelogRequieredListener;
dynamic sItem = new ExpandoObject();
dynamic objData = getData(item.ID, item.ShopItemID);
sItem = objData;
sItem.iSel = objData;
sItem.iQty = buy_quant;
sItem.iSel.iQty = buy_quant;
sItem.accept = 1;
Bot.Sleep(ActionDelay);
if (Bot.Options.SafeTimings)
Bot.Wait.ForActionCooldown(GameActions.BuyItem);
Bot.Flash.CallGameFunction("world.sendBuyItemRequestWithQuantity", JsonConvert.DeserializeObject<ExpandoObject>(JsonConvert.SerializeObject(sItem))!);
if (Bot.Options.SafeTimings)
Bot.Wait.ForItemBuy();
Bot.Sleep(ActionDelay);
Bot.Events.ExtensionPacketReceived -= RelogRequieredListener;
if (buy_quant > quant && (CheckInventory(item.Name, buy_quant)))
{
// Sell spares
// This only occurs when you buy sth with stack limits, but want less then the stack limit.
int sell_quant = buy_quant - quant;
SellItem(item.Name, quant);
Logger($"Bought {buy_quant} {item.Name}, sold {sell_quant}, now at {quant} {item.Name}");
}
else if (CheckInventory(item.Name, quant))
{
Logger($"Bought {buy_quant} {item.Name}, now at {quant} {item.Name}");
}
else
Logger($"Failed at buying {buy_quant}/{quant} {item.Name}");
void RelogRequieredListener(dynamic packet)
{
string type = packet["params"].type;
dynamic data = packet["params"].dataObj;
if (type == "json")
{
string str = data.strMessage;
switch (str)
{
case "Item is not buyable. Item Inventory full. Re-login to syncronize your real bag slot amount.":
Logger("Inventory de-sync (AE Issue) detected, reloggin so the bot can continue");
Relogin();
break;
}
}
}
dynamic getData(int itemID, int shopItemID = 0)
{
var shopItems = Bot.Flash.GetGameObject<dynamic[]>("world.shopinfo.items")!;
foreach (dynamic i in shopItems)
{
if (i == null || i!.ItemID == null || i!.ItemID != itemID ||
(shopItemID != 0 ? (i!.ShopItemID == null || i!.ShopItemID != shopItemID) : false))
continue;
return i!;
}
Logger($"Failed to find the shopItemData for itemID {itemID} in {shopID}");
return null!;
}
}
private int _CalcBuyQuantity(ShopItem item, int requestedQuant, bool old = false)
{
if (requestedQuant > item.MaxStack)
{
Logger($"Attempting to buy more than {item.MaxStack} of {item.Name}. The developer needs to fix the calling script.");
Bot.Stop();
}
// requestQuant <= max stack.
// No clamp checks needed, as Buys already asserts current quantity is less.
int buy_quant;
if ((buy_quant = requestedQuant - Bot.Inventory.GetQuantity(item.Name)) % item.Quantity != 0)
{
int diff = item.Quantity - (buy_quant % item.Quantity);
SellItem(item.Name, Bot.Inventory.GetQuantity(item.Name) - diff);
buy_quant += diff;
}
return buy_quant;
}
private bool _canBuy(int shopID, ShopItem? item, int buy_quant)
{
if (item == null)
return false;
//Achievement Check
int achievementID = Bot.Flash.GetGameObject<int>("world.shopinfo.iIndex");
string? io = Bot.Flash.GetGameObject<string>("world.shopinfo.sField");
if (achievementID > 0 && io != null && !HasAchievement(achievementID, io))
{
Logger($"Cannot buy {item.Name} from {shopID} because you dont have achievement {achievementID} of category {io}.", "CanBuy");
return false;
}
//Member Check
if (item.Upgrade && !IsMember)
{
Logger($"Cannot buy {item.Name} from {shopID} because you aren't a member.", "CanBuy");
return false;
}
//Required-Item Check
int reqItemID = Bot.Flash.GetGameObject<int>("world.shopinfo.reqItems");
if (reqItemID > 0 && !CheckInventory(reqItemID))
{
Logger($"Cannot buy {item.Name} from {shopID} because you dont have the requiered item needed to buy stuff from the shop, itemID: {reqItemID}", "CanBuy");
return false;
}
//Quest Check
string? questName = Bot.Flash.GetGameObject<List<dynamic>>("world.shopinfo.items")?.Find(d => d.ItemID == item.ID)?.sQuest;
if (!String.IsNullOrEmpty(questName))
{
var v = JsonConvert.DeserializeObject<dynamic[]>(File.ReadAllText("Quests.txt"));
if (v != null)
{
List<int> ids = v.Where(x => x.Name == questName).Select(q => (int)q.ID).ToList();
if (ids.Count > 0)
{
List<Quest> quests = EnsureLoad(ids.Where(q => !isCompletedBefore(q)).ToArray());
if (quests.Count > 0)
{
string s = String.Empty;
quests.ForEach(q => s += $"[{q.ID}] |");
bool one = quests.Count == 1;
Logger($"Cannot buy {item.Name} from {shopID} because you havn't completed the {(one ? "" : "one of ")}following quest{(one ? "" : "s")}: \"{questName}\" {s[..^2]}", "CanBuy");
return false;
}
}
}
}
//Rep check
if (!String.IsNullOrEmpty(item.Faction) && item.Faction != "None")
{
int reqRank = RepCPLevel.First(x => x.Key == item.RequiredReputation).Value;
if (reqRank > Bot.Reputation.GetRank(item.Faction))
{
Logger($"Cannot buy {item.Name} from {shopID} because you dont have rank {reqRank} {item.Faction}.", "CanBuy");
return false;
}
}
//Merge item check
int itemCount = item.Quantity == 0 ? 1 : item.Quantity;
int buy_count = (int)Math.Ceiling((decimal)buy_quant / (decimal)(itemCount));
if (item.Requirements != null)
{
foreach (ItemBase req in item.Requirements)
{
Bot.Drops.Pickup(req.ID);
Bot.Wait.ForPickup(req.ID);
int total_quant = buy_count * req.Quantity;
if (!CheckInventory(req.ID, total_quant))
{
if (CheckInventory(req.ID))
{
Logger($"Cannot buy {item.Name} from {shopID}.", "CanBuy");
Logger($"You own {Bot.Inventory.GetQuantity(req.ID)}x {req.Name}.", "CanBuy");
Logger($"You need {total_quant}.", "CanBuy");
return false;
}
Logger($"Cannot buy {item.Name} from {shopID} because {req.Name} is missing.", "CanBuy");
return false;
}
}
}
//Gold check
if (!item.Coins && item.Cost > 0)
{
int total_gold_cost = buy_count * item.Cost;
if (total_gold_cost > 100000000)
{
Logger($"Cannot buy more than 100 mil worth of items.", "CanBuy");
return false;
}
else if (total_gold_cost > Bot.Player.Gold)
{
Logger($"Cannot buy {item.Name} from {shopID}.", "CanBuy");
Logger($"You own {Bot.Inventory.GetQuantity(item.ID)}x {item.Name}.", "CanBuy");
Logger($"You need {Bot.Inventory.GetQuantity(item.ID) + buy_count}.", "CanBuy");
Logger($"You are missing {total_gold_cost - Bot.Player.Gold} gold to buy enough.", "CanBuy");
return false;
}
}
//AC costing check
if (item.Coins && item.Cost > 0)
{
int total_ac_cost = buy_count * item.Cost;
if (Bot.ShowMessageBox(
$"The bot is about to buy \"{item.Name}\" {buy_count} times, which costs {total_ac_cost} AC, do you accept this?",
"Warning: Costs AC!", true)
!= true)
{
Logger($"Cannot buy {item.Name} from {shopID} because you didn't allow the bot to buy the item", "CanBuy");
return false;
}
else if (Bot.Flash.GetGameObject<int>("world.myAvatar.objData.intCoins") < total_ac_cost)
{
Logger($"Cannot buy {item.Name} from {shopID} because you are missing {Bot.Flash.GetGameObject<int>("world.myAvatar.objData.intCoins") - total_ac_cost} ACs", "CanBuy");
return false;
}
}
return true;
}
public Dictionary<int, int> RepCPLevel = new()
{
{ 0, 1 },
{ 900, 2 },
{ 3600, 3 },
{ 10000, 4 },
{ 22500, 5 },
{ 44100, 6 },
{ 78400, 7 },
{ 129600, 8 },
{ 202500, 9 },
{ 302500, 10 }
};
/// <summary>
/// Sells a item till you have the desired quantity
/// </summary>
/// <param name="itemName">Name of the item</param>
/// <param name="quant">Desired quantity</param>
/// <param name="all">Set to true if you wish to sell all the items</param>
public void SellItem(string itemName, int quant = 0, bool all = false)
{
if (!(quant > 0 ? CheckInventory(itemName, quant) : CheckInventory(itemName)) || !Bot.Inventory.TryGetItem(itemName, out var item))
return;
JumpWait();
if (!all)
{
// Inv quant >= current quantity.
if (Bot.Options.SafeTimings)
Bot.Wait.ForActionCooldown(GameActions.SellItem);
Bot.Send.Packet($"%xt%zm%sellItem%{Bot.Map.RoomID}%{item!.ID}%{item!.Quantity - quant}%{item!.CharItemID}%");
if (Bot.Options.SafeTimings)
Bot.Wait.ForItemSell();
Bot.Sleep(ActionDelay);
return;
}
else Bot.Shops.SellItem(itemName);
Logger($"{(all ? string.Empty : quant.ToString())} {itemName} sold");
}
public List<ShopItem> GetShopItems(string map, int shopID)
{
Bot.Wait.ForTrue(() => Bot.Shops.ID == shopID, () =>
{
Join(map);
Bot.Shops.Load(shopID);
Bot.Sleep(ActionDelay);
}, 20, 1000);
if (Bot.Shops.ID != shopID || Bot.Shops.Items == null)
{
Bot.ShowMessageBox("Failed to load shop the shop and get it's data, please restart the client.", "Shop Data Loading Failed");
return new();
}
return Bot.Shops.Items;
}
public ShopItem? parseShopItem(List<ShopItem> shopItem, int shopID, string itemNameID, int shopItemID = 0)
{
if (shopItem.Count == 0)
{
Logger($"Item {itemNameID} not found in shop {shopID}.");
return null;
}
else if (shopItem.Count > 1)
{
if (shopItemID > 0)
{
if (!shopItem.Any(x => x.ShopItemID == shopItemID))
{
Logger($"Item {itemNameID} with ShopItemID {shopItemID} was not in {shopID}. The developer needs to correct the Shop Item ID.");
return null;
}
return shopItem.First(x => x.ShopItemID == shopItemID);
}
Logger($"Multiple items found with the name {itemNameID} in shop {shopID}. The developer needs to specify the Shop Item ID.");
return null;
}
return shopItem.First();
}
/// <summary>
/// <param name="items">Items to Trash/Bank</param>
/// Removes the Specific {items} from Players Inv (Banks Coin{ac} items)
/// </summary>
public void TrashCan(params string[] items)
{
JumpWait();
foreach (string item in items)
{
if (!Bot.Inventory.TryGetItem(item, out var TrashItem) || TrashItem == null)
continue;
if (!TrashItem.Coins)
{
Logger($"Trashed: \"{TrashItem}\" x{TrashItem.Quantity}");
Bot.Send.Packet($"%xt%zm%removeItem%{Bot.Map.RoomID}%{TrashItem.ID}%{Bot.Player.ID}%{TrashItem.Quantity}%");
}
else ToBank(item);
}
}