2020-05-26 00:16:53 +05:00
using System ;
2014-05-31 01:59:03 +02:00
using System.Collections.Generic ;
2022-10-02 18:31:08 +08:00
using System.IO ;
2014-05-31 01:59:03 +02:00
using System.Linq ;
using System.Text ;
2015-10-22 22:17:15 +02:00
using System.Text.RegularExpressions ;
2020-03-26 15:01:42 +08:00
using MinecraftClient.Inventory ;
2020-05-29 23:18:34 +05:00
using MinecraftClient.Mapping ;
2014-05-31 01:59:03 +02:00
namespace MinecraftClient
{
///
/// Welcome to the Bot API file !
/// The virtual class "ChatBot" contains anything you need for creating chat bots
2016-09-11 20:11:01 +02:00
/// Inherit from this class while adding your bot class to the "ChatBots" folder.
2014-06-18 13:32:17 +02:00
/// Override the methods you want for handling events: Initialize, Update, GetText.
2014-05-31 01:59:03 +02:00
///
2020-10-24 17:41:35 +02:00
/// For testing your bot you can add it in McClient.cs (see comment at line ~199).
2016-09-11 20:11:01 +02:00
/// 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.
2014-05-31 01:59:03 +02:00
///
/// <summary>
/// The virtual class containing anything you need for creating chat bots.
/// </summary>
public abstract class ChatBot
{
2019-12-08 22:24:20 +01:00
public enum DisconnectReason { InGameKick , LoginRejected , ConnectionLost , UserLogout } ;
2014-05-31 01:59:03 +02:00
2015-06-21 18:45:43 +02:00
//Handler will be automatically set on bot loading, don't worry about this
2022-10-02 18:31:08 +08:00
public void SetHandler ( McClient handler ) { _handler = handler ; }
2015-06-21 18:45:43 +02:00
protected void SetMaster ( ChatBot master ) { this . master = master ; }
protected void LoadBot ( ChatBot bot ) { Handler . BotUnLoad ( bot ) ; Handler . BotLoad ( bot ) ; }
2020-08-01 17:24:17 +05:00
protected List < ChatBot > GetLoadedChatBots ( ) { return Handler . GetLoadedChatBots ( ) ; }
protected void UnLoadBot ( ChatBot bot ) { Handler . BotUnLoad ( bot ) ; }
2022-10-02 18:31:08 +08:00
private McClient ? _handler = null ;
private ChatBot ? master = null ;
private readonly List < string > registeredPluginChannels = new ( ) ;
private readonly List < string > registeredCommands = new ( ) ;
private readonly object delayTasksLock = new ( ) ;
private readonly List < TaskWithDelay > delayedTasks = new ( ) ;
2020-06-20 15:01:16 +02:00
private McClient Handler
2017-03-13 22:11:04 +01:00
{
get
{
if ( master ! = null )
return master . Handler ;
if ( _handler ! = null )
return _handler ;
2020-10-17 19:41:31 +08:00
throw new InvalidOperationException ( Translations . Get ( "exception.chatbot.init" ) ) ;
2017-03-13 22:11:04 +01:00
}
}
2014-05-31 01:59:03 +02:00
2021-05-08 21:03:23 +08:00
/// <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>
2021-05-08 21:10:26 +08:00
public void UpdateInternal ( )
2021-05-08 21:03:23 +08:00
{
lock ( delayTasksLock )
{
2021-05-15 17:36:16 +02:00
if ( delayedTasks . Count > 0 )
2021-05-08 21:03:23 +08:00
{
2022-10-02 18:31:08 +08:00
List < int > tasksToRemove = new ( ) ;
2021-05-15 17:36:16 +02:00
for ( int i = 0 ; i < delayedTasks . Count ; i + + )
2021-05-08 21:03:23 +08:00
{
2021-05-15 17:36:16 +02:00
if ( delayedTasks [ i ] . Tick ( ) )
2021-05-08 21:03:23 +08:00
{
2021-05-15 17:36:16 +02:00
delayedTasks [ i ] . Task ( ) ;
2021-05-08 21:03:23 +08:00
tasksToRemove . Add ( i ) ;
}
}
if ( tasksToRemove . Count > 0 )
{
tasksToRemove . Sort ( ( a , b ) = > b . CompareTo ( a ) ) ; // descending sort
foreach ( int index in tasksToRemove )
{
2021-05-15 17:36:16 +02:00
delayedTasks . RemoveAt ( index ) ;
2021-05-08 21:03:23 +08:00
}
}
}
}
}
2014-05-31 01:59:03 +02:00
/* ================================================== */
/* Main methods to override for creating your bot */
/* ================================================== */
/// <summary>
/// Anything you want to initialize your bot, will be called on load by MinecraftCom
2017-03-13 22:11:04 +01:00
/// This method is called only once, whereas AfterGameJoined() is called once per server join.
2016-02-07 14:47:03 -08:00
///
2017-03-13 22:11:04 +01:00
/// 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.
2014-05-31 01:59:03 +02:00
/// </summary>
public virtual void Initialize ( ) { }
2022-09-25 16:00:43 +02:00
/// <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 ( ) { }
2016-02-07 14:47:03 -08:00
/// <summary>
/// Called after the server has been joined successfully and chat messages are able to be sent.
2017-03-13 22:11:04 +01:00
/// This method is called again after reconnecting to the server, whereas Initialize() is called only once.
2016-02-07 14:47:03 -08:00
///
/// 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 ( ) { }
2014-05-31 01:59:03 +02:00
/// <summary>
/// Will be called every ~100ms (10fps) if loaded in MinecraftCom
/// </summary>
public virtual void Update ( ) { }
2021-07-04 11:26:41 +05:00
/// <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 ) { }
2014-05-31 01:59:03 +02:00
/// <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 ) { }
2017-05-31 20:54:16 +02:00
/// <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>
2022-08-15 23:55:44 +08:00
public virtual void GetText ( string text , string? json ) { }
2022-09-18 00:18:27 +02:00
2014-05-31 01:59:03 +02:00
/// <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 ; }
2016-02-07 14:24:01 -08:00
/// <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 ) { }
2020-03-27 21:14:05 +01:00
/// <summary>
/// Called when properties for the Player entity are received from the server
/// </summary>
/// <param name="prop">Dictionary of player properties</param>
2020-03-23 19:59:00 +08:00
public virtual void OnPlayerProperty ( Dictionary < string , Double > prop ) { }
2020-03-27 21:14:05 +01:00
/// <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>
2020-03-23 19:59:00 +08:00
public virtual void OnServerTpsUpdate ( Double tps ) { }
2020-08-07 13:35:23 +05:00
/// <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 ) { }
2020-03-27 21:14:05 +01:00
/// <summary>
/// Called when an entity moved nearby
/// </summary>
/// <param name="entity">Entity with updated location</param>
2020-03-23 19:59:00 +08:00
public virtual void OnEntityMove ( Mapping . Entity entity ) { }
2020-05-29 23:18:34 +05:00
/// <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 , string Result ) { }
2020-05-01 09:37:15 -05:00
2020-03-27 21:14:05 +01:00
/// <summary>
/// Called when an entity spawned nearby
/// </summary>
/// <param name="entity">New Entity</param>
2020-03-23 19:59:00 +08:00
public virtual void OnEntitySpawn ( Mapping . Entity entity ) { }
2020-03-27 21:14:05 +01:00
/// <summary>
/// Called when an entity despawns/dies nearby
/// </summary>
/// <param name="entity">Entity wich has just disappeared</param>
2020-03-24 15:03:32 +08:00
public virtual void OnEntityDespawn ( Mapping . Entity entity ) { }
2020-03-23 19:59:00 +08:00
2020-05-01 14:02:23 +02:00
/// <summary>
/// Called when the player held item has changed
/// </summary>
/// <param name="slot">New slot ID</param>
2020-04-08 18:23:19 +08:00
public virtual void OnHeldItemChange ( byte slot ) { }
2020-05-01 14:02:23 +02:00
/// <summary>
/// Called when the player health has been updated
/// </summary>
/// <param name="health">New player health</param>
/// <param name="food">New food level</param>
2020-04-08 18:23:19 +08:00
public virtual void OnHealthUpdate ( float health , int food ) { }
2020-05-29 23:18:34 +05:00
/// <summary>
/// Called when an explosion occurs on the server
/// </summary>
/// <param name="explode">Explosion location</param>
2021-07-04 11:26:41 +05:00
/// <param name="strength">Explosion strength</param>
2020-05-29 23:18:34 +05:00
/// <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 ) { }
2022-09-18 00:18:27 +02:00
2020-06-07 16:16:49 +05:00
/// <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 ) { }
2022-09-18 00:18:27 +02:00
2020-08-29 17:46:04 +05:00
/// <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 ) { }
2022-09-18 00:18:27 +02:00
2020-06-20 17:57:07 +05:00
/// <summary>
2022-09-18 00:18:27 +02:00
/// 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
2020-06-20 17:57:07 +05:00
/// </summary>
2022-09-18 00:18:27 +02:00
/// <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 ) { }
2020-11-08 23:39:07 +01:00
/// <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 ) { }
2020-06-20 17:57:07 +05:00
/// <summary>
2020-07-07 13:21:55 +08:00
/// Called when received a title from the server
2020-06-20 17:57:07 +05:00
/// <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>
2020-07-07 13:21:55 +08:00
/// Called when an entity equipped
2020-06-20 17:57:07 +05:00
/// </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>
2022-10-02 18:31:08 +08:00
public virtual void OnEntityEquipment ( Entity entity , int slot , Item ? item ) { }
2021-07-04 11:26:41 +05:00
2020-07-04 13:45:51 +05:00
/// <summary>
2020-07-07 13:21:55 +08:00
/// Called when an entity has effect applied
2020-07-04 13:45:51 +05:00
/// </summary>
2021-07-04 11:26:41 +05:00
/// <param name="entity">entity</param>
2020-07-04 13:45:51 +05:00
/// <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 ) { }
2020-07-07 13:21:55 +08:00
2020-07-04 13:45:51 +05:00
/// <summary>
2020-07-07 13:21:55 +08:00
/// Called when a scoreboard objective updated
2020-07-04 13:45:51 +05:00
/// </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>
public virtual void OnScoreboardObjective ( string objectivename , byte mode , string objectivevalue , int type , string json ) { }
2022-09-18 00:18:27 +02:00
2020-07-04 13:45:51 +05:00
/// <summary>
2020-07-07 13:21:55 +08:00
/// Called when a scoreboard updated
2020-07-04 13:45:51 +05:00
/// </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>
2020-07-07 13:21:55 +08:00
/// <param name="value">The score to be displayed next to the entry. Only sent when Action does not equal 1.</param>
2022-07-24 22:21:15 +08:00
public virtual void OnUpdateScore ( string entityname , int action , string objectivename , int value ) { }
2020-05-29 23:18:34 +05:00
2020-07-07 13:21:55 +08:00
/// <summary>
/// Called when an inventory/container was updated by server
/// </summary>
/// <param name="inventoryId"></param>
2020-07-07 11:26:49 +08:00
public virtual void OnInventoryUpdate ( int inventoryId ) { }
2020-07-07 13:21:55 +08:00
/// <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 ) { }
2020-08-06 21:57:23 +08:00
/// <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>
2022-08-15 23:55:44 +08:00
public virtual void OnPlayerLeave ( Guid uuid , string? name ) { }
2022-09-18 00:18:27 +02:00
2020-08-19 00:08:19 +05:00
/// <summary>
/// Called when the player deaths
/// </summary>
public virtual void OnDeath ( ) { }
2022-09-18 00:18:27 +02:00
2020-08-07 13:35:23 +05:00
/// <summary>
/// Called when the player respawns
/// </summary>
public virtual void OnRespawn ( ) { }
2020-08-06 21:57:23 +08:00
2020-08-15 21:32:46 +08:00
/// <summary>
/// Called when the health of an entity changed
/// </summary>
2020-08-20 21:36:50 +05:00
/// <param name="entity">Entity</param>
2020-08-15 21:32:46 +08:00
/// <param name="health">The health of the entity</param>
2020-08-20 21:36:50 +05:00
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>
2022-09-15 21:11:47 +08:00
public virtual void OnEntityMetadata ( Entity entity , Dictionary < int , object? > metadata ) { }
2020-08-15 21:32:46 +08:00
2021-03-21 22:17:19 +08:00
/// <summary>
/// Called when the status of client player have been changed
/// </summary>
/// <param name="statusId"></param>
public virtual void OnPlayerStatus ( byte statusId ) { }
2020-09-07 03:51:42 +08:00
/// <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 ) { }
2014-05-31 01:59:03 +02:00
/* =================================================================== */
/* ToolBox - Methods below might be useful while creating your bot. */
/* You should not need to interact with other classes of the program. */
2014-07-20 12:02:17 +02:00
/* All the methods in this ChatBot class should do the job for you. */
2014-05-31 01:59:03 +02:00
/* =================================================================== */
/// <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>
2021-02-12 20:23:03 +01:00
/// <param name="sendImmediately">Bypass send queue (Deprecated, still there for compatibility purposes but ignored)</param>
2020-10-24 17:41:35 +02:00
/// <returns>TRUE if successfully sent (Deprectated, always returns TRUE for compatibility purposes with existing scripts)</returns>
2016-01-29 16:11:26 -08:00
protected bool SendText ( string text , bool sendImmediately = false )
2014-05-31 01:59:03 +02:00
{
2014-07-20 12:02:17 +02:00
LogToConsole ( "Sending '" + text + "'" ) ;
2020-10-24 17:41:35 +02:00
Handler . SendText ( text ) ;
return true ;
2014-06-14 13:20:15 +02:00
}
/// <summary>
2014-06-14 18:48:43 +02:00
/// Perform an internal MCC command (not a server command, use SendText() instead for that!)
2014-06-14 13:20:15 +02:00
/// </summary>
2014-06-14 18:48:43 +02:00
/// <param name="command">The command to process</param>
2020-03-27 21:14:05 +01:00
/// <param name="localVars">Local variables passed along with the command</param>
2014-06-14 18:48:43 +02:00
/// <returns>TRUE if the command was indeed an internal MCC command</returns>
2022-10-02 18:31:08 +08:00
protected bool PerformInternalCommand ( string command , Dictionary < string , object > ? localVars = null )
2014-06-14 13:20:15 +02:00
{
2022-10-02 18:31:08 +08:00
string? temp = "" ;
2020-03-27 21:14:05 +01:00
return Handler . PerformInternalCommand ( command , ref temp , localVars ) ;
2014-06-14 13:20:15 +02:00
}
/// <summary>
/// Perform an internal MCC command (not a server command, use SendText() instead for that!)
/// </summary>
2014-06-14 18:48:43 +02:00
/// <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>
2020-03-27 21:14:05 +01:00
/// <param name="localVars">Local variables passed along with the command</param>
2014-06-14 18:48:43 +02:00
/// <returns>TRUE if the command was indeed an internal MCC command</returns>
2022-10-02 18:31:08 +08:00
protected bool PerformInternalCommand ( string command , ref string? response_msg , Dictionary < string , object > ? localVars = null )
2014-06-14 13:20:15 +02:00
{
2020-03-27 21:14:05 +01:00
return Handler . PerformInternalCommand ( command , ref response_msg , localVars ) ;
2014-05-31 01:59:03 +02:00
}
/// <summary>
/// Remove color codes ("§c") from a text message received from the server
/// </summary>
2022-10-02 18:31:08 +08:00
public static string GetVerbatim ( string? text )
2014-05-31 01:59:03 +02:00
{
2022-09-18 00:18:27 +02:00
if ( String . IsNullOrEmpty ( text ) )
2014-05-31 01:59:03 +02:00
return String . Empty ;
int idx = 0 ;
var data = new char [ text . Length ] ;
2022-09-18 00:18:27 +02:00
for ( int i = 0 ; i < text . Length ; i + + )
if ( text [ i ] ! = '§' )
2014-05-31 01:59:03 +02:00
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>
2016-08-22 23:15:16 +02:00
public static bool IsValidName ( string username )
2014-05-31 01:59:03 +02:00
{
2015-10-22 22:17:15 +02:00
if ( String . IsNullOrEmpty ( username ) )
2014-05-31 01:59:03 +02:00
return false ;
2015-10-22 22:17:15 +02:00
foreach ( char c in username )
if ( ! ( ( c > = 'a' & & c < = 'z' )
2014-05-31 01:59:03 +02:00
| | ( c > = 'A' & & c < = 'Z' )
| | ( c > = '0' & & c < = '9' )
2022-09-18 00:18:27 +02:00
| | c = = '_' ) )
2014-05-31 01:59:03 +02:00
return false ;
return true ;
}
/// <summary>
2014-06-14 13:51:30 +02:00
/// Returns true if the text passed is a private message sent to the bot
2014-05-31 01:59:03 +02:00
/// </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>
2015-06-20 22:58:18 +02:00
protected static bool IsPrivateMessage ( string text , ref string message , ref string sender )
2014-05-31 01:59:03 +02:00
{
2015-10-22 22:17:15 +02:00
if ( String . IsNullOrEmpty ( text ) )
return false ;
2015-06-20 22:58:18 +02:00
text = GetVerbatim ( text ) ;
2014-05-31 01:59:03 +02:00
2019-04-17 05:32:31 +02:00
//User-defined regex for private chat messages
if ( Settings . ChatFormat_Private ! = null )
{
Match regexMatch = Settings . ChatFormat_Private . Match ( text ) ;
if ( regexMatch . Success & & regexMatch . Groups . Count > = 3 )
{
sender = regexMatch . Groups [ 1 ] . Value ;
message = regexMatch . Groups [ 2 ] . Value ;
return IsValidName ( sender ) ;
}
}
2015-10-22 22:17:15 +02:00
//Built-in detection routine for private messages
if ( Settings . ChatFormat_Builtins )
2014-05-31 01:59:03 +02:00
{
2015-10-22 22:17:15 +02:00
string [ ] tmp = text . Split ( ' ' ) ;
try
2014-05-31 01:59:03 +02:00
{
2015-10-22 22:17:15 +02:00
//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" )
2014-06-03 13:05:53 +02:00
{
2015-10-22 22:17:15 +02:00
if ( tmp . Length > 4 & & tmp [ 2 ] = = "to" & & tmp [ 3 ] = = "you:" )
{
2022-10-02 18:31:08 +08:00
message = text [ ( tmp [ 0 ] . Length + 18 ) . . ] ; //MC 1.7
2015-10-22 22:17:15 +02:00
}
2022-10-02 18:31:08 +08:00
else message = text [ ( tmp [ 0 ] . Length + 10 ) . . ] ; //MC 1.5
2015-10-22 22:17:15 +02:00
sender = tmp [ 0 ] ;
return IsValidName ( sender ) ;
2014-06-03 13:05:53 +02:00
}
2014-05-31 01:59:03 +02:00
2015-10-22 22:17:15 +02:00
//Detect Essentials (Bukkit) /m messages
//[Someone -> me] message
//[~Someone -> me] message
else if ( text [ 0 ] = = '[' & & tmp . Length > 3 & & tmp [ 1 ] = = "->"
2016-02-27 17:56:47 +01:00
& & ( tmp [ 2 ] . ToLower ( ) = = "me]" | | tmp [ 2 ] . ToLower ( ) = = "moi]" ) ) //'me' is replaced by 'moi' in french servers
2015-10-22 22:17:15 +02:00
{
2022-10-02 18:31:08 +08:00
message = text [ ( tmp [ 0 ] . Length + 4 + tmp [ 2 ] . Length + 1 ) . . ] ;
sender = tmp [ 0 ] [ 1. . ] ;
if ( sender [ 0 ] = = '~' ) { sender = sender [ 1. . ] ; }
2015-10-22 22:17:15 +02:00
return IsValidName ( sender ) ;
}
2014-07-29 17:08:24 +02:00
2015-10-22 22:17:15 +02:00
//Detect Modified server messages. /m
//[Someone @ me] message
else if ( text [ 0 ] = = '[' & & tmp . Length > 3 & & tmp [ 1 ] = = "@"
2016-02-27 17:56:47 +01:00
& & ( tmp [ 2 ] . ToLower ( ) = = "me]" | | tmp [ 2 ] . ToLower ( ) = = "moi]" ) ) //'me' is replaced by 'moi' in french servers
2015-10-22 22:17:15 +02:00
{
2022-10-02 18:31:08 +08:00
message = text [ ( tmp [ 0 ] . Length + 4 + tmp [ 2 ] . Length + 0 ) . . ] ;
sender = tmp [ 0 ] [ 1. . ] ;
if ( sender [ 0 ] = = '~' ) { sender = sender [ 1. . ] ; }
2015-10-22 22:17:15 +02:00
return IsValidName ( sender ) ;
}
2015-09-02 23:01:46 -04:00
2015-10-22 22:17:15 +02:00
//Detect Essentials (Bukkit) /me messages with some custom prefix
//[Prefix] [Someone -> me] message
//[Prefix] [~Someone -> me] message
2022-10-02 18:31:08 +08:00
else if ( text [ 0 ] = = '[' & & tmp [ 0 ] [ ^ 1 ] = = ']'
2015-10-22 22:17:15 +02:00
& & tmp [ 1 ] [ 0 ] = = '[' & & tmp . Length > 4 & & tmp [ 2 ] = = "->"
2016-02-27 17:56:47 +01:00
& & ( tmp [ 3 ] . ToLower ( ) = = "me]" | | tmp [ 3 ] . ToLower ( ) = = "moi]" ) )
2015-10-22 22:17:15 +02:00
{
2022-10-02 18:31:08 +08:00
message = text [ ( tmp [ 0 ] . Length + 1 + tmp [ 1 ] . Length + 4 + tmp [ 3 ] . Length + 1 ) . . ] ;
sender = tmp [ 1 ] [ 1. . ] ;
if ( sender [ 0 ] = = '~' ) { sender = sender [ 1. . ] ; }
2015-10-22 22:17:15 +02:00
return IsValidName ( sender ) ;
}
2015-07-31 12:23:13 +02:00
2015-10-22 22:17:15 +02:00
//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 ] = = "->"
2016-02-27 17:56:47 +01:00
& & ( tmp [ 3 ] . ToLower ( ) = = "me]" | | tmp [ 3 ] . ToLower ( ) = = "moi]" ) )
2015-10-22 22:17:15 +02:00
{
2022-10-02 18:31:08 +08:00
message = text [ ( tmp [ 0 ] . Length + 1 + tmp [ 1 ] . Length + 4 + tmp [ 2 ] . Length + 1 ) . . ] ;
sender = tmp [ 0 ] [ 1. . ] ;
if ( sender [ 0 ] = = '~' ) { sender = sender [ 1. . ] ; }
2015-10-22 22:17:15 +02:00
return IsValidName ( sender ) ;
}
//Detect HeroChat PMsend
//From Someone: message
else if ( text . StartsWith ( "From " ) )
{
2022-10-02 18:31:08 +08:00
sender = text [ 5. . ] . Split ( ':' ) [ 0 ] ;
message = text [ ( text . IndexOf ( ':' ) + 2 ) . . ] ;
2015-10-22 22:17:15 +02:00
return IsValidName ( sender ) ;
}
else return false ;
2014-07-29 17:08:24 +02:00
}
2015-10-22 22:17:15 +02:00
catch ( IndexOutOfRangeException ) { /* Not an expected chat format */ }
2016-01-26 10:35:44 +01:00
catch ( ArgumentOutOfRangeException ) { /* Same here */ }
2015-10-22 22:17:15 +02:00
}
2015-02-26 12:45:24 +01:00
2015-10-22 22:17:15 +02:00
return false ;
2014-05-31 01:59:03 +02:00
}
/// <summary>
2014-06-14 13:51:30 +02:00
/// Returns true if the text passed is a public message written by a player on the chat
2014-05-31 01:59:03 +02:00
/// </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>
2015-06-20 22:58:18 +02:00
protected static bool IsChatMessage ( string text , ref string message , ref string sender )
2014-05-31 01:59:03 +02:00
{
2015-10-22 22:17:15 +02:00
if ( String . IsNullOrEmpty ( text ) )
return false ;
2015-06-20 22:58:18 +02:00
text = GetVerbatim ( text ) ;
2019-04-17 05:32:31 +02:00
//User-defined regex for public chat messages
if ( Settings . ChatFormat_Public ! = null )
{
Match regexMatch = Settings . ChatFormat_Public . Match ( text ) ;
if ( regexMatch . Success & & regexMatch . Groups . Count > = 3 )
{
sender = regexMatch . Groups [ 1 ] . Value ;
message = regexMatch . Groups [ 2 ] . Value ;
return IsValidName ( sender ) ;
}
}
2015-10-22 22:17:15 +02:00
//Built-in detection routine for public messages
if ( Settings . ChatFormat_Builtins )
2014-05-31 01:59:03 +02:00
{
2015-10-22 22:17:15 +02:00
string [ ] tmp = text . Split ( ' ' ) ;
2015-05-18 16:15:58 +02:00
//Detect vanilla/factions Messages
//<Someone> message
//<*Faction Someone> message
//<*Faction Someone>: message
//<*Faction ~Nicknamed>: message
2015-10-22 22:17:15 +02:00
if ( text [ 0 ] = = '<' )
2014-05-31 01:59:03 +02:00
{
2015-05-18 16:15:58 +02:00
try
{
2022-10-02 18:31:08 +08:00
text = text [ 1. . ] ;
2015-05-18 16:15:58 +02:00
string [ ] tmp2 = text . Split ( '>' ) ;
sender = tmp2 [ 0 ] ;
2022-10-02 18:31:08 +08:00
message = text [ ( sender . Length + 2 ) . . ] ;
2015-05-18 16:15:58 +02:00
if ( message . Length > 1 & & message [ 0 ] = = ' ' )
2022-10-02 18:31:08 +08:00
{ message = message [ 1. . ] ; }
2015-05-18 16:15:58 +02:00
tmp2 = sender . Split ( ' ' ) ;
2022-10-02 18:31:08 +08:00
sender = tmp2 [ ^ 1 ] ;
if ( sender [ 0 ] = = '~' ) { sender = sender [ 1. . ] ; }
2015-06-20 22:58:18 +02:00
return IsValidName ( sender ) ;
2015-05-18 16:15:58 +02:00
}
2015-10-26 23:19:06 +01:00
catch ( IndexOutOfRangeException ) { /* Not a vanilla/faction message */ }
2016-01-26 10:35:44 +01:00
catch ( ArgumentOutOfRangeException ) { /* Same here */ }
2015-05-18 16:15:58 +02:00
}
//Detect HeroChat Messages
2015-09-03 23:42:01 -04:00
//Public chat messages
2015-05-18 16:15:58 +02:00
//[Channel] [Rank] User: Message
2015-10-22 22:17:15 +02:00
else if ( text [ 0 ] = = '[' & & text . Contains ( ':' ) & & tmp . Length > 2 )
2015-05-18 16:15:58 +02:00
{
2015-10-26 23:19:06 +01:00
try
{
int name_end = text . IndexOf ( ':' ) ;
2022-10-02 18:31:08 +08:00
int name_start = text [ . . name_end ] . LastIndexOf ( ']' ) + 2 ;
sender = text [ name_start . . name_end ] ;
message = text [ ( name_end + 2 ) . . ] ;
2015-10-26 23:19:06 +01:00
return IsValidName ( sender ) ;
}
catch ( IndexOutOfRangeException ) { /* Not a herochat message */ }
2016-01-26 10:35:44 +01:00
catch ( ArgumentOutOfRangeException ) { /* Same here */ }
2014-05-31 01:59:03 +02:00
}
2015-07-31 12:23:13 +02:00
//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 ( ' ' )
2015-10-22 22:17:15 +02:00
& & text . IndexOf ( ' ' ) < text . IndexOf ( ':' ) )
2015-07-31 12:23:13 +02:00
{
2015-10-26 23:19:06 +01:00
try
2015-07-31 12:23:13 +02:00
{
2015-10-26 23:19:06 +01:00
string prefix = tmp [ 0 ] ;
string user = tmp [ 1 ] ;
string semicolon = tmp [ 2 ] ;
if ( prefix . All ( c = > char . IsLetterOrDigit ( c ) | | new char [ ] { '*' , '<' , '>' , '_' } . Contains ( c ) )
& & semicolon = = ":" )
{
2022-10-02 18:31:08 +08:00
message = text [ ( prefix . Length + user . Length + 4 ) . . ] ;
2015-10-26 23:19:06 +01:00
return IsValidName ( user ) ;
}
2015-07-31 12:23:13 +02:00
}
2015-10-26 23:19:06 +01:00
catch ( IndexOutOfRangeException ) { /* Not a <unknown plugin> message */ }
2016-01-26 10:35:44 +01:00
catch ( ArgumentOutOfRangeException ) { /* Same here */ }
2015-07-31 12:23:13 +02:00
}
2014-05-31 01:59:03 +02:00
}
2015-10-22 22:17:15 +02:00
2015-05-18 16:15:58 +02:00
return false ;
2014-05-31 01:59:03 +02:00
}
2014-06-14 13:51:30 +02:00
/// <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>
2015-06-20 22:58:18 +02:00
protected static bool IsTeleportRequest ( string text , ref string sender )
2014-06-14 13:51:30 +02:00
{
2015-10-22 22:17:15 +02:00
if ( String . IsNullOrEmpty ( text ) )
return false ;
2015-06-20 22:58:18 +02:00
text = GetVerbatim ( text ) ;
2015-10-22 22:17:15 +02:00
2019-04-17 05:32:31 +02:00
//User-defined regex for teleport requests
if ( Settings . ChatFormat_TeleportRequest ! = null )
{
Match regexMatch = Settings . ChatFormat_TeleportRequest . Match ( text ) ;
if ( regexMatch . Success & & regexMatch . Groups . Count > = 2 )
{
sender = regexMatch . Groups [ 1 ] . Value ;
return IsValidName ( sender ) ;
}
}
2015-10-22 22:17:15 +02:00
//Built-in detection routine for teleport requests
if ( Settings . ChatFormat_Builtins )
2014-06-14 13:51:30 +02:00
{
2015-10-22 22:17:15 +02:00
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 ] ;
2022-10-02 18:31:08 +08:00
else //Username has requested..
sender = tmp [ 0 ] ;
2015-10-22 22:17:15 +02:00
//~Username has requested...
if ( sender . Length > 1 & & sender [ 0 ] = = '~' )
2022-10-02 18:31:08 +08:00
sender = sender [ 1. . ] ;
2015-10-22 22:17:15 +02:00
//Final check on username validity
return IsValidName ( sender ) ;
}
}
return false ;
2014-06-14 13:51:30 +02:00
}
2014-05-31 01:59:03 +02:00
/// <summary>
2015-06-21 16:40:13 +02:00
/// Write some text in the console. Nothing will be sent to the server.
2014-05-31 01:59:03 +02:00
/// </summary>
/// <param name="text">Log text to write</param>
2022-10-02 18:31:08 +08:00
protected void LogToConsole ( object? text )
2014-05-31 01:59:03 +02:00
{
2021-01-29 07:45:18 +08:00
if ( _handler = = null | | master = = null )
2022-10-02 18:31:08 +08:00
ConsoleIO . WriteLogLine ( String . Format ( "[{0}] {1}" , GetType ( ) . Name , text ) ) ;
2021-01-29 07:45:18 +08:00
else
2022-10-02 18:31:08 +08:00
Handler . Log . Info ( String . Format ( "[{0}] {1}" , GetType ( ) . Name , text ) ) ;
2015-06-20 22:58:18 +02:00
string logfile = Settings . ExpandVars ( Settings . chatbotLogFile ) ;
2014-07-20 12:02:17 +02:00
2014-09-07 15:17:47 +02:00
if ( ! String . IsNullOrEmpty ( logfile ) )
2014-07-20 12:02:17 +02:00
{
2014-09-07 15:17:47 +02:00
if ( ! File . Exists ( logfile ) )
2014-07-20 12:02:17 +02:00
{
2022-10-02 18:31:08 +08:00
try { Directory . CreateDirectory ( Path . GetDirectoryName ( logfile ) ! ) ; }
2014-07-20 12:02:17 +02:00
catch { return ; /* Invalid path or access denied */ }
2014-09-07 15:17:47 +02:00
try { File . WriteAllText ( logfile , "" ) ; }
2014-07-20 12:02:17 +02:00
catch { return ; /* Invalid file name or access denied */ }
}
2015-06-20 22:58:18 +02:00
File . AppendAllLines ( logfile , new string [ ] { GetTimestamp ( ) + ' ' + text } ) ;
2014-07-20 12:02:17 +02:00
}
2014-05-31 01:59:03 +02:00
}
2017-03-14 22:04:35 +01:00
/// <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 ( Settings . DebugMessages )
LogToConsole ( text ) ;
}
2020-10-17 19:41:31 +08:00
/// <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 ( Translations . TryGet ( 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>
2022-10-02 18:31:08 +08:00
protected void LogDebugToConsoleTranslated ( string key , params object? [ ] args )
2020-10-17 19:41:31 +08:00
{
LogDebugToConsole ( Translations . TryGet ( key , args ) ) ;
}
2014-05-31 01:59:03 +02:00
/// <summary>
/// Disconnect from the server and restart the program
2015-05-18 16:15:58 +02:00
/// It will unload and reload all the bots and then reconnect to the server
2014-05-31 01:59:03 +02:00
/// </summary>
2019-10-03 09:46:08 +02:00
/// <param name="ExtraAttempts">In case of failure, maximum extra attempts before aborting</param>
2017-03-13 21:15:36 +01:00
/// <param name="delaySeconds">Optional delay, in seconds, before restarting</param>
protected void ReconnectToTheServer ( int ExtraAttempts = 3 , int delaySeconds = 0 )
2014-05-31 01:59:03 +02:00
{
2020-04-02 18:19:37 +02:00
if ( Settings . DebugMessages )
2022-10-02 18:31:08 +08:00
ConsoleIO . WriteLogLine ( Translations . Get ( "chatbot.reconnect" , GetType ( ) . Name ) ) ;
2020-06-20 15:01:16 +02:00
McClient . ReconnectionAttemptsLeft = ExtraAttempts ;
2017-03-13 21:15:36 +01:00
Program . Restart ( delaySeconds ) ;
2014-05-31 01:59:03 +02:00
}
/// <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 ( )
{
2021-03-07 14:21:19 +08:00
foreach ( string cmdName in registeredCommands )
{
Handler . UnregisterCommand ( cmdName ) ;
}
2015-06-20 22:58:18 +02:00
Handler . BotUnLoad ( this ) ;
2014-05-31 01:59:03 +02:00
}
/// <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 )
{
2016-01-27 00:23:25 +01:00
SendText ( String . Format ( "/{0} {1} {2}" , Settings . PrivateMsgsCmdName , player , message ) ) ;
2014-05-31 01:59:03 +02:00
}
/// <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>
2020-03-27 21:14:05 +01:00
/// <param name="localVars">Local variables for use in the Script</param>
2022-10-02 18:31:08 +08:00
protected void RunScript ( string filename , string? playername = null , Dictionary < string , object > ? localVars = null )
2014-05-31 01:59:03 +02:00
{
2020-03-27 21:14:05 +01:00
Handler . BotLoad ( new ChatBots . Script ( filename , playername , localVars ) ) ;
2014-05-31 01:59:03 +02:00
}
2014-07-20 12:02:17 +02:00
2020-07-06 13:10:37 +02:00
/// <summary>
/// Load an additional ChatBot
/// </summary>
/// <param name="chatBot">ChatBot to load</param>
protected void BotLoad ( ChatBot chatBot )
{
Handler . BotLoad ( chatBot ) ;
}
2019-04-28 21:32:03 +02:00
/// <summary>
/// Check whether Terrain and Movements is enabled.
/// </summary>
/// <returns>Enable status.</returns>
public bool GetTerrainEnabled ( )
{
return Handler . GetTerrainEnabled ( ) ;
}
/// <summary>
/// Enable or disable Terrain and Movements.
/// Please note that Enabling will be deferred until next relog, respawn or world change.
/// </summary>
/// <param name="enabled">Enabled</param>
/// <returns>TRUE if the setting was applied immediately, FALSE if delayed.</returns>
public bool SetTerrainEnabled ( bool enabled )
{
return Handler . SetTerrainEnabled ( enabled ) ;
}
2020-03-23 19:59:00 +08:00
/// <summary>
/// Get entity handling status
/// </summary>
/// <returns></returns>
/// <remarks>Entity Handling cannot be enabled in runtime (or after joining server)</remarks>
public bool GetEntityHandlingEnabled ( )
{
return Handler . GetEntityHandlingEnabled ( ) ;
}
2020-05-02 03:52:17 -05:00
/// <summary>
2020-05-02 03:55:23 -05:00
/// start Sneaking
/// </summary>
2020-05-03 10:51:50 -05:00
protected bool Sneak ( bool on )
2020-05-02 03:55:23 -05:00
{
2020-05-03 11:21:34 -05:00
return SendEntityAction ( on ? Protocol . EntityActionType . StartSneaking : Protocol . EntityActionType . StopSneaking ) ;
2020-05-02 03:55:23 -05:00
}
2020-05-29 23:18:34 +05:00
2020-05-02 03:55:23 -05:00
/// <summary>
2020-05-02 03:53:39 -05:00
/// Send Entity Action
/// </summary>
2020-05-03 11:21:34 -05:00
private bool SendEntityAction ( Protocol . EntityActionType entityAction )
2020-05-02 03:53:39 -05:00
{
2020-06-20 15:18:34 +02:00
return Handler . SendEntityAction ( entityAction ) ;
2020-05-02 03:53:39 -05:00
}
2020-05-29 23:18:34 +05:00
/// <summary>
2020-06-20 21:30:23 +02:00
/// Attempt to dig a block at the specified location
2020-05-29 23:18:34 +05:00
/// </summary>
2020-11-14 10:19:51 +01:00
/// <param name="location">Location of block to dig</param>
/// <param name="swingArms">Also perform the "arm swing" animation</param>
/// <param name="lookAtBlock">Also look at the block before digging</param>
protected bool DigBlock ( Location location , bool swingArms = true , bool lookAtBlock = true )
2020-05-29 23:18:34 +05:00
{
2020-11-14 10:19:51 +01:00
return Handler . DigBlock ( location , swingArms , lookAtBlock ) ;
2020-05-29 23:18:34 +05:00
}
2020-05-02 03:53:39 -05:00
/// <summary>
2020-05-02 03:52:17 -05:00
/// SetSlot
/// </summary>
protected void SetSlot ( int slotNum )
{
2020-06-14 15:41:34 +02:00
Handler . ChangeSlot ( ( short ) slotNum ) ;
2020-05-02 03:52:17 -05:00
}
2020-03-26 15:01:42 +08:00
2016-01-16 17:51:08 +01:00
/// <summary>
/// Get the current Minecraft World
/// </summary>
/// <returns>Minecraft world or null if associated setting is disabled</returns>
2022-10-02 18:31:08 +08:00
protected World GetWorld ( )
2016-01-16 17:51:08 +01:00
{
2022-10-02 18:31:08 +08:00
return Handler . GetWorld ( ) ;
2016-01-16 17:51:08 +01:00
}
2022-09-18 00:18:27 +02:00
2020-07-04 13:45:51 +05:00
/// <summary>
2020-08-29 17:46:04 +05:00
/// Get all Entities
2020-07-04 13:45:51 +05:00
/// </summary>
/// <returns>All Entities</returns>
protected Dictionary < int , Entity > GetEntities ( )
{
return Handler . GetEntities ( ) ;
}
2016-01-16 17:51:08 +01:00
2020-08-29 17:46:04 +05:00
/// <summary>
/// Get all players Latency
/// </summary>
/// <returns>All players latency</returns>
protected Dictionary < string , int > GetPlayersLatency ( )
{
return Handler . GetPlayersLatency ( ) ;
}
2022-09-18 00:18:27 +02:00
2016-05-04 23:47:08 +02:00
/// <summary>
2020-09-13 16:33:25 +02:00
/// Get the current location of the player (Feet location)
2016-05-04 23:47:08 +02:00
/// </summary>
/// <returns>Minecraft world or null if associated setting is disabled</returns>
protected Mapping . Location GetCurrentLocation ( )
{
return Handler . GetCurrentLocation ( ) ;
}
/// <summary>
/// Move to the specified location
/// </summary>
/// <param name="location">Location to reach</param>
2020-06-14 15:41:34 +02:00
/// <param name="allowUnsafe">Allow possible but unsafe locations thay may hurt the player: lava, cactus...</param>
2022-04-29 22:56:41 +00:00
/// <param name="allowDirectTeleport">Allow non-vanilla direct teleport instead of computing path, but may cause invalid moves and/or trigger anti-cheat plugins</param>
/// <param name="maxOffset">If no valid path can be found, also allow locations within specified distance of destination</param>
/// <param name="minOffset">Do not get closer of destination than specified distance</param>
/// <param name="timeout">How long to wait before stopping computation (default: 5 seconds)</param>
/// <remarks>When location is unreachable, computation will reach timeout, then optionally fallback to a close location within maxOffset</remarks>
2016-05-04 23:47:08 +02:00
/// <returns>True if a path has been found</returns>
2022-04-29 22:56:41 +00:00
protected bool MoveToLocation ( Mapping . Location location , bool allowUnsafe = false , bool allowDirectTeleport = false , int maxOffset = 0 , int minOffset = 0 , TimeSpan ? timeout = null )
2016-05-04 23:47:08 +02:00
{
2022-04-29 22:56:41 +00:00
return Handler . MoveTo ( location , allowUnsafe , allowDirectTeleport , maxOffset , minOffset , timeout ) ;
2016-05-04 23:47:08 +02:00
}
2022-04-29 22:56:41 +00:00
/// <summary>
/// Check if the client is currently processing a Movement.
/// </summary>
/// <returns>true if a movement is currently handled</returns>
protected bool ClientIsMoving ( )
{
return Handler . ClientIsMoving ( ) ;
}
2022-09-18 00:18:27 +02:00
2020-05-01 14:02:23 +02:00
/// <summary>
/// Look at the specified location
/// </summary>
/// <param name="location">Location to look at</param>
protected void LookAtLocation ( Mapping . Location location )
{
Handler . UpdateLocation ( Handler . GetCurrentLocation ( ) , location ) ;
}
2022-09-12 16:27:37 +08:00
/// <summary>
/// Look at the specified location
/// </summary>
/// <param name="yaw">Yaw to look at</param>
/// <param name="pitch">Pitch to look at</param>
protected void LookAtLocation ( float yaw , float pitch )
{
Handler . UpdateLocation ( Handler . GetCurrentLocation ( ) , yaw , pitch ) ;
}
2022-10-02 13:49:36 +08:00
/// <summary>
/// Find the block on the line of sight.
/// </summary>
/// <param name="maxDistance">Maximum distance from sight</param>
/// <param name="includeFluids">Whether to detect fluid</param>
/// <returns>Position of the block</returns>
protected Tuple < bool , Location , Block > GetLookingBlock ( double maxDistance = 4.5 , bool includeFluids = false )
{
return RaycastHelper . RaycastBlock ( Handler , maxDistance , includeFluids ) ;
}
2014-07-20 12:02:17 +02:00
/// <summary>
2015-05-18 16:15:58 +02:00
/// Get a Y-M-D h:m:s timestamp representing the current system date and time
2014-07-20 12:02:17 +02:00
/// </summary>
2015-06-20 22:58:18 +02:00
protected static string GetTimestamp ( )
2014-07-20 12:02:17 +02:00
{
DateTime time = DateTime . Now ;
2015-05-18 16:15:58 +02:00
return String . Format ( "{0}-{1}-{2} {3}:{4}:{5}" ,
time . Year . ToString ( "0000" ) ,
time . Month . ToString ( "00" ) ,
time . Day . ToString ( "00" ) ,
time . Hour . ToString ( "00" ) ,
time . Minute . ToString ( "00" ) ,
time . Second . ToString ( "00" ) ) ;
2014-07-20 12:02:17 +02:00
}
2015-05-26 19:16:50 +02:00
/// <summary>
/// Load entries from a file as a string array, removing duplicates and empty lines
/// </summary>
/// <param name="file">File to load</param>
/// <returns>The string array or an empty array if failed to load the file</returns>
2015-06-21 16:40:13 +02:00
protected string [ ] LoadDistinctEntriesFromFile ( string file )
2015-05-26 19:16:50 +02:00
{
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.
2020-05-29 20:23:03 +02:00
return File . ReadAllLines ( file , Encoding . UTF8 )
2015-05-26 19:16:50 +02:00
. Where ( line = > ! String . IsNullOrWhiteSpace ( line ) )
. Select ( line = > line . ToLower ( ) )
. Distinct ( ) . ToArray ( ) ;
}
else
{
2019-09-22 10:16:43 +02:00
LogToConsole ( "File not found: " + System . IO . Path . GetFullPath ( file ) ) ;
2022-10-02 18:31:08 +08:00
return Array . Empty < string > ( ) ;
2015-05-26 19:16:50 +02:00
}
}
2016-02-07 14:24:01 -08:00
2019-09-20 09:26:30 +02:00
/// <summary>
/// Return the Server Port where the client is connected to
/// </summary>
/// <returns>Server Port where the client is connected to</returns>
protected int GetServerPort ( )
{
return Handler . GetServerPort ( ) ;
}
/// <summary>
/// Return the Server Host where the client is connected to
/// </summary>
/// <returns>Server Host where the client is connected to</returns>
protected string GetServerHost ( )
{
return Handler . GetServerHost ( ) ;
}
/// <summary>
/// Return the Username of the current account
/// </summary>
/// <returns>Username of the current account</returns>
protected string GetUsername ( )
{
return Handler . GetUsername ( ) ;
}
2022-09-18 00:18:27 +02:00
2020-06-13 18:00:30 +05:00
/// <summary>
/// Return the Gamemode of the current account
/// </summary>
/// <returns>Username of the current account</returns>
protected int GetGamemode ( )
{
return Handler . GetGamemode ( ) ;
}
2021-03-13 22:23:58 +08:00
/// <summary>
/// Return the head yaw of the client player
/// </summary>
/// <returns>Yaw of the client player</returns>
protected float GetYaw ( )
{
return Handler . GetYaw ( ) ;
}
/// <summary>
/// Return the head pitch of the client player
/// </summary>
/// <returns>Pitch of the client player</returns>
protected float GetPitch ( )
{
return Handler . GetPitch ( ) ;
}
2019-09-20 09:26:30 +02:00
/// <summary>
/// Return the UserUUID of the current account
/// </summary>
/// <returns>UserUUID of the current account</returns>
protected string GetUserUUID ( )
{
2022-08-27 02:10:44 +08:00
return Handler . GetUserUuidStr ( ) ;
2019-09-20 09:26:30 +02:00
}
2022-09-12 02:10:18 +08:00
/// <summary>
/// Return the EntityID of the current player
/// </summary>
/// <returns>EntityID of the current player</returns>
protected int GetPlayerEntityID ( )
{
return Handler . GetPlayerEntityID ( ) ;
}
2016-10-14 21:14:26 +02:00
/// <summary>
/// Return the list of currently online players
/// </summary>
/// <returns>List of online players</returns>
protected string [ ] GetOnlinePlayers ( )
{
return Handler . GetOnlinePlayers ( ) ;
}
2019-03-30 10:47:59 -04:00
/// <summary>
/// Get a dictionary of online player names and their corresponding UUID
/// </summary>
/// <returns>
/// dictionary of online player whereby
/// UUID represents the key
/// playername represents the value</returns>
protected Dictionary < string , string > GetOnlinePlayersWithUUID ( )
{
return Handler . GetOnlinePlayersWithUUID ( ) ;
}
2016-02-07 14:24:01 -08:00
/// <summary>
/// Registers the given plugin channel for use by this chatbot.
/// </summary>
/// <param name="channel">The name of the channel to register</param>
protected void RegisterPluginChannel ( string channel )
{
2022-10-02 18:31:08 +08:00
registeredPluginChannels . Add ( channel ) ;
2016-02-07 14:24:01 -08:00
Handler . RegisterPluginChannel ( channel , this ) ;
}
/// <summary>
/// Unregisters the given plugin channel, meaning this chatbot can no longer use it.
/// </summary>
/// <param name="channel">The name of the channel to unregister</param>
protected void UnregisterPluginChannel ( string channel )
{
2022-10-02 18:31:08 +08:00
registeredPluginChannels . RemoveAll ( chan = > chan = = channel ) ;
2016-02-07 14:24:01 -08:00
Handler . UnregisterPluginChannel ( channel , this ) ;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="channel">The channel to send the message on.</param>
/// <param name="data">The data to send.</param>
/// <param name="sendEvenIfNotRegistered">Should the message be sent even if it hasn't been registered by the server or this bot? (Some Minecraft channels aren't registered)</param>
/// <returns>Whether the message was successfully sent. False if there was a network error or if the channel wasn't registered.</returns>
protected bool SendPluginChannelMessage ( string channel , byte [ ] data , bool sendEvenIfNotRegistered = false )
{
if ( ! sendEvenIfNotRegistered )
{
2022-10-02 18:31:08 +08:00
if ( ! registeredPluginChannels . Contains ( channel ) )
2016-02-07 14:24:01 -08:00
{
return false ;
}
}
return Handler . SendPluginChannelMessage ( channel , data , sendEvenIfNotRegistered ) ;
}
2020-03-23 19:59:00 +08:00
2020-04-08 18:23:19 +08:00
/// <summary>
/// Get server current TPS (tick per second)
/// </summary>
/// <returns>tps</returns>
2020-03-23 19:59:00 +08:00
protected Double GetServerTPS ( )
{
return Handler . GetServerTPS ( ) ;
}
/// <summary>
/// Interact with an entity
/// </summary>
/// <param name="EntityID"></param>
/// <param name="type">0: interact, 1: attack, 2: interact at</param>
2020-07-04 13:45:51 +05:00
/// <param name="hand">Hand.MainHand or Hand.OffHand</param>
2020-05-29 23:18:34 +05:00
/// <returns>TRUE in case of success</returns>
2022-08-15 17:31:17 -04:00
[Obsolete("Prefer using InteractType enum instead of int for interaction type")]
2020-07-04 13:45:51 +05:00
protected bool InteractEntity ( int EntityID , int type , Hand hand = Hand . MainHand )
2022-08-15 17:31:17 -04:00
{
return Handler . InteractEntity ( EntityID , ( InteractType ) type , hand ) ;
}
/// <summary>
/// Interact with an entity
/// </summary>
/// <param name="EntityID"></param>
/// <param name="type">Interaction type (InteractType.Interact, Attack or AttackAt)</param>
/// <param name="hand">Hand.MainHand or Hand.OffHand</param>
/// <returns>TRUE in case of success</returns>
protected bool InteractEntity ( int EntityID , InteractType type , Hand hand = Hand . MainHand )
2020-03-23 19:59:00 +08:00
{
2020-07-04 13:45:51 +05:00
return Handler . InteractEntity ( EntityID , type , hand ) ;
2020-03-23 19:59:00 +08:00
}
2020-03-27 21:14:05 +01:00
/// <summary>
2020-05-25 21:39:24 +02:00
/// Give Creative Mode items into regular/survival Player Inventory
2020-05-26 00:16:53 +05:00
/// </summary>
2020-05-25 21:39:24 +02:00
/// <remarks>(obviously) requires to be in creative mode</remarks>
2020-05-29 23:18:34 +05:00
/// </summary>
2020-05-25 21:39:24 +02:00
/// <param name="slot">Destination inventory slot</param>
/// <param name="itemType">Item type</param>
/// <param name="count">Item count</param>
/// <returns>TRUE if item given successfully</returns>
2022-10-02 18:31:08 +08:00
protected bool CreativeGive ( int slot , ItemType itemType , int count , Dictionary < string , object > ? nbt = null )
2020-05-26 00:16:53 +05:00
{
2020-06-20 21:30:23 +02:00
return Handler . DoCreativeGive ( slot , itemType , count , nbt ) ;
2020-05-26 00:16:53 +05:00
}
2021-05-16 11:26:48 +02:00
/// <summary>
/// Use Creative Mode to delete items from the regular/survival Player Inventory
/// </summary>
/// <remarks>(obviously) requires to be in creative mode</remarks>
/// </summary>
/// <param name="slot">Inventory slot to clear</param>
/// <returns>TRUE if item cleared successfully</returns>
protected bool CreativeDelete ( int slot )
{
return CreativeGive ( slot , ItemType . Null , 0 , null ) ;
}
2020-05-26 00:16:53 +05:00
/// <summary>
2020-05-26 11:20:12 +02:00
/// Plays animation (Player arm swing)
2020-05-26 14:02:09 +05:00
/// </summary>
2020-07-04 13:45:51 +05:00
/// <param name="hand">Hand.MainHand or Hand.OffHand</param>
/// <returns>TRUE if animation successfully done</returns>
public bool SendAnimation ( Hand hand = Hand . MainHand )
2020-05-26 14:02:09 +05:00
{
2020-07-04 13:45:51 +05:00
return Handler . DoAnimation ( ( int ) hand ) ;
2020-05-26 14:02:09 +05:00
}
/// <summary>
2020-03-27 21:14:05 +01:00
/// Use item currently in the player's hand (active inventory bar slot)
/// </summary>
2020-05-29 23:18:34 +05:00
/// <returns>TRUE if successful</returns>
2020-05-03 10:48:02 -05:00
protected bool UseItemInHand ( )
2020-03-23 19:59:00 +08:00
{
return Handler . UseItemOnHand ( ) ;
}
2020-03-26 15:01:42 +08:00
2022-09-12 02:19:20 +08:00
/// <summary>
/// Use item currently in the player's hand (active inventory bar slot)
/// </summary>
/// <returns>TRUE if successful</returns>
protected bool UseItemInLeftHand ( )
{
return Handler . UseItemOnLeftHand ( ) ;
}
2020-03-27 21:14:05 +01:00
/// <summary>
2020-05-26 11:20:12 +02:00
/// Check inventory handling enable status
/// </summary>
2020-05-29 23:18:34 +05:00
/// <returns>TRUE if inventory handling is enabled</returns>
2020-05-26 11:20:12 +02:00
public bool GetInventoryEnabled ( )
{
return Handler . GetInventoryEnabled ( ) ;
}
2020-05-29 23:18:34 +05:00
/// <summary>
2020-07-04 13:45:51 +05:00
/// Place the block at hand in the Minecraft world
2020-05-29 23:18:34 +05:00
/// </summary>
2020-07-04 13:45:51 +05:00
/// <param name="location">Location to place block to</param>
/// <param name="blockFace">Block face (e.g. Direction.Down when clicking on the block below to place this block)</param>
/// <param name="hand">Hand.MainHand or Hand.OffHand</param>
/// <returns>TRUE if successfully placed</returns>
public bool SendPlaceBlock ( Location location , Direction blockFace , Hand hand = Hand . MainHand )
2020-05-29 23:18:34 +05:00
{
2020-07-04 13:45:51 +05:00
return Handler . PlaceBlock ( location , blockFace , hand ) ;
2020-05-29 23:18:34 +05:00
}
2020-05-26 11:20:12 +02:00
/// <summary>
/// Get the player's inventory. Do not write to it, will not have any effect server-side.
2020-03-27 21:14:05 +01:00
/// </summary>
/// <returns>Player inventory</returns>
2020-03-26 15:01:42 +08:00
protected Container GetPlayerInventory ( )
{
Container container = Handler . GetPlayerInventory ( ) ;
2022-10-02 18:31:08 +08:00
return new Container ( container . ID , container . Type , container . Title , container . Items ) ;
2020-03-26 15:01:42 +08:00
}
2020-04-08 00:28:03 +08:00
/// <summary>
2020-05-26 11:20:12 +02:00
/// Get all inventories, player and container(s). Do not write to them. Will not have any effect server-side.
2020-04-08 00:28:03 +08:00
/// </summary>
2020-05-26 11:20:12 +02:00
/// <returns>All inventories</returns>
public Dictionary < int , Container > GetInventories ( )
{
return Handler . GetInventories ( ) ;
}
2020-05-29 23:18:34 +05:00
/// <summary>
/// Perform inventory action
/// </summary>
/// <param name="inventoryId">Inventory ID</param>
/// <param name="slot">Slot ID</param>
/// <param name="actionType">Action Type</param>
/// <returns>TRUE in case of success</returns>
protected bool WindowAction ( int inventoryId , int slot , WindowActionType actionType )
{
return Handler . DoWindowAction ( inventoryId , slot , actionType ) ;
}
2020-08-29 23:53:29 +08:00
/// <summary>
/// Get inventory action helper
/// </summary>
/// <param name="container">Inventory Container</param>
/// <returns>ItemMovingHelper instance</returns>
protected ItemMovingHelper GetItemMovingHelper ( Container container )
{
return new ItemMovingHelper ( container , Handler ) ;
}
2020-05-26 11:20:12 +02:00
/// <summary>
/// Change player selected hotbar slot
/// </summary>
/// <param name="slot">0-8</param>
2020-04-08 18:23:19 +08:00
/// <returns>True if success</returns>
protected bool ChangeSlot ( short slot )
2020-04-08 00:28:03 +08:00
{
2020-04-08 18:23:19 +08:00
return Handler . ChangeSlot ( slot ) ;
2020-04-08 00:28:03 +08:00
}
2020-04-11 14:33:22 +08:00
2020-05-26 11:20:12 +02:00
/// <summary>
/// Get current player selected hotbar slot
/// </summary>
/// <returns>0-8</returns>
2020-04-11 14:33:22 +08:00
protected byte GetCurrentSlot ( )
{
return Handler . GetCurrentSlot ( ) ;
}
2022-09-18 00:18:27 +02:00
2020-06-20 17:57:07 +05:00
/// <summary>
/// Clean all inventory
/// </summary>
/// <returns>TRUE if the uccessfully clear</returns>
protected bool ClearInventories ( )
{
return Handler . ClearInventories ( ) ;
}
2022-09-18 00:18:27 +02:00
2020-06-20 17:57:07 +05:00
/// <summary>
/// Update sign text
/// </summary>
/// <param name="location"> sign location</param>
/// <param name="line1"> text one</param>
/// <param name="line2"> text two</param>
/// <param name="line3"> text three</param>
/// <param name="line4"> text1 four</param>
protected bool UpdateSign ( Location location , string line1 , string line2 , string line3 , string line4 )
{
return Handler . UpdateSign ( location , line1 , line2 , line3 , line4 ) ;
}
2020-11-08 23:39:07 +01:00
/// <summary>
/// Selects villager trade
/// </summary>
/// <param name="selectedSlot">Trade slot to select, starts at 0.</param>
protected bool SelectTrade ( int selectedSlot )
{
return Handler . SelectTrade ( selectedSlot ) ;
}
2021-11-17 17:33:52 +01:00
/// <summary>
/// Teleport to player in spectator mode
/// </summary>
/// <param name="entity">player to teleport to</param>
protected bool SpectatorTeleport ( Entity entity )
{
return Handler . Spectate ( entity ) ;
}
/// <summary>
/// Teleport to player/entity in spectator mode
/// </summary>
/// <param name="uuid">uuid of entity to teleport to</param>
protected bool SpectatorTeleport ( Guid UUID )
{
return Handler . SpectateByUUID ( UUID ) ;
}
2022-09-18 00:18:27 +02:00
2020-07-04 13:45:51 +05:00
/// <summary>
/// Update command block
/// </summary>
/// <param name="location">command block location</param>
/// <param name="command">command</param>
/// <param name="mode">command block mode</param>
/// <param name="flags">command block flags</param>
protected bool UpdateCommandBlock ( Location location , string command , CommandBlockMode mode , CommandBlockFlags flags )
{
return Handler . UpdateCommandBlock ( location , command , mode , flags ) ;
}
2020-07-02 13:18:20 +08:00
/// <summary>
2021-03-07 14:21:19 +08:00
/// Register a command in command prompt. Command will be automatically unregistered when unloading ChatBot
2020-07-02 13:18:20 +08:00
/// </summary>
2020-07-04 11:12:23 +02:00
/// <param name="cmdName">Name of the command</param>
/// <param name="cmdDesc">Description/usage of the command</param>
/// <param name="callback">Method for handling the command</param>
2020-07-02 13:18:20 +08:00
/// <returns>True if successfully registered</returns>
2020-10-17 19:41:31 +08:00
protected bool RegisterChatBotCommand ( string cmdName , string cmdDesc , string cmdUsage , CommandRunner callback )
2020-07-02 13:18:20 +08:00
{
2021-03-07 14:21:19 +08:00
bool result = Handler . RegisterCommand ( cmdName , cmdDesc , cmdUsage , callback ) ;
if ( result )
registeredCommands . Add ( cmdName . ToLower ( ) ) ;
return result ;
2020-07-02 13:18:20 +08:00
}
2020-07-09 22:21:39 +08:00
/// <summary>
/// Close a opened inventory
/// </summary>
/// <param name="inventoryID"></param>
/// <returns>True if success</returns>
protected bool CloseInventory ( int inventoryID )
{
return Handler . CloseInventory ( inventoryID ) ;
}
Add Mailer bot (#1108)
* Update for the mail script.
As requested, I added the synchronization between the config debugmessage bool and the one in the script. Furthermore, I added a way to send anonymous mails by writing "tellonym". The messages are saved as normal mails, which lets them count to the mail cap, due to the fact that the host knows the sender.
I added the script to the chat bots because of the problems, that the scripts have with serialization. Instead of rewriting the whole serialization part, my idea was to add the script to the other chat bots, to avoid the compiling issues. Then the serialization would work perfectly fine. Then you could remove the option class at some point and move all the settings to the config file with the addition to activate the whole script.
* Correction of debug message loading.
The object was missing and the change would be overridden a few lines later.
* Update McClient.cs
* Add Mail to config file
* Correcting the safe file.
* Small correction of Settings.c
* Update Mailscript
Added a failsafe version of the path changing commands. If a path could not be found, an error will be created and the path will be reseted to standart, to avoid endless chains of errors.
* Fix for the mail script
Removed a wrong option call. Removed the debug_msg condition around the path functions. => Users are aware of what happened (if they see the error) although they turned off debug_msg.
* Added some features.
Added a try statement to all number changing commands. Added a command to list all moderators to the console.
* Serialization Fix
There was a chance, that if two bots work on one file, and two users send messages in a short time period, that one bot deserializes the message and then the other bot deserialize the same file, before the other one could save its changes. This would lead to one message disappearing, because one bot never deserialized this message. For this I changed the whole serialization process.
All changes are now committed after the interval and not after an incoming mail command directly. All mails are safed temporarily in cache and get serialized after the interval. Due to this changes, you can determit when the individual bot changes the file (there are no more direct interactions with the file after a command, which lead to a certain randomness). Furthermore you can now set an interval of e.g. 2 mins and reset the interval of one bot with "resettimer" after one minute so that the bots won't disturb eachother and no files get lost.
* My idea of a manual.
This is my idea of a manual for the bot. Improvements of my language / further ideas are welcome! :D
* addIgnored [NAME] and removeIgnored[NAME]
Added an ignored list. Moderators can add players to the list. The bot won't react to them and just log to the console that they are ignored, everytime they are sending a message, to ensure that they are not accidently ignored. (Just if debug_msg is active.)
Especially useful if there are other chat bots on the server, which spam many messages that aren't useful for the mail system. Or block spammers etc.
* Add the three commands to the manual.
Added addignored, removeignored and getignored to the manual.
* Remove moderators. Implement Console Control.
Due to security concerns, I converted all moderator commands to console internal commands. Thereby only the host can change crucial settings. Special thanks to ORelio for the hint!
* Added empty statement check
Added if to all commands, where the syntax is not already protected by a try, so that an incorrect syntax (Empty args[] due to missing statement) won't crash the script.
* Changed the serialization fail
If the programm can't safe the file, because of some strange character for instance, it first tries to change the path back to normal and if this not helps, it creates a new, file.
* toggle mail sending/receiving
Add an option to turn mailsending and the listening to commands in chat on/off.
* Updated manual.
- Removed moderator commands.
- Removed moderator part in the network manual
+ added the two new commands
+ added a waring for nick plugins and minecraft renames
+ added a small syntax example
* Updated the Settings.cs file.
* Smaller fixes and additions
+ improved command reading of 'mail' & 'tellonym'
+ sorted internal commands alphabetically
+ host can set a maximum message length
+ host can accept commands from public chat
+ host can decide if 'self mailing' (mailing yourself) is accepted
+ new order makes 'getsettings' easier to read
+ new internal commands to toggle 'publiccommands' and 'selfmailing' as well as the maximum mail size
- removed the old command interpreter
* Small improvements and additions
Added a few commands and settings
* Completing getsettings
+ added 'publiccomands'
* Completed getsettings
+ Added 'publiccommand' to 'getsettings'
* Removed single bolean, added Dictionary
- removed all boleans in the option class
- removed all functions relating them
+ added Dictionary for the booleans
+ added a single function to set/toggle all booleans
* Removed Commands, added interpreter
- Removed all Register commands
- removed all integer methods
+ added a single mail command
+ added integer dictionary
+ added integer handling similar like bool handling
* Small fix
+ Changed the numbers in several methods to adjust them to the new syntax.
- removed parameters in several methods, because they got unneccesary
* Even smaller fix
+ Sorted 'getsettings' alphabetically
+ corrected a typo
* New Serialization method.
Now serializing through the .INI format! Thanks to ORelio, who helped me a lot! :)
* Added different time
Added the option to switch between utc and the time of the local machine for timestamps.
* Made timeinutc serializable
Added the bool to the serialization method.
* Adding the INIFile.cs
For Dictionary serialization.
* Reworked ignore feature
Ignored players are now serialized in a file and reloaded, after the bot enters a server.
* Mailer bot refactoring
Rename Mail to Mailer
Move options to MinecraftClient.ini
Make the bot much simpler by removing some settings
Create specific MailDatabase and IgnoreList classes
However the core functionality for users is the same
Settings removed:
- allow_sendmail: Cannot use Mailer if it's disabled
- allow_receivemail: Cannot use Mailer if it's disabled
- path_setting: Settings moved to MinecraftClient.ini
- debug_msg: MCC already has a setting for that with LogDebugToConsole()
- auto_respawn: MCC already has a built-in auto-respawn feature
- allow_selfmail: Is it really necessary to block self mails? ;)
- maxcharsinmsg: Automatically calculated based on max chat message length
- timeinutc: DateTime is not show to the recipient so I think it's not absolutely necessary
- interval_sendmail: Set to 10 seconds for now
Internal Commands removed:
- changemailpath: Now a static setting in config
- changesettingspath: Now a static setting in config
- updatemails: Already updated every 10 seconds
- getsettings: Shown on startup with debugmessages=true
- resettimer: Seems only useful for debugging
- setbool: Settings are static in config file
- setinteger: Settings are static in config file
All user commands are retained:
- mail
- tellonym
* Reload database for mailer network feature
* Merge Mail documentation to Readme.md
Co-authored-by: ORelio <oreliogitantispam.l0gin@spamgourmet.com>
2020-08-03 21:44:39 +02:00
/// <summary>
/// Get max length for chat messages
/// </summary>
/// <returns>Max length, in characters</returns>
protected int GetMaxChatMessageLength ( )
{
return Handler . GetMaxChatMessageLength ( ) ;
}
2022-09-18 00:18:27 +02:00
2020-08-22 14:17:31 +05:00
/// <summary>
/// Respawn player
/// </summary>
protected bool Respawn ( )
{
if ( Handler . GetHealth ( ) < = 0 )
return Handler . SendRespawnPacket ( ) ;
else return false ;
}
Add Mailer bot (#1108)
* Update for the mail script.
As requested, I added the synchronization between the config debugmessage bool and the one in the script. Furthermore, I added a way to send anonymous mails by writing "tellonym". The messages are saved as normal mails, which lets them count to the mail cap, due to the fact that the host knows the sender.
I added the script to the chat bots because of the problems, that the scripts have with serialization. Instead of rewriting the whole serialization part, my idea was to add the script to the other chat bots, to avoid the compiling issues. Then the serialization would work perfectly fine. Then you could remove the option class at some point and move all the settings to the config file with the addition to activate the whole script.
* Correction of debug message loading.
The object was missing and the change would be overridden a few lines later.
* Update McClient.cs
* Add Mail to config file
* Correcting the safe file.
* Small correction of Settings.c
* Update Mailscript
Added a failsafe version of the path changing commands. If a path could not be found, an error will be created and the path will be reseted to standart, to avoid endless chains of errors.
* Fix for the mail script
Removed a wrong option call. Removed the debug_msg condition around the path functions. => Users are aware of what happened (if they see the error) although they turned off debug_msg.
* Added some features.
Added a try statement to all number changing commands. Added a command to list all moderators to the console.
* Serialization Fix
There was a chance, that if two bots work on one file, and two users send messages in a short time period, that one bot deserializes the message and then the other bot deserialize the same file, before the other one could save its changes. This would lead to one message disappearing, because one bot never deserialized this message. For this I changed the whole serialization process.
All changes are now committed after the interval and not after an incoming mail command directly. All mails are safed temporarily in cache and get serialized after the interval. Due to this changes, you can determit when the individual bot changes the file (there are no more direct interactions with the file after a command, which lead to a certain randomness). Furthermore you can now set an interval of e.g. 2 mins and reset the interval of one bot with "resettimer" after one minute so that the bots won't disturb eachother and no files get lost.
* My idea of a manual.
This is my idea of a manual for the bot. Improvements of my language / further ideas are welcome! :D
* addIgnored [NAME] and removeIgnored[NAME]
Added an ignored list. Moderators can add players to the list. The bot won't react to them and just log to the console that they are ignored, everytime they are sending a message, to ensure that they are not accidently ignored. (Just if debug_msg is active.)
Especially useful if there are other chat bots on the server, which spam many messages that aren't useful for the mail system. Or block spammers etc.
* Add the three commands to the manual.
Added addignored, removeignored and getignored to the manual.
* Remove moderators. Implement Console Control.
Due to security concerns, I converted all moderator commands to console internal commands. Thereby only the host can change crucial settings. Special thanks to ORelio for the hint!
* Added empty statement check
Added if to all commands, where the syntax is not already protected by a try, so that an incorrect syntax (Empty args[] due to missing statement) won't crash the script.
* Changed the serialization fail
If the programm can't safe the file, because of some strange character for instance, it first tries to change the path back to normal and if this not helps, it creates a new, file.
* toggle mail sending/receiving
Add an option to turn mailsending and the listening to commands in chat on/off.
* Updated manual.
- Removed moderator commands.
- Removed moderator part in the network manual
+ added the two new commands
+ added a waring for nick plugins and minecraft renames
+ added a small syntax example
* Updated the Settings.cs file.
* Smaller fixes and additions
+ improved command reading of 'mail' & 'tellonym'
+ sorted internal commands alphabetically
+ host can set a maximum message length
+ host can accept commands from public chat
+ host can decide if 'self mailing' (mailing yourself) is accepted
+ new order makes 'getsettings' easier to read
+ new internal commands to toggle 'publiccommands' and 'selfmailing' as well as the maximum mail size
- removed the old command interpreter
* Small improvements and additions
Added a few commands and settings
* Completing getsettings
+ added 'publiccomands'
* Completed getsettings
+ Added 'publiccommand' to 'getsettings'
* Removed single bolean, added Dictionary
- removed all boleans in the option class
- removed all functions relating them
+ added Dictionary for the booleans
+ added a single function to set/toggle all booleans
* Removed Commands, added interpreter
- Removed all Register commands
- removed all integer methods
+ added a single mail command
+ added integer dictionary
+ added integer handling similar like bool handling
* Small fix
+ Changed the numbers in several methods to adjust them to the new syntax.
- removed parameters in several methods, because they got unneccesary
* Even smaller fix
+ Sorted 'getsettings' alphabetically
+ corrected a typo
* New Serialization method.
Now serializing through the .INI format! Thanks to ORelio, who helped me a lot! :)
* Added different time
Added the option to switch between utc and the time of the local machine for timestamps.
* Made timeinutc serializable
Added the bool to the serialization method.
* Adding the INIFile.cs
For Dictionary serialization.
* Reworked ignore feature
Ignored players are now serialized in a file and reloaded, after the bot enters a server.
* Mailer bot refactoring
Rename Mail to Mailer
Move options to MinecraftClient.ini
Make the bot much simpler by removing some settings
Create specific MailDatabase and IgnoreList classes
However the core functionality for users is the same
Settings removed:
- allow_sendmail: Cannot use Mailer if it's disabled
- allow_receivemail: Cannot use Mailer if it's disabled
- path_setting: Settings moved to MinecraftClient.ini
- debug_msg: MCC already has a setting for that with LogDebugToConsole()
- auto_respawn: MCC already has a built-in auto-respawn feature
- allow_selfmail: Is it really necessary to block self mails? ;)
- maxcharsinmsg: Automatically calculated based on max chat message length
- timeinutc: DateTime is not show to the recipient so I think it's not absolutely necessary
- interval_sendmail: Set to 10 seconds for now
Internal Commands removed:
- changemailpath: Now a static setting in config
- changesettingspath: Now a static setting in config
- updatemails: Already updated every 10 seconds
- getsettings: Shown on startup with debugmessages=true
- resettimer: Seems only useful for debugging
- setbool: Settings are static in config file
- setinteger: Settings are static in config file
All user commands are retained:
- mail
- tellonym
* Reload database for mailer network feature
* Merge Mail documentation to Readme.md
Co-authored-by: ORelio <oreliogitantispam.l0gin@spamgourmet.com>
2020-08-03 21:44:39 +02:00
2020-09-07 03:51:42 +08:00
/// <summary>
/// Enable or disable network packet event calling. If you want to capture every packet including login phase, please enable this in <see cref="Initialize()"/>
/// </summary>
/// <remarks>
/// Enable this may increase memory usage.
/// </remarks>
/// <param name="enabled"></param>
protected void SetNetworkPacketEventEnabled ( bool enabled )
{
Handler . SetNetworkPacketCaptureEnabled ( enabled ) ;
}
/// <summary>
/// Get the minecraft protcol number currently in use
/// </summary>
/// <returns>Protcol number</returns>
protected int GetProtocolVersion ( )
{
return Handler . GetProtocolVersion ( ) ;
}
2021-05-08 21:03:23 +08:00
/// <summary>
2021-05-15 17:36:16 +02:00
/// Invoke a task on the main thread, wait for completion and retrieve return value.
/// </summary>
/// <param name="task">Task to run with any type or return value</param>
/// <returns>Any result returned from task, result type is inferred from the task</returns>
/// <example>bool result = InvokeOnMainThread(methodThatReturnsAbool);</example>
/// <example>bool result = InvokeOnMainThread(() => methodThatReturnsAbool(argument));</example>
/// <example>int result = InvokeOnMainThread(() => { yourCode(); return 42; });</example>
/// <typeparam name="T">Type of the return value</typeparam>
protected T InvokeOnMainThread < T > ( Func < T > task )
{
return Handler . InvokeOnMainThread ( task ) ;
}
/// <summary>
/// Invoke a task on the main thread and wait for completion
/// </summary>
/// <param name="task">Task to run without return value</param>
/// <example>InvokeOnMainThread(methodThatReturnsNothing);</example>
/// <example>InvokeOnMainThread(() => methodThatReturnsNothing(argument));</example>
/// <example>InvokeOnMainThread(() => { yourCode(); });</example>
protected void InvokeOnMainThread ( Action task )
{
Handler . InvokeOnMainThread ( task ) ;
}
/// <summary>
/// Schedule a task to run on the main thread, and do not wait for completion
2021-05-08 21:03:23 +08:00
/// </summary>
/// <param name="task">Task to run</param>
/// <param name="delayTicks">Run the task after X ticks (1 tick delay = ~100ms). 0 for no delay</param>
/// <example>
2021-05-15 17:36:16 +02:00
/// <example>InvokeOnMainThread(methodThatReturnsNothing, 10);</example>
/// <example>InvokeOnMainThread(() => methodThatReturnsNothing(argument), 10);</example>
/// <example>InvokeOnMainThread(() => { yourCode(); }, 10);</example>
2021-05-08 21:03:23 +08:00
/// </example>
2021-05-15 17:36:16 +02:00
protected void ScheduleOnMainThread ( Action task , int delayTicks = 0 )
2021-05-08 21:03:23 +08:00
{
2021-05-15 17:36:16 +02:00
lock ( delayTasksLock )
2021-05-08 21:03:23 +08:00
{
2021-05-15 17:36:16 +02:00
delayedTasks . Add ( new TaskWithDelay ( task , delayTicks ) ) ;
2021-05-12 12:20:13 +08:00
}
2021-05-15 17:36:16 +02:00
}
2021-05-08 21:03:23 +08:00
2021-05-12 12:20:13 +08:00
/// <summary>
2021-05-15 17:36:16 +02:00
/// Schedule a task to run on the main thread, and do not wait for completion
2021-05-12 12:20:13 +08:00
/// </summary>
/// <param name="task">Task to run</param>
2021-05-15 17:36:16 +02:00
/// <param name="delay">Run the task after the specified delay</param>
protected void ScheduleOnMainThread ( Action task , TimeSpan delay )
2021-05-12 12:20:13 +08:00
{
2021-05-15 17:36:16 +02:00
lock ( delayTasksLock )
{
delayedTasks . Add ( new TaskWithDelay ( task , delay ) ) ;
}
}
2021-05-12 12:20:13 +08:00
2020-07-04 13:45:51 +05:00
/// <summary>
/// Command runner definition.
/// Returned string will be the output of the command
/// </summary>
/// <param name="command">Full command</param>
/// <param name="args">Arguments in the command</param>
2020-07-04 11:12:23 +02:00
/// <returns>Command result to display to the user</returns>
2020-07-04 13:45:51 +05:00
public delegate string CommandRunner ( string command , string [ ] args ) ;
2020-07-02 13:18:20 +08:00
/// <summary>
2020-07-04 13:45:51 +05:00
/// Command class with constructor for creating command for ChatBots.
2020-07-02 13:18:20 +08:00
/// </summary>
2020-07-04 13:45:51 +05:00
public class ChatBotCommand : Command
2020-07-02 13:18:20 +08:00
{
2020-07-04 13:45:51 +05:00
public CommandRunner Runner ;
2020-07-04 11:12:23 +02:00
private readonly string _cmdName ;
private readonly string _cmdDesc ;
2020-10-17 19:41:31 +08:00
private readonly string _cmdUsage ;
2020-07-04 11:12:23 +02:00
2020-10-17 19:41:31 +08:00
public override string CmdName { get { return _cmdName ; } }
public override string CmdUsage { get { return _cmdUsage ; } }
public override string CmdDesc { get { return _cmdDesc ; } }
2020-07-04 11:12:23 +02:00
2022-10-02 18:31:08 +08:00
public override string Run ( McClient handler , string command , Dictionary < string , object > ? localVars )
2020-07-04 13:45:51 +05:00
{
2022-10-02 18:31:08 +08:00
return Runner ( command , GetArgs ( command ) ) ;
2020-07-04 13:45:51 +05:00
}
/// <summary>
2020-07-04 11:12:23 +02:00
/// ChatBotCommand Constructor
2020-07-04 13:45:51 +05:00
/// </summary>
2020-10-17 19:41:31 +08:00
/// <param name="cmdName">Name of the command</param>
/// <param name="cmdDesc">Description of the command. Support tranlation.</param>
/// <param name="cmdUsage">Usage of the command</param>
/// <param name="callback">Method for handling the command</param>
public ChatBotCommand ( string cmdName , string cmdDesc , string cmdUsage , CommandRunner callback )
2020-07-04 13:45:51 +05:00
{
2022-10-02 18:31:08 +08:00
_cmdName = cmdName ;
_cmdDesc = cmdDesc ;
_cmdUsage = cmdUsage ;
Runner = callback ;
2020-07-04 13:45:51 +05:00
}
2020-07-02 13:18:20 +08:00
}
2014-05-31 01:59:03 +02:00
}
}