-
Notifications
You must be signed in to change notification settings - Fork 397
/
ChatBot.cs
1738 lines (1556 loc) · 73.7 KB
/
ChatBot.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Brigadier.NET;
using MinecraftClient.CommandHandler;
using MinecraftClient.Inventory;
using MinecraftClient.Mapping;
using static MinecraftClient.Settings;
namespace MinecraftClient.Scripting
{
///
/// Welcome to the Bot API file !
/// The virtual class "ChatBot" contains anything you need for creating chat bots
/// Inherit from this class while adding your bot class to the "ChatBots" folder.
/// Override the methods you want for handling events: Initialize, Update, GetText.
///
/// For testing your bot you can add it in McClient.cs (see comment at line ~199).
/// Your bot will be loaded everytime MCC is started so that you can test/debug.
///
/// Once your bot is fully written and tested, you can export it a standalone script.
/// This way it can be loaded in newer MCC builds, without modifying MCC itself.
/// See config/sample-script-with-chatbot.cs for a ChatBot script example.
///
/// <summary>
/// The virtual class containing anything you need for creating chat bots.
/// </summary>
public abstract class ChatBot
{
public enum DisconnectReason { InGameKick, LoginRejected, ConnectionLost, UserLogout };
//Handler will be automatically set on bot loading, don't worry about this
public void SetHandler(McClient handler) { _handler = handler; }
protected void SetMaster(ChatBot master) { this.master = master; }
protected void LoadBot(ChatBot bot) { Handler.BotUnLoad(bot); Handler.BotLoad(bot); }
protected List<ChatBot> GetLoadedChatBots() { return Handler.GetLoadedChatBots(); }
protected void UnLoadBot(ChatBot bot) { Handler.BotUnLoad(bot); }
private McClient? _handler = null;
private ChatBot? master = null;
private readonly List<string> registeredPluginChannels = new();
private readonly object delayTasksLock = new();
private readonly List<TaskWithDelay> delayedTasks = new();
protected McClient Handler
{
get
{
if (master != null)
return master.Handler;
if (_handler != null)
return _handler;
throw new InvalidOperationException(Translations.exception_chatbot_init);
}
}
/// <summary>
/// Will be called every ~100ms.
/// </summary>
/// <remarks>
/// <see cref="Update"/> method can be overridden by child class so need an extra update method
/// </remarks>
public void UpdateInternal()
{
lock (delayTasksLock)
{
if (delayedTasks.Count > 0)
{
List<int> tasksToRemove = new();
for (int i = 0; i < delayedTasks.Count; i++)
{
if (delayedTasks[i].Tick())
{
delayedTasks[i].Task();
tasksToRemove.Add(i);
}
}
if (tasksToRemove.Count > 0)
{
tasksToRemove.Sort((a, b) => b.CompareTo(a)); // descending sort
foreach (int index in tasksToRemove)
{
delayedTasks.RemoveAt(index);
}
}
}
}
}
/* ================================================== */
/* Main methods to override for creating your bot */
/* ================================================== */
/// <summary>
/// Anything you want to initialize your bot, will be called on load by MinecraftCom
/// This method is called only once, whereas AfterGameJoined() is called once per server join.
///
/// NOTE: Chat messages cannot be sent at this point in the login process.
/// If you want to send a message when the bot is loaded, use AfterGameJoined.
/// </summary>
public virtual void Initialize() { }
/// <summary>
/// This method is called when the bot is being unloaded, you can use it to free up resources like DB connections
/// </summary>
public virtual void OnUnload() { }
/// <summary>
/// Called after the server has been joined successfully and chat messages are able to be sent.
/// This method is called again after reconnecting to the server, whereas Initialize() is called only once.
///
/// NOTE: This is not always right after joining the server - if the bot was loaded after logging
/// in this is still called.
/// </summary>
public virtual void AfterGameJoined() { }
/// <summary>
/// Will be called every ~100ms (10fps) if loaded in MinecraftCom
/// </summary>
public virtual void Update() { }
/// <summary>
/// Will be called every player break block in gamemode 0
/// </summary>
/// <param name="entity">Player</param>
/// <param name="location">Block location</param>
/// <param name="stage">Destroy stage, maximum 255</param>
public virtual void OnBlockBreakAnimation(Entity entity, Location location, byte stage) { }
/// <summary>
/// Will be called every animations of the hit and place block
/// </summary>
/// <param name="entity">Player</param>
/// <param name="animation">0 = LMB, 1 = RMB (RMB Corrent not work)</param>
public virtual void OnEntityAnimation(Entity entity, byte animation) { }
/// <summary>
/// Any text sent by the server will be sent here by MinecraftCom
/// </summary>
/// <param name="text">Text from the server</param>
public virtual void GetText(string text) { }
/// <summary>
/// Any text sent by the server will be sent here by MinecraftCom (extended variant)
/// </summary>
/// <remarks>
/// You can use Json.ParseJson() to process the JSON string.
/// </remarks>
/// <param name="text">Text from the server</param>
/// <param name="json">Raw JSON from the server. This parameter will be NULL on MC 1.5 or lower!</param>
public virtual void GetText(string text, string? json) { }
/// <summary>
/// Is called when the client has been disconnected fom the server
/// </summary>
/// <param name="reason">Disconnect Reason</param>
/// <param name="message">Kick message, if any</param>
/// <returns>Return TRUE if the client is about to restart</returns>
public virtual bool OnDisconnect(DisconnectReason reason, string message) { return false; }
/// <summary>
/// Called when a plugin channel message is received.
/// The given channel must have previously been registered with RegisterPluginChannel.
/// This can be used to communicate with server mods or plugins. See wiki.vg for more
/// information about plugin channels: http://wiki.vg/Plugin_channel
/// </summary>
/// <param name="channel">The name of the channel</param>
/// <param name="data">The payload for the message</param>
public virtual void OnPluginMessage(string channel, byte[] data) { }
/// <summary>
/// Called when properties for the Player entity are received from the server
/// </summary>
/// <param name="prop">Dictionary of player properties</param>
public virtual void OnPlayerProperty(Dictionary<string, double> prop) { }
/// <summary>
/// Called when server TPS are recalculated by MCC based on world time updates
/// </summary>
/// <param name="tps">New estimated server TPS (between 0 and 20)</param>
public virtual void OnServerTpsUpdate(double tps) { }
/// <summary>
/// Called when a time changed
/// </summary>
/// <param name="WorldAge">World age</param>
/// <param name="TimeOfDay">Time</param>
public virtual void OnTimeUpdate(long WorldAge, long TimeOfDay) { }
/// <summary>
/// Called when an entity moved nearby
/// </summary>
/// <param name="entity">Entity with updated location</param>
public virtual void OnEntityMove(Entity entity) { }
/// <summary>
/// Called when an entity rotates
/// </summary>
/// <param name="entity">Entity with updated rotation</param>
public virtual void OnEntityRotate(Entity entity) { }
/// <summary>
/// Called after an internal MCC command has been performed
/// </summary>
/// <param name="commandName">MCC Command Name</param>
/// <param name="commandParams">MCC Command Parameters</param>
/// <param name="Result">MCC command result</param>
public virtual void OnInternalCommand(string commandName, string commandParams, CmdResult Result) { }
/// <summary>
/// Called when an entity spawned nearby
/// </summary>
/// <param name="entity">New Entity</param>
public virtual void OnEntitySpawn(Entity entity) { }
/// <summary>
/// Called when an entity despawns/dies nearby
/// </summary>
/// <param name="entity">Entity wich has just disappeared</param>
public virtual void OnEntityDespawn(Entity entity) { }
/// <summary>
/// Called when the player held item has changed
/// </summary>
/// <param name="slot">New slot ID</param>
public virtual void OnHeldItemChange(byte slot) { }
/// <summary>
/// Called when the player health has been updated
/// </summary>
/// <param name="health">New player health</param>
/// <param name="food">New food level</param>
public virtual void OnHealthUpdate(float health, int food) { }
/// <summary>
/// Called when an explosion occurs on the server
/// </summary>
/// <param name="explode">Explosion location</param>
/// <param name="strength">Explosion strength</param>
/// <param name="recordcount">Amount of blocks blown up</param>
public virtual void OnExplosion(Location explode, float strength, int recordcount) { }
/// <summary>
/// Called when experience updates
/// </summary>
/// <param name="Experiencebar">Between 0 and 1</param>
/// <param name="Level">Level</param>
/// <param name="TotalExperience">Total Experience</param>
public virtual void OnSetExperience(float Experiencebar, int Level, int TotalExperience) { }
/// <summary>
/// Called when the Game Mode has been updated for a player
/// </summary>
/// <param name="playername">Player Name</param>
/// <param name="uuid">Player UUID</param>
/// <param name="gamemode">New Game Mode (0: Survival, 1: Creative, 2: Adventure, 3: Spectator).</param>
public virtual void OnGamemodeUpdate(string playername, Guid uuid, int gamemode) { }
/// <summary>
/// Called when the Latency has been updated for a player
/// </summary>
/// <param name="playername">Player Name</param>
/// <param name="uuid">Player UUID</param>
/// <param name="latency">Latency.</param>
public virtual void OnLatencyUpdate(string playername, Guid uuid, int latency) { }
/// <summary>
/// Called when the Latency has been updated for a player
/// </summary>
/// <param name="entity">Entity</param>
/// <param name="playername">Player Name</param>
/// <param name="uuid">Player UUID</param>
/// <param name="latency">Latency.</param>
public virtual void OnLatencyUpdate(Entity entity, string playername, Guid uuid, int latency) { }
/// <summary>
/// Called when an update of the map is sent by the server, take a look at https://wiki.vg/Protocol#Map_Data for more info on the fields
/// Map format and colors: https://minecraft.wiki/w/Map_item_format
/// </summary>
/// <param name="mapid">Map ID of the map being modified</param>
/// <param name="scale">A scale of the Map, from 0 for a fully zoomed-in map (1 block per pixel) to 4 for a fully zoomed-out map (16 blocks per pixel)</param>
/// <param name="trackingposition">Specifies whether player and item frame icons are shown </param>
/// <param name="locked">True if the map has been locked in a cartography table </param>
/// <param name="icons">A list of MapIcon objects of map icons, send only if trackingPosition is true</param>
/// <param name="columnsUpdated">Numbs of columns that were updated (map width) (NOTE: If it is 0, the next fields are not used/are set to default values of 0 and null respectively)</param>
/// <param name="rowsUpdated">Map height</param>
/// <param name="mapCoulmnX">x offset of the westernmost column</param>
/// <param name="mapRowZ">z offset of the northernmost row</param>
/// <param name="colors">a byte array of colors on the map</param>
public virtual void OnMapData(int mapid, byte scale, bool trackingPosition, bool locked, List<MapIcon> icons, byte columnsUpdated, byte rowsUpdated, byte mapCoulmnX, byte mapRowZ, byte[]? colors) { }
/// <summary>
/// Called when tradeList is received from server
/// </summary>
/// <param name="windowID">Window ID</param>
/// <param name="trades">List of trades.</param>
/// <param name="villagerInfo">Contains Level, Experience, IsRegularVillager and CanRestock .</param>
public virtual void OnTradeList(int windowID, List<VillagerTrade> trades, VillagerInfo villagerInfo) { }
/// <summary>
/// Called when received a title from the server
/// <param name="action"> 0 = set title, 1 = set subtitle, 3 = set action bar, 4 = set times and display, 4 = hide, 5 = reset</param>
/// <param name="titletext"> title text</param>
/// <param name="subtitletext"> suntitle text</param>
/// <param name="actionbartext"> action bar text</param>
/// <param name="fadein"> Fade In</param>
/// <param name="stay"> Stay</param>
/// <param name="fadeout"> Fade Out</param>
/// <param name="json"> json text</param>
public virtual void OnTitle(int action, string titletext, string subtitletext, string actionbartext, int fadein, int stay, int fadeout, string json) { }
/// <summary>
/// Called when an entity equipped
/// </summary>
/// <param name="entity"> Entity</param>
/// <param name="slot"> Equipment slot. 0: main hand, 1: off hand, 2–5: armor slot (2: boots, 3: leggings, 4: chestplate, 5: helmet)</param>
/// <param name="item"> Item)</param>
public virtual void OnEntityEquipment(Entity entity, int slot, Item? item) { }
/// <summary>
/// Called when an entity has effect applied
/// </summary>
/// <param name="entity">entity</param>
/// <param name="effect">effect id</param>
/// <param name="amplifier">effect amplifier</param>
/// <param name="duration">effect duration</param>
/// <param name="flags">effect flags</param>
public virtual void OnEntityEffect(Entity entity, Effects effect, int amplifier, int duration, byte flags) { }
/// <summary>
/// Called when a scoreboard objective updated
/// </summary>
/// <param name="objectiveName">objective name</param>
/// <param name="mode">0 to create the scoreboard. 1 to remove the scoreboard. 2 to update the display text.</param>
/// <param name="objectiveValue">Only if mode is 0 or 2. The text to be displayed for the score</param>
/// <param name="type">Only if mode is 0 or 2. 0 = "integer", 1 = "hearts".</param>
/// <param name="numberFormat">Number format: 0 - blank, 1 - styled, 2 - fixed</param>
public virtual void OnScoreboardObjective(string objectiveName, byte mode, string objectiveValue, int type, string json, int numberFormat) { }
/// <summary>
/// Called when a scoreboard updated
/// </summary>
/// <param name="entityName">The entity whose score this is. For players, this is their username; for other entities, it is their UUID.</param>
/// <param name="action">0 to create/update an item. 1 to remove an item.</param>
/// <param name="objectiveName">The name of the objective the score belongs to</param>
/// <param name="objectiveDisplayName">The name of the objective the score belongs to, but with chat formatting</param>
/// <param name="value">The score to be displayed next to the entry. Only sent when Action does not equal 1.</param>
/// <param name="numberFormat">Number format: 0 - blank, 1 - styled, 2 - fixed</param>
public virtual void OnUpdateScore(string entityName, int action, string objectiveName, string objectiveDisplayName, int value, int numberFormat) { }
/// <summary>
/// Called when the client received the Tab Header and Footer
/// </summary>
/// <param name="header">Header</param>
/// <param name="footer">Footer</param>
public virtual void OnTabListHeaderAndFooter(string header, string footer) { }
/// <summary>
/// Called when an inventory/container was updated by server
/// </summary>
/// <param name="inventoryId"></param>
public virtual void OnInventoryUpdate(int inventoryId) { }
/// <summary>
/// Called when a container was opened
/// </summary>
/// <param name="inventoryId"></param>
public virtual void OnInventoryOpen(int inventoryId) { }
/// <summary>
/// Called when a container was closed
/// </summary>
/// <param name="inventoryId"></param>
public virtual void OnInventoryClose(int inventoryId) { }
/// <summary>
/// When received inventory/container/window properties from the server.
/// Used for Frunaces, Enchanting Table, Beacon, Brewing stand, Stone cutter, Loom and Lectern
/// More info about: https://wiki.vg/Protocol#Set_Container_Property
/// </summary>
/// <param name="inventoryID">Inventory ID</param>
/// <param name="propertyId">Property ID</param>
/// <param name="propertyValue">Property Value</param>
public virtual void OnInventoryProperties(byte inventoryID, short propertyId, short propertyValue) { }
/// <summary>
/// When received enchantments from the server this method is called
/// Enchantment levels are the levels of enchantment (eg. I, II, III, IV, V) (eg. Smite IV, Power III, Knockback II ..)
/// Enchantment level requirements are the levels that player needs to have in order to enchant the item
/// </summary>
/// <param name="topEnchantment">Enchantment in the top most slot</param>
/// <param name="middleEnchantment">Enchantment in the middle slot</param>
/// <param name="bottomEnchantment">Enchantment in the bottom slot</param>
/// <param name="topEnchantmentLevel">Enchantment level for the enchantment in the top most slot</param>
/// <param name="middleEnchantmentLevel">Enchantment level for the enchantment in the middle slot</param>
/// <param name="bottomEnchantmentLevel">Enchantment level for the enchantment in the bottom slot</param>
/// <param name="topEnchantmentLevelRequirement">Levels required by player for the enchantment in the top most slot</param>
/// <param name="middleEnchantmentLevelRequirement">Levels required by player for the enchantment in the middle slot</param>
/// <param name="bottomEnchantmentLevelRequirement">Levels required by player for the enchantment in the bottom slot</param>
public virtual void OnEnchantments(
Enchantment topEnchantment,
Enchantment middleEnchantment,
Enchantment bottomEnchantment,
short topEnchantmentLevel,
short middleEnchantmentLevel,
short bottomEnchantmentLevel,
short topEnchantmentLevelRequirement,
short middleEnchantmentLevelRequirement,
short bottomEnchantmentLevelRequirement)
{ }
/// <summary>
/// When received enchantments from the server this method is called
/// Enchantment levels are the levels of enchantment (eg. I, II, III, IV, V) (eg. Smite IV, Power III, Knockback II ..)
/// Enchantment level requirements are the levels that player needs to have in order to enchant the item
/// </summary>
/// <param name="enchantment">Enchantment data/info</param>
public virtual void OnEnchantments(EnchantmentData enchantment) { }
/// <summary>
/// Called when a player joined the game
/// </summary>
/// <param name="uuid">UUID of the player</param>
/// <param name="name">Name of the player</param>
public virtual void OnPlayerJoin(Guid uuid, string name) { }
/// <summary>
/// Called when a player left the game
/// </summary>
/// <param name="uuid">UUID of the player</param>
/// <param name="name">Name of the player</param>
public virtual void OnPlayerLeave(Guid uuid, string? name) { }
/// <summary>
/// This method is called when a player has been killed by another entity
/// </summary>
/// <param name="killerEntity">Killer's entity</param>
/// <param name="chatMessage">message sent in chat when player is killed</param>
public virtual void OnKilled(Entity killerEntity, string chatMessage) { }
/// <summary>
/// Called when the player dies
/// For getting the info about the player/entity who killed the player use OnPlayerKilled
/// </summary>
public virtual void OnDeath() { }
/// <summary>
/// Called when the player respawns
/// </summary>
public virtual void OnRespawn() { }
/// <summary>
/// Called when the health of an entity changed
/// </summary>
/// <param name="entity">Entity</param>
/// <param name="health">The health of the entity</param>
public virtual void OnEntityHealth(Entity entity, float health) { }
/// <summary>
/// Called when the metadata of an entity changed
/// </summary>
/// <param name="entity">Entity</param>
/// <param name="metadata">The metadata of the entity</param>
public virtual void OnEntityMetadata(Entity entity, Dictionary<int, object?> metadata) { }
/// <summary>
/// Called when the status of client player have been changed
/// </summary>
/// <param name="statusId"></param>
public virtual void OnPlayerStatus(byte statusId) { }
/// <summary>
/// Called when a network packet received or sent
/// </summary>
/// <remarks>
/// You need to enable this event by calling <see cref="SetNetworkPacketEventEnabled(bool)"/> with True before you can use this event
/// </remarks>
/// <param name="packetID">Packet ID</param>
/// <param name="packetData">A copy of Packet Data</param>
/// <param name="isLogin">The packet is login phase or playing phase</param>
/// <param name="isInbound">The packet is received from server or sent by client</param>
public virtual void OnNetworkPacket(int packetID, List<byte> packetData, bool isLogin, bool isInbound) { }
/// <summary>
/// Called when the rain level have been changed
/// </summary>
/// <param name="level"></param>
public virtual void OnRainLevelChange(float level) { }
/// <summary>
/// Called when the thunder level have been changed
/// </summary>
/// <param name="level"></param>
public virtual void OnThunderLevelChange(float level) { }
/// <summary>
/// Called when a block is changed.
/// </summary>
/// <param name="location">The location of the block.</param>
/// <param name="block">The block</param>
public virtual void OnBlockChange(Location location, Block block) { }
/* =================================================================== */
/* ToolBox - Methods below might be useful while creating your bot. */
/* You should not need to interact with other classes of the program. */
/* All the methods in this ChatBot class should do the job for you. */
/* =================================================================== */
/// <summary>
/// Send text to the server. Can be anything such as chat messages or commands
/// </summary>
/// <param name="text">Text to send to the server</param>
/// <param name="sendImmediately">Bypass send queue (Deprecated, still there for compatibility purposes but ignored)</param>
/// <returns>TRUE if successfully sent (Deprectated, always returns TRUE for compatibility purposes with existing scripts)</returns>
protected bool SendText(string text, bool sendImmediately = false)
{
LogToConsole("Sending '" + text + "'");
Handler.SendText(text);
return true;
}
/// <summary>
/// Perform an internal MCC command (not a server command, use SendText() instead for that!)
/// </summary>
/// <param name="command">The command to process</param>
/// <param name="localVars">Local variables passed along with the command</param>
/// <returns>TRUE if the command was indeed an internal MCC command</returns>
protected bool PerformInternalCommand(string command, Dictionary<string, object>? localVars = null)
{
CmdResult temp = new();
return Handler.PerformInternalCommand(command, ref temp, localVars);
}
/// <summary>
/// Perform an internal MCC command (not a server command, use SendText() instead for that!)
/// </summary>
/// <param name="command">The command to process</param>
/// <param name="response_msg">May contain a confirmation or error message after processing the command, or "" otherwise.</param>
/// <param name="localVars">Local variables passed along with the command</param>
/// <returns>TRUE if the command was indeed an internal MCC command</returns>
protected bool PerformInternalCommand(string command, ref CmdResult result, Dictionary<string, object>? localVars = null)
{
return Handler.PerformInternalCommand(command, ref result, localVars);
}
/// <summary>
/// Remove color codes ("§c") from a text message received from the server
/// </summary>
public static string GetVerbatim(string? text)
{
if (string.IsNullOrEmpty(text))
return string.Empty;
int idx = 0;
var data = new char[text.Length];
for (int i = 0; i < text.Length; i++)
if (text[i] != '§')
data[idx++] = text[i];
else
i++;
return new string(data, 0, idx);
}
/// <summary>
/// Verify that a string contains only a-z A-Z 0-9 and _ characters.
/// </summary>
public static bool IsValidName(string username)
{
if (string.IsNullOrEmpty(username))
return false;
foreach (char c in username)
if (!(c >= 'a' && c <= 'z'
|| c >= 'A' && c <= 'Z'
|| c >= '0' && c <= '9'
|| c == '_'))
return false;
return true;
}
/// <summary>
/// Returns true if the text passed is a private message sent to the bot
/// </summary>
/// <param name="text">text to test</param>
/// <param name="message">if it's a private message, this will contain the message</param>
/// <param name="sender">if it's a private message, this will contain the player name that sends the message</param>
/// <returns>Returns true if the text is a private message</returns>
protected static bool IsPrivateMessage(string text, ref string message, ref string sender)
{
if (string.IsNullOrEmpty(text))
return false;
text = GetVerbatim(text);
//User-defined regex for private chat messages
if (Config.ChatFormat.UserDefined && !string.IsNullOrWhiteSpace(Config.ChatFormat.Private))
{
Match regexMatch = Regex.Match(text, Config.ChatFormat.Private);
if (regexMatch.Success && regexMatch.Groups.Count >= 3)
{
sender = regexMatch.Groups[1].Value;
message = regexMatch.Groups[2].Value;
return IsValidName(sender);
}
}
//Built-in detection routine for private messages
if (Config.ChatFormat.Builtins)
{
string[] tmp = text.Split(' ');
try
{
//Detect vanilla /tell messages
//Someone whispers message (MC 1.5)
//Someone whispers to you: message (MC 1.7)
if (tmp.Length > 2 && tmp[1] == "whispers")
{
if (tmp.Length > 4 && tmp[2] == "to" && tmp[3] == "you:")
{
message = text[(tmp[0].Length + 18)..]; //MC 1.7
}
else message = text[(tmp[0].Length + 10)..]; //MC 1.5
sender = tmp[0];
return IsValidName(sender);
}
//Detect Essentials (Bukkit) /m messages
//[Someone -> me] message
//[~Someone -> me] message
else if (text[0] == '[' && tmp.Length > 3 && tmp[1] == "->"
&& (tmp[2].ToLower() == "me]" || tmp[2].ToLower() == "moi]")) //'me' is replaced by 'moi' in french servers
{
message = text[(tmp[0].Length + 4 + tmp[2].Length + 1)..];
sender = tmp[0][1..];
if (sender[0] == '~') { sender = sender[1..]; }
return IsValidName(sender);
}
//Detect Modified server messages. /m
//[Someone @ me] message
else if (text[0] == '[' && tmp.Length > 3 && tmp[1] == "@"
&& (tmp[2].ToLower() == "me]" || tmp[2].ToLower() == "moi]")) //'me' is replaced by 'moi' in french servers
{
message = text[(tmp[0].Length + 4 + tmp[2].Length + 0)..];
sender = tmp[0][1..];
if (sender[0] == '~') { sender = sender[1..]; }
return IsValidName(sender);
}
//Detect Essentials (Bukkit) /me messages with some custom prefix
//[Prefix] [Someone -> me] message
//[Prefix] [~Someone -> me] message
else if (text[0] == '[' && tmp[0][^1] == ']'
&& tmp[1][0] == '[' && tmp.Length > 4 && tmp[2] == "->"
&& (tmp[3].ToLower() == "me]" || tmp[3].ToLower() == "moi]"))
{
message = text[(tmp[0].Length + 1 + tmp[1].Length + 4 + tmp[3].Length + 1)..];
sender = tmp[1][1..];
if (sender[0] == '~') { sender = sender[1..]; }
return IsValidName(sender);
}
//Detect Essentials (Bukkit) /me messages with some custom rank
//[Someone [rank] -> me] message
//[~Someone [rank] -> me] message
else if (text[0] == '[' && tmp.Length > 3 && tmp[2] == "->"
&& (tmp[3].ToLower() == "me]" || tmp[3].ToLower() == "moi]"))
{
message = text[(tmp[0].Length + 1 + tmp[1].Length + 4 + tmp[2].Length + 1)..];
sender = tmp[0][1..];
if (sender[0] == '~') { sender = sender[1..]; }
return IsValidName(sender);
}
//Detect HeroChat PMsend
//From Someone: message
else if (text.StartsWith("From "))
{
sender = text[5..].Split(':')[0];
message = text[(text.IndexOf(':') + 2)..];
return IsValidName(sender);
}
else return false;
}
catch (IndexOutOfRangeException) { /* Not an expected chat format */ }
catch (ArgumentOutOfRangeException) { /* Same here */ }
}
return false;
}
/// <summary>
/// Returns true if the text passed is a public message written by a player on the chat
/// </summary>
/// <param name="text">text to test</param>
/// <param name="message">if it's message, this will contain the message</param>
/// <param name="sender">if it's message, this will contain the player name that sends the message</param>
/// <returns>Returns true if the text is a chat message</returns>
protected static bool IsChatMessage(string text, ref string message, ref string sender)
{
if (string.IsNullOrEmpty(text))
return false;
text = GetVerbatim(text);
//User-defined regex for public chat messages
if (Config.ChatFormat.UserDefined && !string.IsNullOrWhiteSpace(Config.ChatFormat.Public))
{
Match regexMatch = Regex.Match(text, Config.ChatFormat.Public);
if (regexMatch.Success && regexMatch.Groups.Count >= 3)
{
sender = regexMatch.Groups[1].Value;
message = regexMatch.Groups[2].Value;
return IsValidName(sender);
}
}
//Built-in detection routine for public messages
if (Config.ChatFormat.Builtins)
{
string[] tmp = text.Split(' ');
//Detect vanilla/factions Messages
//<Someone> message
//<*Faction Someone> message
//<*Faction Someone>: message
//<*Faction ~Nicknamed>: message
if (text[0] == '<')
{
try
{
text = text[1..];
string[] tmp2 = text.Split('>');
sender = tmp2[0];
message = text[(sender.Length + 2)..];
if (message.Length > 1 && message[0] == ' ')
{ message = message[1..]; }
tmp2 = sender.Split(' ');
sender = tmp2[^1];
if (sender[0] == '~') { sender = sender[1..]; }
return IsValidName(sender);
}
catch (IndexOutOfRangeException) { /* Not a vanilla/faction message */ }
catch (ArgumentOutOfRangeException) { /* Same here */ }
}
//Detect HeroChat Messages
//Public chat messages
//[Channel] [Rank] User: Message
else if (text[0] == '[' && text.Contains(':') && tmp.Length > 2)
{
try
{
int name_end = text.IndexOf(':');
int name_start = text[..name_end].LastIndexOf(']') + 2;
sender = text[name_start..name_end];
message = text[(name_end + 2)..];
return IsValidName(sender);
}
catch (IndexOutOfRangeException) { /* Not a herochat message */ }
catch (ArgumentOutOfRangeException) { /* Same here */ }
}
//Detect (Unknown Plugin) Messages
//**Faction<Rank> User : Message
else if (text[0] == '*'
&& text.Length > 1
&& text[1] != ' '
&& text.Contains('<') && text.Contains('>')
&& text.Contains(' ') && text.Contains(':')
&& text.IndexOf('*') < text.IndexOf('<')
&& text.IndexOf('<') < text.IndexOf('>')
&& text.IndexOf('>') < text.IndexOf(' ')
&& text.IndexOf(' ') < text.IndexOf(':'))
{
try
{
string prefix = tmp[0];
string user = tmp[1];
string semicolon = tmp[2];
if (prefix.All(c => char.IsLetterOrDigit(c) || new char[] { '*', '<', '>', '_' }.Contains(c))
&& semicolon == ":")
{
message = text[(prefix.Length + user.Length + 4)..];
return IsValidName(user);
}
}
catch (IndexOutOfRangeException) { /* Not a <unknown plugin> message */ }
catch (ArgumentOutOfRangeException) { /* Same here */ }
}
}
return false;
}
/// <summary>
/// Returns true if the text passed is a teleport request (Essentials)
/// </summary>
/// <param name="text">Text to parse</param>
/// <param name="sender">Will contain the sender's username, if it's a teleport request</param>
/// <returns>Returns true if the text is a teleport request</returns>
protected static bool IsTeleportRequest(string text, ref string sender)
{
if (string.IsNullOrEmpty(text))
return false;
text = GetVerbatim(text);
//User-defined regex for teleport requests
if (Config.ChatFormat.UserDefined && !string.IsNullOrWhiteSpace(Config.ChatFormat.TeleportRequest))
{
Match regexMatch = Regex.Match(text, Config.ChatFormat.TeleportRequest);
if (regexMatch.Success && regexMatch.Groups.Count >= 2)
{
sender = regexMatch.Groups[1].Value;
return IsValidName(sender);
}
}
//Built-in detection routine for teleport requests
if (Config.ChatFormat.Builtins)
{
string[] tmp = text.Split(' ');
//Detect Essentials teleport requests, prossibly with
//nicknamed names or other modifications such as HeroChat
if (text.EndsWith("has requested to teleport to you.")
|| text.EndsWith("has requested that you teleport to them."))
{
//<Rank> Username has requested...
//[Rank] Username has requested...
if ((tmp[0].StartsWith("<") && tmp[0].EndsWith(">")
|| tmp[0].StartsWith("[") && tmp[0].EndsWith("]"))
&& tmp.Length > 1)
sender = tmp[1];
else //Username has requested..
sender = tmp[0];
//~Username has requested...
if (sender.Length > 1 && sender[0] == '~')
sender = sender[1..];
//Final check on username validity
return IsValidName(sender);
}
}
return false;
}
/// <summary>
/// Write some text in the console. Nothing will be sent to the server.
/// </summary>
/// <param name="text">Log text to write</param>
protected void LogToConsole(object? text)
{
string botName = Translations.ResourceManager.GetString("botname." + GetType().Name) ?? GetType().Name;
if (_handler == null || master == null)
ConsoleIO.WriteLogLine(string.Format("[{0}] {1}", botName, text));
else
Handler.Log.Info(string.Format("[{0}] {1}", botName, text));
string logfile = Config.AppVar.ExpandVars(Config.Main.Advanced.ChatbotLogFile);
if (!string.IsNullOrEmpty(logfile))
{
if (!File.Exists(logfile))
{
try { Directory.CreateDirectory(Path.GetDirectoryName(logfile)!); }
catch { return; /* Invalid path or access denied */ }
try { File.WriteAllText(logfile, ""); }
catch { return; /* Invalid file name or access denied */ }
}
File.AppendAllLines(logfile, new string[] { GetTimestamp() + ' ' + text });
}
}
protected static void LogToConsole(string originBotName, object? text)
{
string botName = Translations.ResourceManager.GetString(originBotName) ?? originBotName;
ConsoleIO.WriteLogLine(string.Format("[{0}] {1}", botName, text));
string logfile = Config.AppVar.ExpandVars(Config.Main.Advanced.ChatbotLogFile);
if (!string.IsNullOrEmpty(logfile))
{
if (!File.Exists(logfile))
{
try { Directory.CreateDirectory(Path.GetDirectoryName(logfile)!); }
catch { return; /* Invalid path or access denied */ }
try { File.WriteAllText(logfile, ""); }
catch { return; /* Invalid file name or access denied */ }
}
File.AppendAllLines(logfile, new string[] { GetTimestamp() + ' ' + text });
}
}
/// <summary>
/// Write some text in the console, but only if DebugMessages is enabled in INI file. Nothing will be sent to the server.
/// </summary>
/// <param name="text">Debug log text to write</param>
protected void LogDebugToConsole(object text)
{
if (Config.Logging.DebugMessages)
LogToConsole(text);
}
/// <summary>
/// Write the translated text in the console by giving a translation key. Nothing will be sent to the server.
/// </summary>
/// <param name="key">Translation key</param>
/// <param name="args"></param>
protected void LogToConsoleTranslated(string key, params object[] args)
{
LogToConsole(string.Format(Translations.ResourceManager.GetString(key) ?? key, args));
}
/// <summary>
/// Write the translated text in the console by giving a translation key, but only if DebugMessages is enabled in INI file. Nothing will be sent to the server.
/// </summary>
/// <param name="key">Translation key</param>
/// <param name="args"></param>
protected void LogDebugToConsoleTranslated(string key, params object?[] args)
{
LogDebugToConsole(string.Format(Translations.ResourceManager.GetString(key) ?? key, args));
}
/// <summary>
/// Disconnect from the server and restart the program
/// It will unload and reload all the bots and then reconnect to the server
/// </summary>
/// <param name="ExtraAttempts">In case of failure, maximum extra attempts before aborting</param>
/// <param name="delaySeconds">Optional delay, in seconds, before restarting</param>
protected void ReconnectToTheServer(int ExtraAttempts = 3, int delaySeconds = 0, bool keepAccountAndServerSettings = false)
{
if (Config.Logging.DebugMessages)
{
string botName = Translations.ResourceManager.GetString("botname." + GetType().Name) ?? GetType().Name;
ConsoleIO.WriteLogLine(string.Format(Translations.chatbot_reconnect, botName));
}
McClient.ReconnectionAttemptsLeft = ExtraAttempts;
Program.Restart(delaySeconds, keepAccountAndServerSettings);
}
/// <summary>
/// Disconnect from the server and exit the program
/// </summary>
protected void DisconnectAndExit()
{
Program.Exit();
}
/// <summary>
/// Unload the chatbot, and release associated memory.
/// </summary>
protected void UnloadBot()
{
Handler.BotUnLoad(this);
}
/// <summary>
/// Send a private message to a player
/// </summary>
/// <param name="player">Player name</param>
/// <param name="message">Message</param>
protected void SendPrivateMessage(string player, string message)
{
SendText(string.Format("/{0} {1} {2}", Config.Main.Advanced.PrivateMsgsCmdName, player, message));
}
/// <summary>
/// Run a script from a file using a Scripting bot
/// </summary>
/// <param name="filename">File name</param>
/// <param name="playername">Player name to send error messages, if applicable</param>
/// <param name="localVars">Local variables for use in the Script</param>
protected void RunScript(string filename, string? playername = null, Dictionary<string, object>? localVars = null)
{
Handler.BotLoad(new ChatBots.Script(filename, playername, localVars));
}
/// <summary>
/// Load an additional ChatBot
/// </summary>
/// <param name="chatBot">ChatBot to load</param>
protected void BotLoad(ChatBot chatBot)
{
Handler.BotLoad(chatBot);
}
/// <summary>
/// Set an App Variable
/// </summary>
/// <param name="name">App variable name</param>