forked from auqw/Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoreBots.cs
More file actions
11953 lines (10360 loc) · 422 KB
/
CoreBots.cs
File metadata and controls
11953 lines (10360 loc) · 422 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
/*
name: null
description: null
tags: null
version: 1.4.0.5
*/
using CommunityToolkit.Mvvm.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Skua.Core.Interfaces;
using Skua.Core.Models;
using Skua.Core.Models.Auras;
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.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
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; } = string.Empty;
// [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; } = string.Empty;
// [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] Name of your dodge class
public string DodgeClass { get; set; } = string.Empty;
// [Can Change] Mode of dodge class, if it has multiple.
public ClassUseMode DodgeUseMode { get; set; } = ClassUseMode.Base;
// [Can Change] Whether you wish to equip dodge equipment
public bool DodgeGearOn { get; set; } = true;
// [Can Change] Names of your dodge equipment
public string[] DodgeGear { get; set; } = Array.Empty<string>();
// [Can Change] Name of your bossing class
public string BossClass { get; set; } = string.Empty;
// [Can Change] Mode of boss class, if it has multiple.
public ClassUseMode BossUseMode { get; set; } = ClassUseMode.Base;
// [Can Change] Whether you wish to equip bossing equipment
public bool BossGearOn { get; set; } = true;
// [Can Change] Names of your bossing equipment
public string[] BossGear { 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; }
public bool AutoEnhance { get; set; } = true;
public bool BestGear { get; set; } = false;
private static CoreBots? _instance;
public static CoreBots Instance => _instance ??= new CoreBots();
private IScriptInterface Bot => IScriptInterface.Instance;
private const string DiscordLink = "https://discord.gg/CKKbk2zr3p";
private Stopwatch? _scriptStopwatch;
#endregion Declerations
#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)
{
EnforceInvariantCulture();
SkuaVersionChecker();
Bot.UltraBossHelper.EnableCounterAttack();
if (changeTo)
{
Bot.Events.ScriptStopping += CrashDetector;
// Start the stopwatch for timing the script run
_scriptStopwatch = Stopwatch.StartNew();
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();
int retries = 0;
const int maxRetries = 3;
while (!Bot.Player.LoggedIn && retries < maxRetries)
{
retries++;
if (Bot.Servers.CachedServers.Any())
{
Logger("Auto Login triggered");
try
{
if (
!Bot.Servers.EnsureRelogin(
Bot.Options.ReloginServer
?? Bot.Servers.CachedServers.FirstOrDefault(s =>
s.Name != "Class Test Realm"
&& s.Online
&& s.PlayerCount < s.MaxPlayers
)?.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
);
}
Bot.Wait.ForTrue(() => Bot.Player.Loaded, 10);
}
if (!Bot.Player.LoggedIn)
Bot.StopSync();
ReadCBO();
#region Social Privacy Options
bool isStarting = changeTo;
CBOBool("IncognitoMode", out bool IncognitoModeOn);
if (!IncognitoModeOn)
{
if (isStarting == true)
{
Logger("Incognito Mode in CBO is off. Skipping privacy settings.");
}
}
else
{
bool disabling = isStarting;
bool warned = false;
foreach (
(string key, string label) in new Dictionary<string, string>
{
{ "bGoto", "Goto" },
{ "bParty", "Party invites" },
{ "bFriend", "Friend invites" },
{ "bDuel", "Duel invites" },
{ "bGuild", "Guild invites" },
{ "bWhisper", "Whisper" },
}
)
{
if (label == "Goto" && !loadedBot.ToLower().Contains("butler"))
continue;
bool current = Bot.Flash.GetGameObject<bool>($"uoPref.{key}");
if (disabling ? current : !current)
{
if (disabling && !warned)
{
Logger(
"[SetOptions] Turning certain \"Social\" options off to help protect you"
);
warned = true;
}
Logger($"[SetOptions] {(disabling ? "Turning off" : "Re-enabling")}: {label}");
SendPackets($"%xt%zm%cmd%1%uopref%{key}%{(!disabling).ToString().ToLower()}%");
Bot.Sleep(500);
}
}
if (disabling)
GC.Collect();
}
#endregion Social Privacy Options
// Set the member status
IsMember = isUpgraded();
// Common Options
Bot.Options.RejectAllDrops = false;
Bot.Options.PrivateRooms = false;
Bot.Options.AttackWithoutTarget = false;
Bot.Options.QuestAcceptAndCompleteTries = AcceptandCompleteTries;
Bot.Options.AutoRelogin = true;
Bot.Options.SafeTimings = changeTo;
Bot.Options.RestPackets = changeTo && ShouldRest;
Bot.Options.InfiniteRange = changeTo;
Bot.Options.SkipCutscenes = changeTo;
// Lite Options
Bot.Lite.ReacceptQuest = false;
Bot.Lite.DisableRedWarning = true;
Bot.Lite.CharacterSelectScreen = false;
Bot.Lite.UntargetDead = true;
Bot.Lite.UntargetSelf = true;
Bot.Lite.SmoothBackground = true;
Bot.Lite.ShowMonsterType = true;
Bot.Lite.CustomDropsUI = true;
Bot.Lite.DraggableDrops = false;
Bot.Lite.AurasUI = true;
Bot.Lite.QuantityWarnings = false;
Bot.Lite.VisualSkillCooldowns = true;
Bot.Lite.ChatUI = true;
Bot.Lite.QuestLogTurnIns = true;
Bot.Lite.DisableSoundFx = true;
// Drop Options
Bot.Drops.RejectElse = changeTo;
Bot.Drops.Clear();
Bot.Drops.Start();
CollectData(changeTo);
#region Required things that must be done before starting the Script
if (changeTo)
{
//Start scripts Safely by starting them in the house ( or whitemap if house desnt exist) if the start map is battleon
if (
new[] { "battleon", "oaklore", "bludrutbrawl" }.Any(m =>
Bot.Map.Name.Equals(m, StringComparison.OrdinalIgnoreCase)
)
)
{
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}%"
);
}
// 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;
AutoAddTags();
DateTime now = DateTime.Now;
if (now >= new DateTime(now.Year, 12, 25) && now < new DateTime(now.Year, 12, 26, 12, 0, 0))
OneTimeMessage("Xmax2025", "Merry Christmas - Skua Team");
}
#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)
);
var currentClassName = Bot.Player.CurrentClass?.Name ?? "generic";
usingSoloGeneric = SoloClass.ToLower() == "generic";
usingFarmGeneric = FarmClass.ToLower() == "generic";
usingDodgeGeneric = DodgeClass.ToLower() == "generic";
usingBossGeneric = BossClass.ToLower() == "generic";
Bot.Skills.StartAdvanced(
currentClassName,
false,
currentClassName switch
{
var n when n == SoloClass => SoloUseMode,
var n when n == FarmClass => FarmUseMode,
var n when n == BossClass => BossUseMode,
var n when n == DodgeClass => DodgeUseMode,
_ => ClassUseMode.Base,
}
);
Bot.Events.ScriptStopping += StopBotEvent;
// Alive Check handling
Bot.Events.MapChanged += CleanKilledMonstersList;
Bot.Events.MonsterKilled += KilledMonsterListener;
Bot.Events.ExtensionPacketReceived += RespawnListener;
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;
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.Events.MapChanged -= PrisonDetector;
Bot.StopSync(true);
}
Bot.Events.MapChanged -= PrisonDetector;
}
}
#endregion Handlers
// Anti-lag option
if (AntiLag)
{
Bot.Options.LagKiller = changeTo;
// Some maps are codded horrible and the animations can cause lag or freezes, so we'll turn all the animations off
Bot.Lite.FreezeMonsterPosition = true;
Bot.Lite.DisableMonsterAnimation = true;
Bot.Lite.DisableDamageStrobe = true;
Bot.Lite.DisableSelfAnimation = true;
Bot.Lite.DisableWeaponAnimation = true;
Bot.Lite.DisableSkillAnimation = true;
Bot.Lite.DisableAuraAnimations = true;
Bot.Lite.DisableDamageNumbers = true;
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 = "SkuaLabRat";
// Bot.Options.CustomGuild = "Skua-cide Squad";
// Holiday Handlers
AprilFools();
//Fucking with specific people
UserSpecificMessages();
});
}
}
if (!changeTo && _scriptStopwatch != null)
{
Bot.Drops.Clear();
_scriptStopwatch.Stop();
Logger($"Script ran for {_scriptStopwatch.Elapsed:hh\\:mm\\:ss}");
_scriptStopwatch = null;
}
}
// 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
{
get => _BankingBlackList ??= new List<string>();
set => _BankingBlackList = value;
}
public List<string> _BankingBlackList;
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())
{
string[] PVPMaps = new[]
{
"bludrutbrawl",
"darkoviapvp",
"dagepvp",
"deathpitbrawl",
"frostbrawl",
"chaosbrawl",
"doomarenaa",
"doomarenab",
"doomarenac",
"doomarenad",
};
if (PVPMaps.Contains(Bot.Map.Name))
Join("whitemap");
else
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 () =>
{
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
await Bot.Manager.RestartScriptAsync();
if (Bot.Player.LoggedIn)
return;
Logger("Bot stopped due to Auto-Relogin failure.");
}
catch (OperationCanceledException)
{
Logger("Auto-relogin timed out after 30 seconds.");
}
});
}
else
Logger("Bot stopped due to player logout.");
}
else
Logger("Bot stopped successfully.");
GC.KeepAlive(_instance);
return scriptFinished;
void StopBotAsync()
{
Task.Run(() =>
{
SavedState(false);
Bot.Events.MapChanged -= CleanKilledMonstersList;
Bot.Events.MonsterKilled -= KilledMonsterListener;
Bot.Events.ExtensionPacketReceived -= RespawnListener;
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;
public bool StopBotEvent(Exception? e)
{
Bot.Events.ScriptStopping -= StopBotEvent;
SetOptions(false);
return StopBot(e != null);
}
public 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("--------------------------------------");
Bot.Events.ScriptStopping -= CrashDetector;
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 Start/Stop
#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.House.Contains(_itemID))
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;
}
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;