-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAPI.cs
More file actions
3950 lines (3489 loc) · 141 KB
/
API.cs
File metadata and controls
3950 lines (3489 loc) · 141 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.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using ClassicUO.Assets;
using ClassicUO.Configuration;
using ClassicUO.Game;
using ClassicUO.Game.Data;
using ClassicUO.Game.GameObjects;
using ClassicUO.Game.Managers;
using ClassicUO.Game.Managers.Structs;
using ClassicUO.Game.Scenes;
using ClassicUO.Game.UI.Controls;
using ClassicUO.Game.UI.Gumps;
using ClassicUO.LegionScripting.PyClasses;
using ClassicUO.Network;
using ClassicUO.Utility;
using IronPython.Runtime;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.Utils;
using Microsoft.Xna.Framework;
using Control = ClassicUO.Game.UI.Controls.Control;
using Label = ClassicUO.Game.UI.Controls.Label;
using Lock = ClassicUO.Game.Data.Lock;
using CUOKeyboard = ClassicUO.Input.Keyboard;
namespace ClassicUO.LegionScripting
{
/// <summary>
/// Python scripting access point
/// </summary>
public class API : IDisposable
{
private volatile bool disposed = false;
private readonly ScriptFile _scriptFile;
public API(ScriptEngine engine, ScriptFile script)
{
this.engine = engine;
_scriptFile = script;
Events = new PyEvents(engine, this);
Gumps = new PyGumps(this);
}
internal ScriptEngine engine;
internal ConcurrentBag<Gump> gumps = new();
#region Python Callback Queue
private readonly Queue<Action> scheduledCallbacks = new();
private static readonly ConcurrentDictionary<string, object> sharedVars = new();
private readonly ConcurrentDictionary<string, object> hotkeyCallbacks = new();
private readonly ConcurrentDictionary<string, bool> pressedKeys = new();
internal void ScheduleCallback(Action action)
{
lock (scheduledCallbacks)
{
scheduledCallbacks.Enqueue(action);
while (scheduledCallbacks.Count > 100)
{
scheduledCallbacks.Dequeue(); //Limit callback counts
GameActions.Print(World, "Python Scripting Error: Too many callbacks registered!");
}
}
}
internal void ScheduleCallback(object callback, params object[] args)
{
if (callback == null || !engine.Operations.IsCallable(callback))
return;
ScheduleCallback(() =>
{
try
{
engine.Operations.Invoke(callback, args);
}
catch (Exception ex)
{
Console.WriteLine($"Script callback error: {ex}");
}
});
}
/// <summary>
/// Use this when you need to wait for players to click buttons.
/// Example:
/// ```py
/// while True:
/// API.ProcessCallbacks()
/// API.Pause(0.1)
/// ```
/// </summary>
public void ProcessCallbacks()
{
while (true)
{
Action next = null;
lock (scheduledCallbacks)
{
if (scheduledCallbacks.Count > 0)
next = scheduledCallbacks.Dequeue();
}
if (next != null)
next();
else
break;
}
}
#endregion
private ConcurrentBag<uint> ignoreList = new();
private ConcurrentQueue<PyJournalEntry> journalEntries = new();
private ConcurrentQueue<PySoundEntry> soundEntries = new();
internal World World = Client.UnitTestingActive ? new World() : Client.Game.UO.World;
private Item backpack;
private PyPlayer player;
private bool keyboardHooked = false;
private readonly object hookLock = new object();
private void EnsureKeyboardHook()
{
lock (hookLock)
{
if (keyboardHooked) return;
CUOKeyboard.KeyDownEvent += OnKeyDown;
CUOKeyboard.KeyUpEvent += OnKeyUp;
keyboardHooked = true;
}
}
private void OnKeyDown(string hotkey)
{
if (disposed) return;
if (pressedKeys.TryAdd(hotkey, true) && hotkeyCallbacks.TryGetValue(hotkey, out object callback))
{
ScheduleCallback(callback);
}
}
private void OnKeyUp(string hotkey)
{
if (disposed) return;
pressedKeys.TryRemove(hotkey, out _);
}
public void Dispose()
{
if (disposed) return;
disposed = true;
if (keyboardHooked)
{
CUOKeyboard.KeyDownEvent -= OnKeyDown;
CUOKeyboard.KeyUpEvent -= OnKeyUp;
keyboardHooked = false;
}
hotkeyCallbacks.Clear();
pressedKeys.Clear();
}
public ConcurrentQueue<PyJournalEntry> JournalEntries => journalEntries;
public ConcurrentQueue<PySoundEntry> SoundEntries => soundEntries;
#region Properties
/// <summary>
/// Get this scripts full filename
/// </summary>
public string ScriptName => _scriptFile != null ? _scriptFile.FileName : string.Empty;
/// <summary>
/// Get the full path to the file, no filename included. Use API.ScriptName to get the script.
/// </summary>
public string ScriptPath => _scriptFile != null ? _scriptFile.Path : string.Empty;
/// <summary>
/// Get the player's backpack serial
/// </summary>
public uint Backpack
{
get
{
if (backpack == null)
backpack = MainThreadQueue.InvokeOnMainThread(() => World.Player.Backpack);
return backpack;
}
}
/// <summary>
/// Returns the player character object
/// </summary>
public PyPlayer Player
{
get
{
if (player == null)
player = MainThreadQueue.InvokeOnMainThread(() => new PyPlayer(World.Player));
return player;
}
}
/// <summary>
/// Return the player's bank container serial if open, otherwise 0
/// </summary>
public uint Bank
{
get
{
Item i = MainThreadQueue.InvokeOnMainThread(() => World.Player.FindItemByLayer(Layer.Bank));
return i != null ? i.Serial : 0;
}
}
/// <summary>
/// Can be used for random numbers.
/// `API.Random.Next(1, 100)` will return a number between 1 and 100.
/// `API.Random.Next(100)` will return a number between 0 and 100.
/// </summary>
public Random Random { get; set; } = new();
/// <summary>
/// The serial of the last target, if it has a serial.
/// </summary>
public uint LastTargetSerial => MainThreadQueue.InvokeOnMainThread(() => World.TargetManager.LastTargetInfo.Serial);
/// <summary>
/// The last target's position
/// </summary>
public Vector3Int LastTargetPos => MainThreadQueue.InvokeOnMainThread(() => World.TargetManager.LastTargetInfo.Position);
/// <summary>
/// The graphic of the last targeting object
/// </summary>
public ushort LastTargetGraphic => MainThreadQueue.InvokeOnMainThread(() => World.TargetManager.LastTargetInfo.Graphic);
/// <summary>
/// The serial of the last item or mobile from the various findtype/mobile methods
/// </summary>
public uint Found { get; set; }
/// <summary>
/// Access useful player settings.
/// </summary>
public static PyProfile Profile = new();
public PyEvents Events;
public PyGumps Gumps;
/// <summary>
/// Check if the script has been requested to stop.
/// ```py
/// while not API.StopRequested:
/// DoSomeStuff()
/// ```
/// </summary>
public volatile bool StopRequested;
public CancellationTokenSource CancellationToken = new();
#endregion
#region Enum
public enum ScanType
{
Hostile = 0,
Party,
Followers,
Objects,
Mobiles
}
public enum Notoriety : byte
{
Unknown = 0x00,
Innocent = 0x01,
Ally = 0x02,
Gray = 0x03,
Criminal = 0x04,
Enemy = 0x05,
Murderer = 0x06,
Invulnerable = 0x07
}
public enum PersistentVar
{
Char,
Account,
Server,
Global
}
#endregion
#region Methods
/// <summary>
/// Register or unregister a Python callback for a hotkey.
/// ### Register:
/// ```py
/// def on_shift_a():
/// API.SysMsg("SHIFT+A pressed!")
/// API.OnHotKey("SHIFT+A", on_shift_a)
/// while True:
/// API.ProcessCallbacks()
/// API.Pause(0.1)
/// ```
/// ### Unregister:
/// ```py
/// API.OnHotKey("SHIFT+A")
/// ```
/// The <paramref name="key"/> can include modifiers (CTRL, SHIFT, ALT),
/// for example: "CTRL+SHIFT+F1" or "ALT+A".
/// </summary>
/// <param name="key">Key combination to listen for, e.g. "CTRL+SHIFT+F1".</param>
/// <param name="callback">
/// Python function to invoke when the hotkey is pressed.
/// If <c>null</c>, the hotkey will be unregistered.
/// </param>
public void OnHotKey(string key, object callback = null)
{
if (string.IsNullOrEmpty(key))
return;
if (engine == null || engine.Operations == null)
{
return;
}
string normalized = CUOKeyboard.NormalizeKeyString(key);
EnsureKeyboardHook();
if (callback == null || !engine.Operations.IsCallable(callback))
{
hotkeyCallbacks.TryRemove(normalized, out _);
return;
}
hotkeyCallbacks[normalized] = callback;
}
/// <summary>
/// Set a variable that is shared between scripts.
/// Example:
/// ```py
/// API.SetSharedVar("myVar", 10)
/// ```
/// </summary>
/// <param name="name">Name of the var</param>
/// <param name="value">Value, can be a number, text, or *most* other objects too.</param>
public void SetSharedVar(string name, object value) => sharedVars[name] = value;
/// <summary>
/// Get the value of a shared variable.
/// Example:
/// ```py
/// myVar = API.GetSharedVar("myVar")
/// if myVar:
/// API.SysMsg(f"myVar is {myVar}")
/// ```
/// </summary>
/// <param name="name">Name of the var</param>
/// <returns></returns>
public object GetSharedVar(string name)
{
if (sharedVars.TryGetValue(name, out object v))
return v;
return null;
}
/// <summary>
/// Try to remove a shared variable.
/// Example:
/// ```py
/// API.RemoveSharedVar("myVar")
/// ```
/// </summary>
/// <param name="name">Name of the var</param>
public void RemoveSharedVar(string name) => sharedVars.TryRemove(name, out _);
/// <summary>
/// Clear all shared vars.
/// Example:
/// ```py
/// API.ClearSharedVars()
/// ```
/// </summary>
public void ClearSharedVars() => sharedVars.Clear();
/// <summary>
/// Close all gumps created by the API unless marked to remain open.
/// </summary>
public void CloseGumps()
{
int c = 0;
while (gumps.TryTake(out Gump g))
{
if (g is { IsDisposed: false })
MainThreadQueue.EnqueueAction(() => DisposeGump(g));
c++;
if (c > 1000)
break; //Prevent infinite loop just in case.
}
}
/// <summary>
/// Attack a mobile
/// Example:
/// ```py
/// enemy = API.NearestMobile([API.Notoriety.Gray, API.Notoriety.Criminal], 7)
/// if enemy:
/// API.Attack(enemy)
/// ```
/// </summary>
/// <param name="serial"></param>
public void Attack(uint serial) => MainThreadQueue.InvokeOnMainThread(() => GameActions.Attack(World, serial));
/// <summary>
/// Sets the player's war mode state (peace/war toggle).
/// </summary>
/// <param name="enabled">True to enable war mode, false to disable war mode</param>
public void SetWarMode(bool enabled) => MainThreadQueue.InvokeOnMainThread(() => GameActions.RequestWarMode(World.Player, enabled));
/// <summary>
/// Attempt to bandage yourself. Older clients this will not work, you will need to find a bandage, use it, and target yourself.
/// Example:
/// ```py
/// if player.HitsMax - player.Hits > 10 or player.IsPoisoned:
/// if API.BandageSelf():
/// API.CreateCooldownBar(delay, "Bandaging...", 21)
/// API.Pause(8)
/// else:
/// API.SysMsg("WARNING: No bandages!", 32)
/// break
/// ```
/// </summary>
/// <returns>True if bandages found and used</returns>
public bool BandageSelf() => MainThreadQueue.InvokeOnMainThread(() => GameActions.BandageSelf(World));
/// <summary>
/// If you have an item in your left hand, move it to your backpack
/// Sets API.Found to the item's serial.
/// Example:
/// ```py
/// leftHand = API.ClearLeftHand()
/// if leftHand:
/// API.SysMsg("Cleared left hand: " + leftHand.Name)
/// ```
/// </summary>
/// <returns>The item that was in your hand</returns>
public PyItem ClearLeftHand() => MainThreadQueue.InvokeOnMainThread
(() =>
{
Item i = World.Player.FindItemByLayer(Layer.OneHanded);
if (i != null)
{
Item bp = World.Player.Backpack;
ObjectActionQueue.Instance.Enqueue(new MoveRequest(i, bp).ToObjectActionQueueItem(), ActionPriority.MoveItem);
Found = i.Serial;
return new PyItem(i);
}
Found = 0;
return null;
}
);
/// <summary>
/// If you have an item in your right hand, move it to your backpack
/// Sets API.Found to the item's serial.
/// Example:
/// ```py
/// rightHand = API.ClearRightHand()
/// if rightHand:
/// API.SysMsg("Cleared right hand: " + rightHand.Name)
/// ```
/// </summary>
/// <returns>The item that was in your hand</returns>
public PyItem ClearRightHand() => MainThreadQueue.InvokeOnMainThread
(() =>
{
Item i = World.Player.FindItemByLayer(Layer.TwoHanded);
if (i != null)
{
Item bp = World.Player.Backpack;
ObjectActionQueue.Instance.Enqueue(new MoveRequest(i, bp).ToObjectActionQueueItem(), ActionPriority.MoveItem);
Found = i.Serial;
return new PyItem(i);
}
Found = 0;
return null;
}
);
/// <summary>
/// Single click an object
/// Example:
/// ```py
/// API.ClickObject(API.Player)
/// ```
/// </summary>
/// <param name="serial">Serial, or item/mobile reference</param>
public void ClickObject(uint serial) => MainThreadQueue.InvokeOnMainThread(() => GameActions.SingleClick(World, serial));
/// <summary>
/// Attempt to use(double click) an object.
/// Example:
/// ```py
/// API.UseObject(API.Backpack)
/// ```
/// </summary>
/// <param name="serial">The serial</param>
/// <param name="skipQueue">Defaults true, set to false to use a double click queue</param>
public void UseObject(uint serial, bool skipQueue = true) => MainThreadQueue.InvokeOnMainThread
(() =>
{
if (skipQueue)
GameActions.DoubleClick(World, serial);
else
GameActions.DoubleClickQueued(serial);
}
);
/// <summary>
/// Get an item count for the contents of a container
/// Example:
/// ```py
/// count = API.Contents(API.Backpack)
/// if count > 0:
/// API.SysMsg(f"You have {count} items in your backpack")
/// ```
/// </summary>
/// <param name="serial"></param>
/// <returns>The amount of items in a container. Does **not** include sub-containers, or item amounts. (100 Gold = 1 item if it's in a single stack)</returns>
public int Contents(uint serial) => MainThreadQueue.InvokeOnMainThread<int>
(() =>
{
Item i = World.Items.Get(serial);
if (i != null)
return (int)Utility.ContentsCount(i);
return 0;
}
);
/// <summary>
/// Send a context menu(right click menu) response.
/// This does not open the menu, you do not need to open the menu first. This handles both in one action.
/// Example:
/// ```py
/// API.ContextMenu(API.Player, 1)
/// ```
/// </summary>
/// <param name="serial"></param>
/// <param name="entry">Entries start at 0, the top entry will be 0, then 1, 2, etc. (Usually)</param>
public void ContextMenu(uint serial, ushort entry) => MainThreadQueue.InvokeOnMainThread
(() =>
{
PopupMenuGump.CloseNext = serial;
AsyncNetClient.Socket.Send_RequestPopupMenu(serial);
AsyncNetClient.Socket.Send_PopupMenuSelection(serial, entry);
}
);
/// <summary>
/// Send a response to the currently open menu (uses the latest MenuGump).
/// Useful when menu IDs change every time (e.g., Tracking skill).
/// Returns true if a menu was found and a response was sent.
/// </summary>
public bool MenuResponseCurrent(int index, ushort itemGraphic = 0, ushort itemHue = 0) => MainThreadQueue.InvokeOnMainThread<bool>
(() =>
{
MenuGump menu = UIManager.Gumps.OfType<MenuGump>()
.LastOrDefault(g => !g.IsDisposed && g.IsVisible);
if (menu == null)
return false;
AsyncNetClient.Socket.Send_MenuResponse(menu.LocalSerial, (ushort)menu.ServerSerial, index, itemGraphic, itemHue);
menu.Dispose();
return true;
}
);
/// <summary>
/// Retrieve the current open menu's (uses the latest MenuGump) menu item descriptions.
/// Useful when menu IDs change every time (e.g., Tracking skill).
/// </summary>
/// <returns>List of <see cref="PyMenuItem"/> containing Index, Name, Graphic and Hue values for each menu item</returns>
public PythonList MenuItemsCurrent() => MainThreadQueue.InvokeOnMainThread<PythonList>
(() =>
{
MenuGump menu = UIManager.Gumps
.OfType<MenuGump>()
.LastOrDefault(g => !g.IsDisposed && g.IsVisible);
if (menu is null)
return [];
PythonList items = [];
items.AddRange(menu.MenuItemsMetadata.Select(mim => new PyMenuItem(mim.Index, mim.Name, mim.Graphic, mim.Hue)));
return items;
}
);
/// <summary>
/// Send a response to the currently open gray menu (text list menu).
/// Returns true if a gray menu was found and a response was sent.
/// </summary>
public bool GrayMenuResponseCurrent(ushort index) => MainThreadQueue.InvokeOnMainThread<bool>
(() =>
{
GrayMenuGump menu = UIManager.Gumps.OfType<GrayMenuGump>()
.LastOrDefault(g => !g.IsDisposed && g.IsVisible);
if (menu == null)
return false;
AsyncNetClient.Socket.Send_GrayMenuResponse(menu.LocalSerial, (ushort)menu.ServerSerial, index);
menu.Dispose();
return true;
}
);
/// <summary>
/// Attempt to equip an item. Layer is automatically detected.
/// Example:
/// ```py
/// lefthand = API.ClearLeftHand()
/// API.Pause(2)
/// API.EquipItem(lefthand)
/// ```
/// </summary>
/// <param name="serial"></param>
public void EquipItem(uint serial) => MainThreadQueue.InvokeOnMainThread
(() =>
{
if(ProfileManager.CurrentProfile.QueueManualItemMoves && World.Items.Get(serial) is Item i)
ObjectActionQueue.Instance.Enqueue(ObjectActionQueueItem.EquipItem(serial, (Layer)i.ItemData.Layer), ActionPriority.EquipItem);
else
{
GameActions.PickUp(World, serial, 0, 0, 1);
GameActions.Equip(World);
}
}
);
/// <summary>
/// Clear the move item que of all items.
/// </summary>
public void ClearMoveQueue() => MainThreadQueue.InvokeOnMainThread(() => ObjectActionQueue.Instance.ClearByPriority(ActionPriority.MoveItem));
/// <summary>
/// Move an item to another container.
/// Use x, and y if you don't want items stacking in the desination container.
/// Example:
/// ```py
/// items = API.ItemsInContainer(API.Backpack)
///
/// API.SysMsg("Target your fish barrel", 32)
/// barrel = API.RequestTarget()
///
///
/// if len(items) > 0 and barrel:
/// for item in items:
/// data = API.ItemNameAndProps(item)
/// if data and "An Exotic Fish" in data:
/// API.QueueMoveItem(item, barrel)
/// ```
/// </summary>
/// <param name="serial"></param>
/// <param name="destination"></param>
/// <param name="amt">Amount to move</param>
/// <param name="x">X coordinate inside a container</param>
/// <param name="y">Y coordinate inside a container</param>
public void QueueMoveItem(uint serial, uint destination, ushort amt = 0, int x = 0xFFFF, int y = 0xFFFF) => MainThreadQueue.InvokeOnMainThread
(() =>
{
ObjectActionQueue.Instance.Enqueue(new MoveRequest(serial, destination, amt, x, y).ToObjectActionQueueItem(), ActionPriority.MoveItem);
}
);
/// <summary>
/// Move an item to another container.
/// Use x, and y if you don't want items stacking in the desination container.
/// Example:
/// ```py
/// items = API.ItemsInContainer(API.Backpack)
///
/// API.SysMsg("Target your fish barrel", 32)
/// barrel = API.RequestTarget()
///
///
/// if len(items) > 0 and barrel:
/// for item in items:
/// data = API.ItemNameAndProps(item)
/// if data and "An Exotic Fish" in data:
/// API.MoveItem(item, barrel)
/// API.Pause(0.75)
/// ```
/// </summary>
/// <param name="serial"></param>
/// <param name="destination"></param>
/// <param name="amt">Amount to move</param>
/// <param name="x">X coordinate inside a container</param>
/// <param name="y">Y coordinate inside a container</param>
public void MoveItem(uint serial, uint destination, int amt = 0, int x = 0xFFFF, int y = 0xFFFF) => MainThreadQueue.InvokeOnMainThread
(() =>
{
GameActions.PickUp(World, serial, 0, 0, amt);
GameActions.DropItem(serial, x, y, 0, destination);
}
);
/// <summary>
/// Move an item to the ground near you.
/// Example:
/// ```py
/// items = API.ItemsInContainer(API.Backpack)
/// for item in items:
/// API.QueueMoveItemOffset(item, 0, 1, 0, 0)
/// ```
/// </summary>
/// <param name="serial"></param>
/// <param name="amt">0 to grab entire stack</param>
/// <param name="x">Offset from your location</param>
/// <param name="y">Offset from your location</param>
/// <param name="z">Offset from your location. Leave blank in most cases</param>
/// <param name="OSI">True if you are playing OSI</param>
public void QueueMoveItemOffset(uint serial, ushort amt = 0, int x = 0, int y = 0, int z = 0, bool OSI = false) => MainThreadQueue.InvokeOnMainThread
(() =>
{
World.Map.GetMapZ(World.Player.X + x, World.Player.Y + y, out sbyte gz, out sbyte gz2);
bool useCalculatedZ = false;
if (gz > z)
{
z = gz;
useCalculatedZ = true;
}
if (gz2 > z)
{
z = gz2;
useCalculatedZ = true;
}
if (!useCalculatedZ)
z = World.Player.Z + z;
ObjectActionQueue.Instance.Enqueue(new MoveRequest(serial, OSI ? uint.MaxValue : 0, amt, World.Player.X + x, World.Player.Y + y, z).ToObjectActionQueueItem(), ActionPriority.MoveItem);
}
);
/// <summary>
/// Move an item to the ground near you.
/// Example:
/// ```py
/// items = API.ItemsInContainer(API.Backpack)
/// for item in items:
/// API.MoveItemOffset(item, 0, 1, 0, 0)
/// API.Pause(0.75)
/// ```
/// </summary>
/// <param name="serial"></param>
/// <param name="amt">0 to grab entire stack</param>
/// <param name="x">Offset from your location</param>
/// <param name="y">Offset from your location</param>
/// <param name="z">Offset from your location. Leave blank in most cases</param>
/// <param name="OSI">True if you are playing OSI</param>
public void MoveItemOffset(uint serial, int amt = 0, int x = 0, int y = 0, int z = 0, bool OSI = false) => MainThreadQueue.InvokeOnMainThread
(() =>
{
World.Map.GetMapZ(World.Player.X + x, World.Player.Y + y, out sbyte gz, out sbyte gz2);
bool useCalculatedZ = false;
if (gz > z)
{
z = gz;
useCalculatedZ = true;
}
if (gz2 > z)
{
z = gz2;
useCalculatedZ = true;
}
if (!useCalculatedZ)
z = World.Player.Z + z;
GameActions.PickUp(World, serial, 0, 0, amt);
GameActions.DropItem(serial, World.Player.X + x, World.Player.Y + y, z, OSI ? uint.MaxValue : 0);
}
);
/// <summary>
/// Use a skill.
/// Example:
/// ```py
/// API.UseSkill("Hiding")
/// API.Pause(11)
/// ```
/// </summary>
/// <param name="skillName">Can be a partial match. Will match the first skill containing this text.</param>
public void UseSkill(string skillName) => MainThreadQueue.InvokeOnMainThread
(() =>
{
if (skillName.Length > 0)
{
for (int i = 0; i < World.Player.Skills.Length; i++)
{
if (World.Player.Skills[i].Name.IndexOf(skillName, StringComparison.OrdinalIgnoreCase) >= 0)
{
GameActions.UseSkill(World.Player.Skills[i].Index);
break;
}
}
}
}
);
/// <summary>
/// Attempt to cast a spell by its name.
/// Example:
/// ```py
/// API.CastSpell("Fireball")
/// API.WaitForTarget()
/// API.Target(API.Player)
/// ```
/// </summary>
/// <param name="spellName">This can be a partial match. Fireba will cast Fireball.</param>
public void CastSpell(string spellName) => MainThreadQueue.InvokeOnMainThread(() =>
{
if(!GameActions.CastSpellByName(spellName, false))
GameActions.CastSpellByName(spellName);
});
/// <summary>
/// Dress from a saved dress configuration.
/// Example:
/// ```py
/// API.Dress("PvP Gear")
/// ```
/// </summary>
/// <param name="name">The name of the dress configuration</param>
public void Dress(string name) => MainThreadQueue.InvokeOnMainThread(() =>
{
if (string.IsNullOrEmpty(name))
return;
DressConfig config = DressAgentManager.Instance.CurrentPlayerConfigs
.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
if (config != null)
{
DressAgentManager.Instance.DressFromConfig(config);
}
});
/// <summary>
/// Undress from a saved dress configuration.
/// Example:
/// ```py
/// API.Undress("PvP Gear")
/// ```
/// </summary>
/// <param name="name">The name of the dress configuration</param>
public void Undress(string name) => MainThreadQueue.InvokeOnMainThread(() =>
{
if (string.IsNullOrEmpty(name))
return;
DressConfig config = DressAgentManager.Instance.CurrentPlayerConfigs
.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
if (config != null)
{
DressAgentManager.Instance.UndressFromConfig(config);
}
});
/// <summary>
/// Undress all your equipment
/// </summary>
/// <param name="kr">True to use the faster KR packet(not supported everywhere)</param>
public void UndressAll(bool kr = false) => MainThreadQueue.InvokeOnMainThread(() =>
{
DressAgentManager.Instance.UndressAll(kr);
});
/// <summary>
/// Get all available dress configurations.
/// Example:
/// ```py
/// outfits = API.GetAvailableDressOutfits()
/// if outfits:
/// Dress(outfits[0])
/// ```
/// </summary>
/// <returns>Returns a list of outfit names for use with Dress(outfitname)</returns>
public PythonList GetAvailableDressOutfits() => MainThreadQueue.InvokeOnMainThread(() =>
{
PythonList list = new();
foreach (DressConfig config in DressAgentManager.Instance.CurrentPlayerConfigs)
{
list.Add(config.Name);
}
return list;
});
/// <summary>
/// Runs an organizer agent to move items between containers.
/// Example:
/// ```py
/// # Run organizer with default containers
/// API.Organizer("MyOrganizer")
///
/// # Run organizer with specific source and destination
/// API.Organizer("MyOrganizer", 0x40001234, 0x40005678)
/// ```
/// </summary>
/// <param name="name">The name of the organizer configuration to run</param>
/// <param name="source">Optional serial of the source container (0 for default)</param>
/// <param name="destination">Optional serial of the destination container (0 for default)</param>
public void Organizer(string name, uint source = 0, uint destination = 0)
{
if (string.IsNullOrEmpty(name))
{
GameActions.Print("Invalid organizer name", Constants.HUE_ERROR);
return;
}
OrganizerAgent.Instance.RunOrganizer(name, source, destination);
}
/// <summary>
/// Executes a client command as if typed in the game console
/// </summary>
/// <param name="command">The command to execute (including any arguments)</param>
public void ClientCommand(string command)
{
if (string.IsNullOrEmpty(command))
{
GameActions.Print("Command can't be empty", Constants.HUE_ERROR);
return;
}
string[] split = command.Split(' ');
World.Instance.CommandManager.Execute(split[0], split);
}
/// <summary>
/// Check if a buff is active.
/// Example:
/// ```py
/// if API.BuffExists("Bless"):
/// API.SysMsg("You are blessed!")
/// ```
/// </summary>
/// <param name="buffName">The name/title of the buff</param>
/// <returns></returns>
public bool BuffExists(string buffName) => MainThreadQueue.InvokeOnMainThread
(() =>
{
if (string.IsNullOrEmpty(buffName) || World == null || World.Player == null)
return false;
foreach (BuffIcon buff in World.Player.BuffIcons.Values)
{
if (buff == null) continue;