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. /// /// /// The virtual class containing anything you need for creating chat bots. /// 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 GetLoadedChatBots() { return Handler.GetLoadedChatBots(); } protected void UnLoadBot(ChatBot bot) { Handler.BotUnLoad(bot); } private McClient? _handler = null; private ChatBot? master = null; private readonly List registeredPluginChannels = new(); private readonly object delayTasksLock = new(); private readonly List delayedTasks = new(); protected McClient Handler { get { if (master != null) return master.Handler; if (_handler != null) return _handler; throw new InvalidOperationException(Translations.exception_chatbot_init); } } /// /// Will be called every ~100ms. /// /// /// method can be overridden by child class so need an extra update method /// public void UpdateInternal() { lock (delayTasksLock) { if (delayedTasks.Count > 0) { List 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 */ /* ================================================== */ /// /// 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. /// public virtual void Initialize() { } /// /// This method is called when the bot is being unloaded, you can use it to free up resources like DB connections /// public virtual void OnUnload() { } /// /// 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. /// public virtual void AfterGameJoined() { } /// /// Will be called every ~100ms (10fps) if loaded in MinecraftCom /// public virtual void Update() { } /// /// Will be called every player break block in gamemode 0 /// /// Player /// Block location /// Destroy stage, maximum 255 public virtual void OnBlockBreakAnimation(Entity entity, Location location, byte stage) { } /// /// Will be called every animations of the hit and place block /// /// Player /// 0 = LMB, 1 = RMB (RMB Corrent not work) public virtual void OnEntityAnimation(Entity entity, byte animation) { } /// /// Any text sent by the server will be sent here by MinecraftCom /// /// Text from the server public virtual void GetText(string text) { } /// /// Any text sent by the server will be sent here by MinecraftCom (extended variant) /// /// /// You can use Json.ParseJson() to process the JSON string. /// /// Text from the server /// Raw JSON from the server. This parameter will be NULL on MC 1.5 or lower! public virtual void GetText(string text, string? json) { } /// /// Is called when the client has been disconnected fom the server /// /// Disconnect Reason /// Kick message, if any /// Return TRUE if the client is about to restart public virtual bool OnDisconnect(DisconnectReason reason, string message) { return false; } /// /// 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 /// /// The name of the channel /// The payload for the message public virtual void OnPluginMessage(string channel, byte[] data) { } /// /// Called when properties for the Player entity are received from the server /// /// Dictionary of player properties public virtual void OnPlayerProperty(Dictionary prop) { } /// /// Called when server TPS are recalculated by MCC based on world time updates /// /// New estimated server TPS (between 0 and 20) public virtual void OnServerTpsUpdate(double tps) { } /// /// Called when a time changed /// /// World age /// Time public virtual void OnTimeUpdate(long WorldAge, long TimeOfDay) { } /// /// Called when an entity moved nearby /// /// Entity with updated location public virtual void OnEntityMove(Entity entity) { } /// /// Called after an internal MCC command has been performed /// /// MCC Command Name /// MCC Command Parameters /// MCC command result public virtual void OnInternalCommand(string commandName, string commandParams, CmdResult Result) { } /// /// Called when an entity spawned nearby /// /// New Entity public virtual void OnEntitySpawn(Entity entity) { } /// /// Called when an entity despawns/dies nearby /// /// Entity wich has just disappeared public virtual void OnEntityDespawn(Entity entity) { } /// /// Called when the player held item has changed /// /// New slot ID public virtual void OnHeldItemChange(byte slot) { } /// /// Called when the player health has been updated /// /// New player health /// New food level public virtual void OnHealthUpdate(float health, int food) { } /// /// Called when an explosion occurs on the server /// /// Explosion location /// Explosion strength /// Amount of blocks blown up public virtual void OnExplosion(Location explode, float strength, int recordcount) { } /// /// Called when experience updates /// /// Between 0 and 1 /// Level /// Total Experience public virtual void OnSetExperience(float Experiencebar, int Level, int TotalExperience) { } /// /// Called when the Game Mode has been updated for a player /// /// Player Name /// Player UUID /// New Game Mode (0: Survival, 1: Creative, 2: Adventure, 3: Spectator). public virtual void OnGamemodeUpdate(string playername, Guid uuid, int gamemode) { } /// /// Called when the Latency has been updated for a player /// /// Player Name /// Player UUID /// Latency. public virtual void OnLatencyUpdate(string playername, Guid uuid, int latency) { } /// /// Called when the Latency has been updated for a player /// /// Entity /// Player Name /// Player UUID /// Latency. public virtual void OnLatencyUpdate(Entity entity, string playername, Guid uuid, int latency) { } /// /// 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.fandom.com/wiki/Map_item_format /// /// Map ID of the map being modified /// 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) /// Specifies whether player and item frame icons are shown /// True if the map has been locked in a cartography table /// A list of MapIcon objects of map icons, send only if trackingPosition is true /// 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) /// Map height /// x offset of the westernmost column /// z offset of the northernmost row /// a byte array of colors on the map public virtual void OnMapData(int mapid, byte scale, bool trackingPosition, bool locked, List icons, byte columnsUpdated, byte rowsUpdated, byte mapCoulmnX, byte mapRowZ, byte[]? colors) { } /// /// Called when tradeList is received from server /// /// Window ID /// List of trades. /// Contains Level, Experience, IsRegularVillager and CanRestock . public virtual void OnTradeList(int windowID, List trades, VillagerInfo villagerInfo) { } /// /// Called when received a title from the server /// 0 = set title, 1 = set subtitle, 3 = set action bar, 4 = set times and display, 4 = hide, 5 = reset /// title text /// suntitle text /// action bar text /// Fade In /// Stay /// Fade Out /// json text public virtual void OnTitle(int action, string titletext, string subtitletext, string actionbartext, int fadein, int stay, int fadeout, string json) { } /// /// Called when an entity equipped /// /// Entity /// Equipment slot. 0: main hand, 1: off hand, 2–5: armor slot (2: boots, 3: leggings, 4: chestplate, 5: helmet) /// Item) public virtual void OnEntityEquipment(Entity entity, int slot, Item? item) { } /// /// Called when an entity has effect applied /// /// entity /// effect id /// effect amplifier /// effect duration /// effect flags public virtual void OnEntityEffect(Entity entity, Effects effect, int amplifier, int duration, byte flags) { } /// /// Called when a scoreboard objective updated /// /// objective name /// 0 to create the scoreboard. 1 to remove the scoreboard. 2 to update the display text. /// Only if mode is 0 or 2. The text to be displayed for the score /// Only if mode is 0 or 2. 0 = "integer", 1 = "hearts". public virtual void OnScoreboardObjective(string objectivename, byte mode, string objectivevalue, int type, string json) { } /// /// Called when a scoreboard updated /// /// The entity whose score this is. For players, this is their username; for other entities, it is their UUID. /// 0 to create/update an item. 1 to remove an item. /// The name of the objective the score belongs to /// The score to be displayed next to the entry. Only sent when Action does not equal 1. public virtual void OnUpdateScore(string entityname, int action, string objectivename, int value) { } /// /// Called when an inventory/container was updated by server /// /// public virtual void OnInventoryUpdate(int inventoryId) { } /// /// Called when a container was opened /// /// public virtual void OnInventoryOpen(int inventoryId) { } /// /// Called when a container was closed /// /// public virtual void OnInventoryClose(int inventoryId) { } /// /// 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 /// /// Inventory ID /// Property ID /// Property Value public virtual void OnInventoryProperties(byte inventoryID, short propertyId, short propertyValue) { } /// /// 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 /// /// Enchantment in the top most slot /// Enchantment in the middle slot /// Enchantment in the bottom slot /// Enchantment level for the enchantment in the top most slot /// Enchantment level for the enchantment in the middle slot /// Enchantment level for the enchantment in the bottom slot /// Levels required by player for the enchantment in the top most slot /// Levels required by player for the enchantment in the middle slot /// Levels required by player for the enchantment in the bottom slot public virtual void OnEnchantments( Enchantment topEnchantment, Enchantment middleEnchantment, Enchantment bottomEnchantment, short topEnchantmentLevel, short middleEnchantmentLevel, short bottomEnchantmentLevel, short topEnchantmentLevelRequirement, short middleEnchantmentLevelRequirement, short bottomEnchantmentLevelRequirement) { } /// /// 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 /// /// Enchantment data/info public virtual void OnEnchantments(EnchantmentData enchantment) { } /// /// Called when a player joined the game /// /// UUID of the player /// Name of the player public virtual void OnPlayerJoin(Guid uuid, string name) { } /// /// Called when a player left the game /// /// UUID of the player /// Name of the player public virtual void OnPlayerLeave(Guid uuid, string? name) { } /// /// This method is called when a player has been killed by another entity /// /// Killer's entity /// message sent in chat when player is killed public virtual void OnKilled(Entity killerEntity, string chatMessage) { } /// /// Called when the player dies /// For getting the info about the player/entity who killed the player use OnPlayerKilled /// public virtual void OnDeath() { } /// /// Called when the player respawns /// public virtual void OnRespawn() { } /// /// Called when the health of an entity changed /// /// Entity /// The health of the entity public virtual void OnEntityHealth(Entity entity, float health) { } /// /// Called when the metadata of an entity changed /// /// Entity /// The metadata of the entity public virtual void OnEntityMetadata(Entity entity, Dictionary metadata) { } /// /// Called when the status of client player have been changed /// /// public virtual void OnPlayerStatus(byte statusId) { } /// /// Called when a network packet received or sent /// /// /// You need to enable this event by calling with True before you can use this event /// /// Packet ID /// A copy of Packet Data /// The packet is login phase or playing phase /// The packet is received from server or sent by client public virtual void OnNetworkPacket(int packetID, List packetData, bool isLogin, bool isInbound) { } /// /// Called when the rain level have been changed /// /// public virtual void OnRainLevelChange(float level) { } /// /// Called when the thunder level have been changed /// /// public virtual void OnThunderLevelChange(float level) { } /// /// Called when a block is changed. /// /// The location of the block. /// The block 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. */ /* =================================================================== */ /// /// Send text to the server. Can be anything such as chat messages or commands /// /// Text to send to the server /// Bypass send queue (Deprecated, still there for compatibility purposes but ignored) /// TRUE if successfully sent (Deprectated, always returns TRUE for compatibility purposes with existing scripts) protected bool SendText(string text, bool sendImmediately = false) { LogToConsole("Sending '" + text + "'"); Handler.SendText(text); return true; } /// /// Perform an internal MCC command (not a server command, use SendText() instead for that!) /// /// The command to process /// Local variables passed along with the command /// TRUE if the command was indeed an internal MCC command protected bool PerformInternalCommand(string command, Dictionary? localVars = null) { CmdResult temp = new(); return Handler.PerformInternalCommand(command, ref temp, localVars); } /// /// Perform an internal MCC command (not a server command, use SendText() instead for that!) /// /// The command to process /// May contain a confirmation or error message after processing the command, or "" otherwise. /// Local variables passed along with the command /// TRUE if the command was indeed an internal MCC command protected bool PerformInternalCommand(string command, ref CmdResult result, Dictionary? localVars = null) { return Handler.PerformInternalCommand(command, ref result, localVars); } /// /// Remove color codes ("§c") from a text message received from the server /// 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); } /// /// Verify that a string contains only a-z A-Z 0-9 and _ characters. /// 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; } /// /// Returns true if the text passed is a private message sent to the bot /// /// text to test /// if it's a private message, this will contain the message /// if it's a private message, this will contain the player name that sends the message /// Returns true if the text is a private message 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; } /// /// Returns true if the text passed is a public message written by a player on the chat /// /// text to test /// if it's message, this will contain the message /// if it's message, this will contain the player name that sends the message /// Returns true if the text is a chat message 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 // 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 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 message */ } catch (ArgumentOutOfRangeException) { /* Same here */ } } } return false; } /// /// Returns true if the text passed is a teleport request (Essentials) /// /// Text to parse /// Will contain the sender's username, if it's a teleport request /// Returns true if the text is a teleport request 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.")) { // 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; } /// /// Write some text in the console. Nothing will be sent to the server. /// /// Log text to write 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 }); } } /// /// Write some text in the console, but only if DebugMessages is enabled in INI file. Nothing will be sent to the server. /// /// Debug log text to write protected void LogDebugToConsole(object text) { if (Config.Logging.DebugMessages) LogToConsole(text); } /// /// Write the translated text in the console by giving a translation key. Nothing will be sent to the server. /// /// Translation key /// protected void LogToConsoleTranslated(string key, params object[] args) { LogToConsole(string.Format(Translations.ResourceManager.GetString(key) ?? key, args)); } /// /// 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. /// /// Translation key /// protected void LogDebugToConsoleTranslated(string key, params object?[] args) { LogDebugToConsole(string.Format(Translations.ResourceManager.GetString(key) ?? key, args)); } /// /// Disconnect from the server and restart the program /// It will unload and reload all the bots and then reconnect to the server /// /// In case of failure, maximum extra attempts before aborting /// Optional delay, in seconds, before restarting 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); } /// /// Disconnect from the server and exit the program /// protected void DisconnectAndExit() { Program.Exit(); } /// /// Unload the chatbot, and release associated memory. /// protected void UnloadBot() { Handler.BotUnLoad(this); } /// /// Send a private message to a player /// /// Player name /// Message protected void SendPrivateMessage(string player, string message) { SendText(string.Format("/{0} {1} {2}", Config.Main.Advanced.PrivateMsgsCmdName, player, message)); } /// /// Run a script from a file using a Scripting bot /// /// File name /// Player name to send error messages, if applicable /// Local variables for use in the Script protected void RunScript(string filename, string? playername = null, Dictionary? localVars = null) { Handler.BotLoad(new ChatBots.Script(filename, playername, localVars)); } /// /// Load an additional ChatBot /// /// ChatBot to load protected void BotLoad(ChatBot chatBot) { Handler.BotLoad(chatBot); } /// /// Set an App Variable /// /// App variable name /// App variable value /// void protected void SetAppVar(string name, object value) { Config.AppVar.SetVar(name, value); } /// /// Get a value from an App Variable /// /// App variable name /// App Variable value protected object? GetAppVar(string name) { return Config.AppVar.GetVar(name); } /// /// Replaces variables in text with their values from the App Var registry /// /// Your text with variables /// text with variables replaced with their values protected string ExpandAppVars(string text) { return Config.AppVar.ExpandVars(text); } /// /// Check whether Terrain and Movements is enabled. /// /// Enable status. public bool GetTerrainEnabled() { return Handler.GetTerrainEnabled(); } /// /// Enable or disable Terrain and Movements. /// Please note that Enabling will be deferred until next relog, respawn or world change. /// /// Enabled /// TRUE if the setting was applied immediately, FALSE if delayed. public bool SetTerrainEnabled(bool enabled) { return Handler.SetTerrainEnabled(enabled); } /// /// Get entity handling status /// /// /// Entity Handling cannot be enabled in runtime (or after joining server) public bool GetEntityHandlingEnabled() { return Handler.GetEntityHandlingEnabled(); } /// /// start Sneaking /// protected bool Sneak(bool on) { return SendEntityAction(on ? Protocol.EntityActionType.StartSneaking : Protocol.EntityActionType.StopSneaking); } /// /// Send Entity Action /// protected bool SendEntityAction(Protocol.EntityActionType entityAction) { return Handler.SendEntityAction(entityAction); } /// /// Attempt to dig a block at the specified location /// /// Location of block to dig /// Also perform the "arm swing" animation /// Also look at the block before digging protected bool DigBlock(Location location, bool swingArms = true, bool lookAtBlock = true) { return Handler.DigBlock(location, swingArms, lookAtBlock); } /// /// SetSlot /// protected void SetSlot(int slotNum) { Handler.ChangeSlot((short)slotNum); } /// /// Get the current Minecraft World /// /// Minecraft world or null if associated setting is disabled protected World GetWorld() { return Handler.GetWorld(); } /// /// Get all Entities /// /// All Entities protected Dictionary GetEntities() { return Handler.GetEntities(); } /// /// Get all players Latency /// /// All players latency protected Dictionary GetPlayersLatency() { return Handler.GetPlayersLatency(); } /// /// Get the current location of the player (Feet location) /// /// Minecraft world or null if associated setting is disabled protected Location GetCurrentLocation() { return Handler.GetCurrentLocation(); } /// /// Move to the specified location /// /// Location to reach /// Allow possible but unsafe locations thay may hurt the player: lava, cactus... /// Allow non-vanilla direct teleport instead of computing path, but may cause invalid moves and/or trigger anti-cheat plugins /// If no valid path can be found, also allow locations within specified distance of destination /// Do not get closer of destination than specified distance /// How long to wait before stopping computation (default: 5 seconds) /// When location is unreachable, computation will reach timeout, then optionally fallback to a close location within maxOffset /// True if a path has been found protected bool MoveToLocation(Location location, bool allowUnsafe = false, bool allowDirectTeleport = false, int maxOffset = 0, int minOffset = 0, TimeSpan? timeout = null) { return Handler.MoveTo(location, allowUnsafe, allowDirectTeleport, maxOffset, minOffset, timeout); } /// /// Check if the client is currently processing a Movement. /// /// true if a movement is currently handled protected bool ClientIsMoving() { return Handler.ClientIsMoving(); } /// /// Look at the specified location /// /// Location to look at protected void LookAtLocation(Location location) { Handler.UpdateLocation(Handler.GetCurrentLocation(), location); } /// /// Look at the specified location /// /// Yaw to look at /// Pitch to look at protected void LookAtLocation(float yaw, float pitch) { Handler.UpdateLocation(Handler.GetCurrentLocation(), yaw, pitch); } /// /// Find the block on the line of sight. /// /// Maximum distance from sight /// Whether to detect fluid /// Position of the block protected Tuple GetLookingBlock(double maxDistance = 4.5, bool includeFluids = false) { return RaycastHelper.RaycastBlock(Handler, maxDistance, includeFluids); } /// /// Get a Y-M-D h:m:s timestamp representing the current system date and time /// protected static string GetTimestamp() { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } /// /// Get a h:m:s timestamp representing the current system time /// protected static string GetShortTimestamp() { return DateTime.Now.ToString("HH:mm:ss"); } /// /// Load entries from a file as a string array, removing duplicates and empty lines /// /// File to load /// The string array or an empty array if failed to load the file protected string[] LoadDistinctEntriesFromFile(string file) { if (File.Exists(file)) { //Read all lines from file, remove lines with no text, convert to lowercase, //remove duplicate entries, convert to a string array, and return the result. return File.ReadAllLines(file, Encoding.UTF8) .Where(line => !string.IsNullOrWhiteSpace(line)) .Select(line => line.ToLower()) .Distinct().ToArray(); } else { LogToConsole("File not found: " + Path.GetFullPath(file)); return Array.Empty(); } } /// /// Return the Server Port where the client is connected to /// /// Server Port where the client is connected to protected int GetServerPort() { return Handler.GetServerPort(); } /// /// Return the Server Host where the client is connected to /// /// Server Host where the client is connected to protected string GetServerHost() { return Handler.GetServerHost(); } /// /// Return the Username of the current account /// /// Username of the current account protected string GetUsername() { return Handler.GetUsername(); } /// /// Return the Gamemode of the current account /// /// Username of the current account protected int GetGamemode() { return Handler.GetGamemode(); } /// /// Return the head yaw of the client player /// /// Yaw of the client player protected float GetYaw() { return Handler.GetYaw(); } /// /// Return the head pitch of the client player /// /// Pitch of the client player protected float GetPitch() { return Handler.GetPitch(); } /// /// Return the UserUUID of the current account /// /// UserUUID of the current account protected string GetUserUUID() { return Handler.GetUserUuidStr(); } /// /// Return the EntityID of the current player /// /// EntityID of the current player protected int GetPlayerEntityID() { return Handler.GetPlayerEntityID(); } /// /// Return the list of currently online players /// /// List of online players protected string[] GetOnlinePlayers() { return Handler.GetOnlinePlayers(); } /// /// Get a dictionary of online player names and their corresponding UUID /// /// /// dictionary of online player whereby /// UUID represents the key /// playername represents the value protected Dictionary GetOnlinePlayersWithUUID() { return Handler.GetOnlinePlayersWithUUID(); } /// /// Registers the given plugin channel for use by this chatbot. /// /// The name of the channel to register protected void RegisterPluginChannel(string channel) { registeredPluginChannels.Add(channel); Handler.RegisterPluginChannel(channel, this); } /// /// Unregisters the given plugin channel, meaning this chatbot can no longer use it. /// /// The name of the channel to unregister protected void UnregisterPluginChannel(string channel) { registeredPluginChannels.RemoveAll(chan => chan == channel); Handler.UnregisterPluginChannel(channel, this); } /// /// Sends the given plugin channel message to the server, if the channel has been registered. /// See http://wiki.vg/Plugin_channel for more information about plugin channels. /// /// The channel to send the message on. /// The data to send. /// Should the message be sent even if it hasn't been registered by the server or this bot? (Some Minecraft channels aren't registered) /// Whether the message was successfully sent. False if there was a network error or if the channel wasn't registered. protected bool SendPluginChannelMessage(string channel, byte[] data, bool sendEvenIfNotRegistered = false) { if (!sendEvenIfNotRegistered) { if (!registeredPluginChannels.Contains(channel)) { return false; } } return Handler.SendPluginChannelMessage(channel, data, sendEvenIfNotRegistered); } /// /// Get server current TPS (tick per second) /// /// tps protected double GetServerTPS() { return Handler.GetServerTPS(); } /// /// Interact with an entity /// /// /// 0: interact, 1: attack, 2: interact at /// Hand.MainHand or Hand.OffHand /// TRUE in case of success [Obsolete("Prefer using InteractType enum instead of int for interaction type")] protected bool InteractEntity(int EntityID, int type, Hand hand = Hand.MainHand) { return Handler.InteractEntity(EntityID, (InteractType)type, hand); } /// /// Interact with an entity /// /// /// Interaction type (InteractType.Interact, Attack or AttackAt) /// Hand.MainHand or Hand.OffHand /// TRUE in case of success protected bool InteractEntity(int EntityID, InteractType type, Hand hand = Hand.MainHand) { return Handler.InteractEntity(EntityID, type, hand); } /// /// Give Creative Mode items into regular/survival Player Inventory /// /// (obviously) requires to be in creative mode /// /// Destination inventory slot /// Item type /// Item count /// TRUE if item given successfully protected bool CreativeGive(int slot, ItemType itemType, int count, Dictionary? nbt = null) { return Handler.DoCreativeGive(slot, itemType, count, nbt); } /// /// Use Creative Mode to delete items from the regular/survival Player Inventory /// /// (obviously) requires to be in creative mode /// /// Inventory slot to clear /// TRUE if item cleared successfully protected bool CreativeDelete(int slot) { return CreativeGive(slot, ItemType.Null, 0, null); } /// /// Plays animation (Player arm swing) /// /// Hand.MainHand or Hand.OffHand /// TRUE if animation successfully done public bool SendAnimation(Hand hand = Hand.MainHand) { return Handler.DoAnimation((int)hand); } /// /// Use item currently in the player's hand (active inventory bar slot) /// /// TRUE if successful protected bool UseItemInHand() { return Handler.UseItemOnHand(); } /// /// Use item currently in the player's hand (active inventory bar slot) /// /// TRUE if successful protected bool UseItemInLeftHand() { return Handler.UseItemOnLeftHand(); } /// /// Check inventory handling enable status /// /// TRUE if inventory handling is enabled public bool GetInventoryEnabled() { return Handler.GetInventoryEnabled(); } /// /// Place the block at hand in the Minecraft world /// /// Location to place block to /// Block face (e.g. Direction.Down when clicking on the block below to place this block) /// Hand.MainHand or Hand.OffHand /// TRUE if successfully placed public bool SendPlaceBlock(Location location, Direction blockFace, Hand hand = Hand.MainHand) { return Handler.PlaceBlock(location, blockFace, hand); } /// /// Get the player's inventory. Do not write to it, will not have any effect server-side. /// /// Player inventory protected Container GetPlayerInventory() { Container container = Handler.GetPlayerInventory(); return new Container(container.ID, container.Type, container.Title, container.Items); } /// /// Get all inventories, player and container(s). Do not write to them. Will not have any effect server-side. /// /// All inventories public Dictionary GetInventories() { return Handler.GetInventories(); } /// /// Perform inventory action /// /// Inventory ID /// Slot ID /// Action Type /// TRUE in case of success protected bool WindowAction(int inventoryId, int slot, WindowActionType actionType) { return Handler.DoWindowAction(inventoryId, slot, actionType); } /// /// Get inventory action helper /// /// Inventory Container /// ItemMovingHelper instance protected ItemMovingHelper GetItemMovingHelper(Container container) { return new ItemMovingHelper(container, Handler); } /// /// Change player selected hotbar slot /// /// 0-8 /// True if success protected bool ChangeSlot(short slot) { return Handler.ChangeSlot(slot); } /// /// Get current player selected hotbar slot /// /// 0-8 protected byte GetCurrentSlot() { return Handler.GetCurrentSlot(); } /// /// Clean all inventory /// /// TRUE if the uccessfully clear protected bool ClearInventories() { return Handler.ClearInventories(); } /// /// Update sign text /// /// sign location /// text one /// text two /// text three /// text1 four protected bool UpdateSign(Location location, string line1, string line2, string line3, string line4) { return Handler.UpdateSign(location, line1, line2, line3, line4); } /// /// Selects villager trade /// /// Trade slot to select, starts at 0. protected bool SelectTrade(int selectedSlot) { return Handler.SelectTrade(selectedSlot); } /// /// Teleport to player in spectator mode /// /// player to teleport to protected bool SpectatorTeleport(Entity entity) { return Handler.Spectate(entity); } /// /// Teleport to player/entity in spectator mode /// /// uuid of entity to teleport to protected bool SpectatorTeleport(Guid UUID) { return Handler.SpectateByUUID(UUID); } /// /// Update command block /// /// command block location /// command /// command block mode /// command block flags protected bool UpdateCommandBlock(Location location, string command, CommandBlockMode mode, CommandBlockFlags flags) { return Handler.UpdateCommandBlock(location, command, mode, flags); } /// /// Close a opened inventory /// /// /// True if success protected bool CloseInventory(int inventoryID) { return Handler.CloseInventory(inventoryID); } /// /// Get max length for chat messages /// /// Max length, in characters protected int GetMaxChatMessageLength() { return Handler.GetMaxChatMessageLength(); } /// /// Respawn player /// protected bool Respawn() { if (Handler.GetHealth() <= 0) return Handler.SendRespawnPacket(); else return false; } /// /// Enable or disable network packet event calling. If you want to capture every packet including login phase, please enable this in /// /// /// Enable this may increase memory usage. /// /// protected void SetNetworkPacketEventEnabled(bool enabled) { Handler.SetNetworkPacketCaptureEnabled(enabled); } /// /// Get the minecraft protcol number currently in use /// /// Protcol number protected int GetProtocolVersion() { return Handler.GetProtocolVersion(); } /// /// Invoke a task on the main thread, wait for completion and retrieve return value. /// /// Task to run with any type or return value /// Any result returned from task, result type is inferred from the task /// bool result = InvokeOnMainThread(methodThatReturnsAbool); /// bool result = InvokeOnMainThread(() => methodThatReturnsAbool(argument)); /// int result = InvokeOnMainThread(() => { yourCode(); return 42; }); /// Type of the return value protected T InvokeOnMainThread(Func task) { return Handler.InvokeOnMainThread(task); } /// /// Invoke a task on the main thread and wait for completion /// /// Task to run without return value /// InvokeOnMainThread(methodThatReturnsNothing); /// InvokeOnMainThread(() => methodThatReturnsNothing(argument)); /// InvokeOnMainThread(() => { yourCode(); }); protected void InvokeOnMainThread(Action task) { Handler.InvokeOnMainThread(task); } /// /// Schedule a task to run on the main thread, and do not wait for completion /// /// Task to run /// Run the task after X ticks (1 tick delay = ~100ms). 0 for no delay /// /// InvokeOnMainThread(methodThatReturnsNothing, 10); /// InvokeOnMainThread(() => methodThatReturnsNothing(argument), 10); /// InvokeOnMainThread(() => { yourCode(); }, 10); /// protected void ScheduleOnMainThread(Action task, int delayTicks = 0) { lock (delayTasksLock) { delayedTasks.Add(new TaskWithDelay(task, delayTicks)); } } /// /// Schedule a task to run on the main thread, and do not wait for completion /// /// Task to run /// Run the task after the specified delay protected void ScheduleOnMainThread(Action task, TimeSpan delay) { lock (delayTasksLock) { delayedTasks.Add(new TaskWithDelay(task, delay)); } } /// /// Command runner definition. /// Returned string will be the output of the command /// /// Full command /// Arguments in the command /// Command result to display to the user public delegate string CommandRunner(string command, string[] args); /// /// Command class with constructor for creating command for ChatBots. /// public class ChatBotCommand : Command { public CommandRunner Runner; private readonly string _cmdName; private readonly string _cmdDesc; private readonly string _cmdUsage; public override string CmdName { get { return _cmdName; } } public override string CmdUsage { get { return _cmdUsage; } } public override string CmdDesc { get { return _cmdDesc; } } public override void RegisterCommand(CommandDispatcher dispatcher) { } /// /// ChatBotCommand Constructor /// /// Name of the command /// Description of the command. Support tranlation. /// Usage of the command /// Method for handling the command public ChatBotCommand(string cmdName, string cmdDesc, string cmdUsage, CommandRunner callback) { _cmdName = cmdName; _cmdDesc = cmdDesc; _cmdUsage = cmdUsage; Runner = callback; } } } }