-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathCoreBots.cs
8632 lines (7480 loc) · 332 KB
/
CoreBots.cs
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
/*
name: null
description: null
tags: null
*/
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.Players;
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;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using System.Globalization;
using Skua.Core.Models.Auras;
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;
public bool BankUnenhancedACGear { 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; } = Array.Empty<string>();
// [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; } = Array.Empty<string>();
// [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;
// [Can Change] Member Status
public bool IsMember { get; set; }
// Thousand-level Constants
const int OneK = 1000; // 1k
const int TenK = 10000; // 10k
const int OneHundredK = 100000; // 100k
const int FiveHundredK = 500000; // 500k
// Million-level Constants
const int OneMillion = 1000000; // 1m
const int FiveMillion = 5000000; // 5m
const int TenMillion = 10000000; // 10m
const int FiftyMillion = 50000000; // 50m
const int OneHundredMillion = 100000000; // 100m
//Max integer
const int maxint = Int32.MaxValue;
private static CoreBots? _instance;
public static CoreBots Instance => _instance ??= new CoreBots();
private IScriptInterface Bot => IScriptInterface.Instance;
private const string DiscordLink = "https://discord.gg/CKKbk2zr3p";
#endregion
#region Start/Stop
/// <summary>
/// Set common bot options to desired value
/// </summary>
/// <param name="changeTo">Value the options will be changed to</param>
/// <param name="disableClassSwap"></param>
public void SetOptions(bool changeTo = true, bool disableClassSwap = false)
{
// These things need to be set and checked before anything else
if (changeTo)
{
Bot.Events.ScriptStopping += CrashDetector;
SkuaVersionChecker("1.2.4.0");
if (File.Exists(ClientFileSources.SkuaScriptsDIR + "/z_CompiledScript.cs"))
File.Delete(ClientFileSources.SkuaScriptsDIR + "/z_CompiledScript.cs");
loadedBot = Bot.Manager.LoadedScript.Replace("\\", "/").Split("/Scripts/").Last().Replace(".cs", "");
Logger($"Bot Started [{loadedBot}]");
if (Bot.Config != null && Bot.Config.Options.Contains(SkipOptions) && !Bot.Config.Get<bool>(SkipOptions))
Bot.Config.Configure();
if (!Bot.Player.LoggedIn)
{
if (Bot.Servers.CachedServers.Any())
{
Logger("Auto Login triggered");
try
{
if (!Bot.Servers.EnsureRelogin(Bot.Options.ReloginServer ?? Bot.Servers.CachedServers[0]?.Name ?? "Twilly"))
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);
Sleep(5000);
}
catch
{
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);
}
}
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);
}
ReadCBO();
}
// Set the member status
IsMember = isUpgraded();
// Common Options
Bot.Options.PrivateRooms = false;
Bot.Options.AttackWithoutTarget = false;
Bot.Options.SafeTimings = changeTo;
Bot.Options.RestPackets = changeTo && ShouldRest;
Bot.Options.AutoRelogin = true;
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.DisableRedWarning = true;
Bot.Lite.CharacterSelectScreen = false;
//adding sommore
// Bot.Lite.SmoothBackground = true;
// Bot.Lite.ShowMonsterType = true;
// Bot.Lite.CustomDropsUI = true;
CollectData(changeTo);
#region Required things that must be done before starting the Script
if (changeTo)
{
// Open Bank on startup ensuring current window is `Bank`, then load the bank information.
if (Bot.Flash.GetGameObject("ui.mcPopup.currentLabel") != "\"Bank\"")
Bot.Bank.Open();
Bot.Bank.Load();
Bot.Bank.Loaded = true;
// Oaklore is Broke as fffff. So we'll move you somewhere else to start the script.
if (Bot.Map.Name != null && Bot.Map.Name == "oaklore")
{
Bot.Wait.ForMapLoad("oaklore");
Logger("We started in oaklore... starting scripts here can cause \"issues\"... we're not sure why this happens... but hopefully this fixes that.\n \tTeleporting to \"battleon\"\n\n");
Join("battleon-100000");
}
}
#endregion Required things that must be done before starting the Script
// These things need to be taken care of too, but less priority
if (changeTo)
{
SetOptionsAsync();
Bot.Options.HuntDelay = HuntDelay;
if (BankMiscAC)
BankACMisc();
if (BankUnenhancedACGear)
BankACUnenhancedGear();
EquipmentBeforeBot.AddRange(Bot.Inventory.Items.Where(i => i.Equipped).Select(x => x.Name));
currentClass = ClassType.None;
usingSoloGeneric = SoloClass.ToLower() == "generic";
usingFarmGeneric = FarmClass.ToLower() == "generic";
EquipClass(disableClassSwap ? ClassType.None : ClassType.Solo);
Bot.Events.ScriptStopping += StopBotEvent;
// Alive Check handling
Bot.Events.MapChanged += CleanKilledMonstersList;
Bot.Events.MonsterKilled += KilledMonsterListener;
Bot.Events.ExtensionPacketReceived += RespawnListener;
Bot.Drops.Start();
Logger("Bot Configured");
// Bunch of things that are done in the background and you dont need the bot to wait for
void SetOptionsAsync()
{
#region Handlers
Task.Run(() =>
{
Task.Run(() =>
{
if (OneTimeMessage("discordV11",
"Our discord server was recently deleted again (March 29th 2023), click yes if you wish to (re-)join the server",
true, true, true))
Process.Start("explorer", DiscordLink);
});
// Butler directory cleaning
if (Directory.Exists(ButlerLogDir))
{
if (File.Exists(ButlerLogPath()))
File.Delete(ButlerLogPath());
string[] files = Directory.GetFiles(ButlerLogDir);
if (files.Any(x => x.Contains("~!") && x.Split("~!").First() == Username().ToLower()))
File.Delete(files.First(x => x.Contains("~!") && x.Split("~!").First() == Username().ToLower()));
}
// AFK Handler
Bot.Send.Packet("%xt%zm%afk%1%false%");
Sleep();
bool TimerRunning = false;
//int afkCount = 0;
//Bot.Events.PlayerAFK += eventAFK;
//void eventAFK()
//{
// afkCount++;
// int localCount = afkCount;
// Sleep(300000);
// if (Bot.Player.AFK && afkCount == localCount)
// {
// Bot.Options.AutoRelogin = true;
// Bot.Servers.Logout();
// }
//}
Bot.Handlers.RegisterHandler(5000, b =>
{
if (b.Player.AFK && !TimerRunning)
{
TimerRunning = true;
Sleep(300000);
if (b.Player.AFK)
{
b.Options.AutoRelogin = true;
b.Servers.Logout();
}
TimerRunning = false;
}
}, "AFK Handler");
// Settin Loaded Quest Limiter
Bot.Handlers.RegisterHandler(3000, b =>
{
if (Bot.Quests.Tree.Count > LoadedQuestLimit)
{
Bot.Flash.SetGameObject("world.questTree", new ExpandoObject());
}
}, "Quest-Limit Handler");
// Prison Detector
if (loadedBot.Replace("\\", "/") != "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);
}
}
}
#endregion Handlers
// Anti-lag option
if (AntiLag)
{
Bot.Options.LagKiller = changeTo;
Bot.Flash.SetGameObject("stage.frameRate", 10);
if (!Bot.Flash.GetGameObject<bool>("ui.monsterIcon.redX.visible"))
Bot.Flash.CallGameFunction("world.toggleMonsters");
}
// Identity Protection
// Bot.Options.CustomName = "SKUA BOT";
// Bot.Options.CustomGuild = "HTTPS://AUQW.TK/";
// Holiday Handlers
AprilFools();
//Fucking with specific people
UserSpecificMessages();
});
}
}
}
// Whether the player is a Member (set to true if necessary during setOptions)
public bool isUpgraded()
{
// Get membership days left as a string
string? membershipDaysLeftString = Bot.Flash.GetGameObject("world.myAvatar.objData.iUpgDays");
// Attempt to parse the string into an integer
if (int.TryParse(membershipDaysLeftString, out int membershipDaysLeft))
{
// Return true if membership days are greater than 0
return membershipDaysLeft > 0;
}
// If parsing fails, return false (not a member)
return false;
}
public List<string> BankingBlackList = new();
private readonly 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)
{
StopBotAsync();
Bot.Handlers.Clear();
if (Bot.Player.LoggedIn)
{
JumpWait();
Sleep();
if (!string.IsNullOrWhiteSpace(CustomStopLocation))
{
string _stopLoc = CustomStopLocation.Trim().ToLower();
if (new[] { "home", "house" }.Contains(_stopLoc))
{
if (Bot.House.Items.Any(h => h.Equipped))
{
string? toSend = null;
Bot.Events.ExtensionPacketReceived += modifyPacket;
Bot.Send.Packet($"%xt%zm%house%1%{Username()}%");
Bot.Wait.ForMapLoad("house");
Task.Run(() =>
{
Bot.Wait.ForMapLoad("house");
if (Bot.Wait.ForTrue(() => toSend != null, 20))
Bot.Send.ClientPacket(toSend!, "json");
Bot.Events.ExtensionPacketReceived -= modifyPacket;
for (int i = 0; i < 7; i++)
Bot.Send.ClientServer(" ", "");
});
void modifyPacket(dynamic packet)
{
string type = packet["params"].type;
dynamic data = packet["params"].dataObj;
if ((type is not null and "json") && (data.houseData is not null))
{
toSend = $"{{\"t\":\"xt\",\"b\":{{\"r\":-1,\"o\":{{\"cmd\":\"moveToArea\",\"areaName\":\"house\",\"uoBranch\":{JsonConvert.SerializeObject(data.uoBranch)},\"strMapFileName\":\"{data.strMapFileName}\",\"intType\":\"1\",\"monBranch\":[],\"houseData\":{Regex.Replace(JsonConvert.SerializeObject(data.houseData), Username(), "Skua user", RegexOptions.IgnoreCase)},\"sExtra\":\"\",\"areaId\":{data.areaId},\"strMapName\":\"house\"}}}}}}";
Bot.Events.ExtensionPacketReceived -= modifyPacket;
}
}
}
else Bot.Send.Packet($"%xt%zm%cmd%1%tfer%{Username()}%whitemap-{PrivateRoomNumber}%");
}
else if (new[] { "off", "disabled", "disable", "stop", "same", "currentmap", "bot.map.currentmap", "none", "None", string.Empty }
.Any(m => m == _stopLoc))
{
// Nothing happens
}
else Bot.Send.Packet($"%xt%zm%cmd%1%tfer%{Username()}%{_stopLoc}-{PrivateRoomNumber}%");
if (EquipmentBeforeBot.Any())
{
JumpWait();
Equip(EquipmentBeforeBot.ToArray());
}
}
}
if (crashed)
Logger("Bot stopped due to a crash.");
else if (!Bot.Player.LoggedIn)
{
if (Bot.Options.AutoRelogin)
{
Task.Run(async () =>
{
await Bot.Manager.RestartScriptAsync();
if (Bot.Player.LoggedIn)
return;
Logger("Bot stopped due to Auto-Relogin failure.");
});
}
else Logger("Bot stopped due to player logout.");
}
else Logger("Bot stopped successfully.");
GC.KeepAlive(Instance);
return scriptFinished;
void StopBotAsync()
{
Task.Run(() =>
{
SavedState(false);
if (AntiLag)
{
Bot.Options.SetFPS = 60;
if (Bot.Flash.GetGameObject<bool>("ui.monsterIcon.redX.visible"))
Bot.Flash.CallGameFunction("world.toggleMonsters");
}
Bot.Options.CustomName = Bot.Player.Username ?? Username().ToUpper();
// Bot.Options.CustomName = Username().ToUpper();
string? guild = Bot.Flash.GetGameObject<string>("world.myAvatar.objData.guild.Name");
Bot.Options.CustomGuild = guild != null ? $"< {guild} >" : string.Empty;
if (File.Exists(ButlerLogPath()))
File.Delete(ButlerLogPath());
});
}
}
private bool scriptFinished = true;
private bool StopBotEvent(Exception? e)
{
SetOptions(false);
return StopBot(e != null);
}
private bool CrashDetector(Exception? e)
{
if (e == null || e is OperationCanceledException)
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('/', '\\')[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 List<string> GetLogs(LogType type = LogType.Script)
=> (_logService ??= Ioc.Default.GetRequiredService<ILogService>()).GetLogs(type);
private ILogService? _logService;
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 (item == null)
return true;
if (Bot.TempInv.Contains(item, quant))
return true;
if (Bot.Inventory.Contains(item, quant))
return true;
if (Bot.House.Contains(item))
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;
}
return false;
}
/// <summary>
/// Checks the Bank and Inventory for the item with it's ID
/// </summary>
/// <param name="itemID">ID of the item to be checked</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 (itemID == null)
return true;
int _itemID = (int)itemID;
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 checked</param>
/// <param name="quant">Desired quantity</param>
/// <param name="any">If any of the items exist, returns true</param>
/// <param name="toInv">Whether or not send the item to Inventory</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 || !itemNames.Any())
return true;
foreach (string name in itemNames)
{
if (CheckInventory(name, quant, toInv))
{
if (any)
return true;
else
continue;
}
if (!any)
return false;
}
return !any;
}
/// <summary>
/// Checks the Bank and Inventory for the item with it's ID
/// </summary>
/// <param name="itemIDs">Array of IDs of the items to be checked</param>
/// <param name="quant">Desired quantity</param>
/// <param name="any">If any of the items exist, returns true</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[]? itemIDs, int quant = 1, bool any = false, bool toInv = true)
{
if (itemIDs == null || !itemIDs.Any())
return true;
foreach (int id in itemIDs)
{
if (CheckInventory(id, quant, toInv))
{
if (any)
return true;
else
continue;
}
if (!any)
return false;
}
return !any;
}
/// <summary>
/// Attempts to initialize an object using the provided initializer function, retrying up to a specified number of times if the initialization fails.
/// </summary>
/// <typeparam name="T">The type of the object to be initialized. This must be a class type.</typeparam>
/// <param name="initializer">
/// A function that attempts to initialize the object and returns the initialized object or null if the initialization fails.
/// </param>
/// <param name="retries">
/// The number of times to retry the initialization if it fails. The default value is 5 retries.
/// </param>
/// <param name="delay">
/// The delay in milliseconds between retry attempts. The default value is 1000 milliseconds (1 second).
/// </param>
/// <returns>
/// Returns the initialized object of type <typeparamref name="T"/> if the initialization succeeds within the specified retries,
/// otherwise returns null after exhausting all retry attempts.
/// </returns>
/// <remarks>
/// This method provides a way to retry an initialization operation, which can be useful when dealing with operations that might fail intermittently.
/// It logs each retry attempt and will notify if all attempts fail.
/// </remarks>
public T? InitializeWithRetries<T>(Func<T?> initializer, int retries = 5, int delay = 1000) where T : class
{
T? result = null;
for (int i = 0; i < retries; i++)
{
result = initializer();
if (result != null)
break;
Logger($"Attempt {i++}: Initialization failed. Retrying...");
Sleep(delay); // Wait for the specified delay before retrying
}
if (result == null)
{
Logger($"Initialization failed after {retries} attempts at: {initializer}.");
}
return result;
}
/// <summary>
/// Checks if there is enough space in the inventory for specified items and logs a message if space is insufficient.
/// </summary>
/// <param name="counter">Reference to a counter variable tracking successful checks.</param>
/// <param name="items">Items to check for space in the inventory.</param>
public void CheckSpaces(ref int counter, params string[] items)
{
foreach (string item in items)
if (CheckInventory(item, toInv: false))
counter++;
int requiredSlots = items.Length - counter;
if (Bot.Inventory.FreeSlots < requiredSlots)
Logger($"Not enough free slot{(requiredSlots != 1 ? "s" : "")}, please clear {requiredSlots} slot{(requiredSlots != 1 ? "s" : "")}", messageBox: true, stopBot: true);
}
/// <summary>
/// Moves specified items by their names from the inventory to the bank.
/// </summary>
/// <param name="items">
/// Array of item names to transfer to the bank. Items will be skipped if
/// they are equipped, in use, or not present in the inventory. Skips blacklisted
/// or non-bankable categories.
/// </param>
/// <remarks>
/// Only whitelisted item categories are moved, and house items are handled
/// separately from inventory items. Attempts each move up to 5 times for
/// reliability and logs each success or failure.
/// </remarks>
public void Unbank(params string[] items)
{
if (items == null || items.Length == 0)
{
return;
}
if (Bot.Player.InCombat)
{
JumpWait();
}
int RequiredSpaces = items.Count();
foreach (string item in items)
{
if (Bot.House.Contains(item) || Bot.Inventory.Contains(item)
|| (!Bot.Inventory.Contains(item) && !Bot.House.Contains(item) && !Bot.Bank.Contains(item)))
{
RequiredSpaces--;
continue; // Skip the item if it's in house or bank, or nowhere (not in any of the 3 places)
}
if (Bot.Bank.Contains(item) && (!Bot.Inventory.Contains(item) || !Bot.House.Contains(item)))
{
if (Bot.Inventory.FreeSlots <= 0 && Bot.Inventory.Slots != 0 && Bot.Inventory.UsedSlots >= Bot.Inventory.Slots)
{
Logger($"Your inventory is full ({Bot.Inventory.UsedSlots}/{Bot.Inventory.Slots}), please Make {RequiredSpaces} space(s), and restart the bot", messageBox: true, stopBot: true);
return;
}
bool isHouseItem = Bot.Bank.TryGetItem(item, out InventoryItem? x) &&
x != null &&
(x.CategoryString == "House" || x.CategoryString == "Wall Item" || x.CategoryString == "Floor Item");
if (isHouseItem)
{
bool success = false;
for (int i = 0; i < 20; i++) // Retry up to 20 times
{
SendPackets($"%xt%zm%bankToInv%{Bot.Map.RoomID}%{x!.ID}%{x.CharItemID}%");
Sleep(); // Wait for a short period before checking
if (Bot.House.Contains(item))
{
success = true;
break;
}
}
if (!success)
{
Logger($"Failed to unbank {item}, skipping it");
continue;
}
}
else
{
bool success = false;
for (int i = 0; i < 20; i++) // Retry up to 20 times
{
Bot.Bank.EnsureToInventory(item);
Sleep(); // Wait for a short period before checking
if (Bot.Inventory.Contains(item))
{
success = true;
break;
}
}
if (!success)
{
Logger($"Failed to unbank {item}, skipping it");
continue;
}
}
Logger($"{item} moved from bank");
}
}
}
/// <summary>
/// Transfers specified items by their unique IDs from the bank to the inventory.
/// </summary>
/// <param name="itemIDs">
/// Array of item IDs to transfer from the bank. Items will be skipped if
/// they are already in the inventory, house, or cannot be found in the bank.
/// </param>
/// <remarks>
/// Ensures that items can be transferred by checking inventory space,
/// and retries failed transfers up to 20 times before skipping.
/// Provides detailed logging for each success or failure.
/// </remarks>
public void Unbank(params int[] itemIDs)
{
if (itemIDs == null || itemIDs.Length == 0)
return;
if (Bot.Player.InCombat)
JumpWait();
int RequiredSpaces = itemIDs.Count();
foreach (int item in itemIDs)
{
if (Bot.House.Contains(item) || Bot.Inventory.Contains(item)
|| !Bot.Inventory.Contains(item) && !Bot.House.Contains(item) && !Bot.Bank.Contains(item))
{
RequiredSpaces--;
continue; // Skip the item if it's in house or bank, or nowhere (not in any of the 3 places)
}
if (Bot.Bank.Contains(item) && (!Bot.Inventory.Contains(item) || !Bot.House.Contains(item)))
{
ItemBase? itemString = Bot.Bank.Items?.FirstOrDefault(x => x?.ID == item);
if (itemString == null)
{
Logger($"Failed to find item with ID {item}, skipping it");
continue;
}
if (Bot.Inventory.FreeSlots <= 0 && Bot.Inventory.Slots != 0 && Bot.Inventory.UsedSlots >= Bot.Inventory.Slots)
{
Logger($"Your inventory is full ({Bot.Inventory.UsedSlots}/{Bot.Inventory.Slots}), please Make {RequiredSpaces} space(s), and restart the bot", messageBox: true, stopBot: true);
return;
}
bool isHouseItem = Bot.Bank.TryGetItem(item, out InventoryItem? x) &&
x != null &&
(x.CategoryString == "House" || x.CategoryString == "Wall Item" || x.CategoryString == "Floor Item");
if (isHouseItem)
{
bool success = false;
for (int i = 0; i < 20; i++) // Retry up to 20 times
{
SendPackets($"%xt%zm%bankToInv%{Bot.Map.RoomID}%{x!.ID}%{x.CharItemID}%");
Sleep(); // Wait for a short period before checking
if (Bot.House.Contains(item))
{
success = true;
break;
}
}
if (!success)
{
Logger($"Failed to unbank {itemString.Name}, skipping it");
continue;
}
}
else
{
bool success = false;
for (int i = 0; i < 20; i++) // Retry up to 20 times
{
Bot.Bank.EnsureToInventory(item);
Sleep(); // Wait for a short period before checking
if (Bot.Inventory.Contains(item))
{
success = true;
break;
}
}
if (!success)
{
Logger($"Failed to unbank {itemString.Name}, skipping it");
continue;
}
}
Logger($"{itemString.Name} moved from bank");
}
}
}
/// <summary>
/// Transfers specified items from the inventory to the bank by item name.
/// </summary>
/// <param name="items">
/// An array of item names to move to the bank. Items are ignored if they are
/// equipped, excluded by the blacklist, or do not exist in the inventory.
/// </param>
/// <remarks>
/// The method ensures only items from specified whitelisted categories or
/// items marked as "Coins" are moved. Attempts each transfer up to 5 times
/// if the initial move fails and logs any unsuccessful attempts.
///
/// House items are transferred separately, bypassing the normal inventory-to-bank process.
/// Certain items specified in the Extras array are also excluded from being banked.
/// </remarks>
public void ToBank(params string[] items)
{
if (items == null || !items.Any(x => !string.IsNullOrEmpty(x)))
{
return;
}
JumpWait();
// Whitelist categories and items
List<ItemCategory> whiteList = new() { ItemCategory.Note, ItemCategory.Item, ItemCategory.Resource, ItemCategory.QuestItem };
int?[] Extras = { 18927, 38575 }; // Items that shouldn't be banked
foreach (string? item in items)
{
if (item == null || item == SoloClass || item == FarmClass || FarmGear.Contains(item) || SoloGear.Contains(item))
continue;
if (Bot.Inventory.IsEquipped(item) || Bot.House.IsEquipped(item))
{
Logger($"Can't bank an equipped item: {item}");
continue;
}
else if ((!Bot.Inventory.Contains(item) || !Bot.House.Contains(item)) && Bot.Bank.Contains(item))
{
Logger($"Item {item} is already in the bank, skipping it");
continue;
}
else if (!Bot.Inventory.Items.Concat(Bot.House.Items).Any(x => x.Name == item))
{
Logger($"{item} not found in inventory, skipping it");
continue;
}
ItemBase? inventoryItem = Bot.Inventory.Items.Concat(Bot.House.Items).FirstOrDefault(x => x != null && x.Name == item);
bool itemIsForHouse = Bot.House.TryGetItem(item, out InventoryItem? _item) &&
_item != null &&
(_item.CategoryString == "House" || _item.CategoryString == "Wall Item" || _item.CategoryString == "Floor Item");
// Check if item is in whitelist and not in blacklist or Extras
if ((inventoryItem?.Category != null && whiteList.Contains(inventoryItem.Category) || inventoryItem?.Coins == true) &&
!BankingBlackList.Contains(item) &&
!Extras.Contains(inventoryItem?.ID) &&
Bot.Inventory.Contains(item) ||
(itemIsForHouse && Bot.House.Contains(item) &&
_item?.Equipped != true))
{
if (!itemIsForHouse)
{
for (int i = 0; i < 5 && !Bot.Inventory.EnsureToBank(item); i++)
Sleep();
if (!Bot.Inventory.EnsureToBank(item) && !Bot.Bank.Contains(item))
{
Logger($"Failed to bank {item}, skipping it");
continue;
}
}
else if (itemIsForHouse)
{
if (_item != null)
{
SendPackets($"%xt%zm%bankFromInv%{Bot.Map.RoomID}%{_item.ID}%{_item.CharItemID}%");
Bot.Wait.ForTrue(() => !Bot.House.Contains(item), 20);
if (Bot.House.Items.Any(x => x.Name == item))
{
Logger($"Failed to bank {item} in house bank, skipping it");