Added command for reloading settings, chat bots, listing chat bots and unloading a chat bot manually by name.

This commit is contained in:
Milutinke 2022-09-25 16:00:43 +02:00
parent ef79ca1fe8
commit 9b407dbdad
7 changed files with 198 additions and 46 deletions

View file

@ -54,29 +54,6 @@ namespace MinecraftClient.ChatBots
LogToConsoleTranslated("bot.autoFish.no_inv_handle"); LogToConsoleTranslated("bot.autoFish.no_inv_handle");
} }
/// <summary>
/// Update settings when reloaded
/// </summary>
public /* override */ void OnSettingsReload()
{
if (Settings.AutoFishing_Enabled)
{
if (!GetEntityHandlingEnabled())
{
LogToConsoleTranslated("extra.entity_required");
state = FishingState.WaitJoinGame;
}
inventoryEnabled = GetInventoryEnabled();
if (!inventoryEnabled)
LogToConsoleTranslated("bot.autoFish.no_inv_handle");
}
else
{
UnloadBot();
return;
}
}
private void StartFishing() private void StartFishing()
{ {
isFishing = false; isFishing = false;
@ -262,7 +239,7 @@ namespace MinecraftClient.ChatBots
if (Settings.AutoFishing_LogFishingBobber) if (Settings.AutoFishing_LogFishingBobber)
LogToConsole(string.Format("FishingBobber {0} Dx={1:0.000000} Dy={2:0.000000} Dz={3:0.000000}", Pos, Dx, Math.Abs(Dy), Dz)); LogToConsole(string.Format("FishingBobber {0} Dx={1:0.000000} Dy={2:0.000000} Dz={3:0.000000}", Pos, Dx, Math.Abs(Dy), Dz));
if (Math.Abs(Dx) < Math.Abs(Settings.AutoFishing_StationaryThreshold) && if (Math.Abs(Dx) < Math.Abs(Settings.AutoFishing_StationaryThreshold) &&
Math.Abs(Dz) < Math.Abs(Settings.AutoFishing_StationaryThreshold) && Math.Abs(Dz) < Math.Abs(Settings.AutoFishing_StationaryThreshold) &&
Math.Abs(Dy) > Math.Abs(Settings.AutoFishing_HookThreshold)) Math.Abs(Dy) > Math.Abs(Settings.AutoFishing_HookThreshold))
{ {

View file

@ -0,0 +1,76 @@
using MinecraftClient.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands
{
class BotsCommand : Command
{
public override string CmdName { get { return "bots"; } }
public override string CmdUsage { get { return "bots [list|unload <bot name|all>]"; } }
public override string CmdDesc { get { return "cmd.bots.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars)
{
if (hasArg(command))
{
string[] args = getArgs(command);
if (args.Length == 1)
{
if (args[0].Equals("list", StringComparison.OrdinalIgnoreCase))
{
StringBuilder sb = new();
int length = handler.GetLoadedChatBots().Count;
if (length == 0)
return Translations.TryGet("cmd.bots.noloaded");
for (int i = 0; i < length; i++)
{
sb.Append(handler.GetLoadedChatBots()[i].GetType().Name);
if (i != length - 1)
sb.Append(" ,");
}
return Translations.Get("cmd.bots.list") + ": " + sb.ToString();
}
}
else if (args.Length == 2)
{
if (args[0].Equals("unload", StringComparison.OrdinalIgnoreCase))
{
string botName = args[1].Trim();
if (botName.ToLower().Equals("all", StringComparison.OrdinalIgnoreCase))
{
if (handler.GetLoadedChatBots().Count == 0)
return Translations.TryGet("cmd.bots.noloaded");
handler.UnloadAllBots();
return Translations.TryGet("cmd.bots.unloaded_all");
}
else
{
ChatBot? bot = handler.GetLoadedChatBots().Find(bot => bot.GetType().Name.ToLower() == botName.ToLower());
if (bot == null)
return Translations.TryGet("cmd.bots.notfound", botName);
handler.BotUnLoad(bot);
return Translations.TryGet("cmd.bots.unloaded", botName);
}
}
}
}
return GetCmdDescTranslated();
}
}
}

View file

@ -0,0 +1,27 @@
using MinecraftClient.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands
{
class Reload : Command
{
public override string CmdName { get { return "reload"; } }
public override string CmdUsage { get { return "reload"; } }
public override string CmdDesc { get { return "cmd.reload.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars)
{
handler.Log.Info(Translations.TryGet("cmd.reload.started"));
handler.ReloadSettings();
handler.Log.Warn(Translations.TryGet("cmd.reload.warning1"));
handler.Log.Warn(Translations.TryGet("cmd.reload.warning2"));
handler.Log.Warn(Translations.TryGet("cmd.reload.warning3"));
handler.Log.Warn(Translations.TryGet("cmd.reload.warning4"));
return Translations.TryGet("cmd.reload.finished");
}
}
}

View file

@ -178,28 +178,7 @@ namespace MinecraftClient
LoadCommands(); LoadCommands();
if (botsOnHold.Count == 0) if (botsOnHold.Count == 0)
{ RegisterBots();
if (Settings.AntiAFK_Enabled) { BotLoad(new ChatBots.AntiAFK(Settings.AntiAFK_Delay)); }
if (Settings.Hangman_Enabled) { BotLoad(new ChatBots.HangmanGame(Settings.Hangman_English)); }
if (Settings.Alerts_Enabled) { BotLoad(new ChatBots.Alerts()); }
if (Settings.ChatLog_Enabled) { BotLoad(new ChatBots.ChatLog(Settings.ExpandVars(Settings.ChatLog_File), Settings.ChatLog_Filter, Settings.ChatLog_DateTime)); }
if (Settings.PlayerLog_Enabled) { BotLoad(new ChatBots.PlayerListLogger(Settings.PlayerLog_Delay, Settings.ExpandVars(Settings.PlayerLog_File))); }
if (Settings.AutoRelog_Enabled) { BotLoad(new ChatBots.AutoRelog(Settings.AutoRelog_Delay_Min, Settings.AutoRelog_Delay_Max, Settings.AutoRelog_Retries)); }
if (Settings.ScriptScheduler_Enabled) { BotLoad(new ChatBots.ScriptScheduler(Settings.ExpandVars(Settings.ScriptScheduler_TasksFile))); }
if (Settings.RemoteCtrl_Enabled) { BotLoad(new ChatBots.RemoteControl()); }
if (Settings.AutoRespond_Enabled) { BotLoad(new ChatBots.AutoRespond(Settings.AutoRespond_Matches, Settings.AutoRespond_MatchColors)); }
if (Settings.AutoAttack_Enabled) { BotLoad(new ChatBots.AutoAttack(Settings.AutoAttack_Mode, Settings.AutoAttack_Priority, Settings.AutoAttack_OverrideAttackSpeed, Settings.AutoAttack_CooldownSeconds, Settings.AutoAttack_Interaction)); }
if (Settings.AutoFishing_Enabled) { BotLoad(new ChatBots.AutoFishing()); }
if (Settings.AutoEat_Enabled) { BotLoad(new ChatBots.AutoEat(Settings.AutoEat_hungerThreshold)); }
if (Settings.Mailer_Enabled) { BotLoad(new ChatBots.Mailer()); }
if (Settings.AutoCraft_Enabled) { BotLoad(new AutoCraft(Settings.AutoCraft_configFile)); }
if (Settings.AutoDrop_Enabled) { BotLoad(new AutoDrop(Settings.AutoDrop_Mode, Settings.AutoDrop_items)); }
if (Settings.ReplayMod_Enabled) { BotLoad(new ReplayCapture(Settings.ReplayMod_BackupInterval)); }
if (Settings.FollowPlayer_Enabled) { BotLoad(new FollowPlayer(Settings.FollowPlayer_UpdateLimit, Settings.FollowPlayer_UpdateLimit)); }
//Add your ChatBot here by uncommenting and adapting
//BotLoad(new ChatBots.YourBot());
}
} }
try try
@ -287,6 +266,32 @@ namespace MinecraftClient
} }
} }
/// <summary>
/// Register bots
/// </summary>
private void RegisterBots(bool reload = false)
{
if (Settings.AntiAFK_Enabled) { BotLoad(new AntiAFK(Settings.AntiAFK_Delay)); }
if (Settings.Hangman_Enabled) { BotLoad(new HangmanGame(Settings.Hangman_English)); }
if (Settings.Alerts_Enabled) { BotLoad(new Alerts()); }
if (Settings.ChatLog_Enabled) { BotLoad(new ChatLog(Settings.ExpandVars(Settings.ChatLog_File), Settings.ChatLog_Filter, Settings.ChatLog_DateTime)); }
if (Settings.PlayerLog_Enabled) { BotLoad(new PlayerListLogger(Settings.PlayerLog_Delay, Settings.ExpandVars(Settings.PlayerLog_File))); }
if (Settings.AutoRelog_Enabled) { BotLoad(new AutoRelog(Settings.AutoRelog_Delay_Min, Settings.AutoRelog_Delay_Max, Settings.AutoRelog_Retries)); }
if (Settings.ScriptScheduler_Enabled) { BotLoad(new ScriptScheduler(Settings.ExpandVars(Settings.ScriptScheduler_TasksFile))); }
if (Settings.RemoteCtrl_Enabled) { BotLoad(new RemoteControl()); }
if (Settings.AutoRespond_Enabled) { BotLoad(new AutoRespond(Settings.AutoRespond_Matches, Settings.AutoRespond_MatchColors)); }
if (Settings.AutoAttack_Enabled) { BotLoad(new AutoAttack(Settings.AutoAttack_Mode, Settings.AutoAttack_Priority, Settings.AutoAttack_OverrideAttackSpeed, Settings.AutoAttack_CooldownSeconds, Settings.AutoAttack_Interaction)); }
if (Settings.AutoFishing_Enabled) { BotLoad(new AutoFishing()); }
if (Settings.AutoEat_Enabled) { BotLoad(new AutoEat(Settings.AutoEat_hungerThreshold)); }
if (Settings.Mailer_Enabled) { BotLoad(new Mailer()); }
if (Settings.AutoCraft_Enabled) { BotLoad(new AutoCraft(Settings.AutoCraft_configFile)); }
if (Settings.AutoDrop_Enabled) { BotLoad(new AutoDrop(Settings.AutoDrop_Mode, Settings.AutoDrop_items)); }
if (Settings.ReplayMod_Enabled && reload) { BotLoad(new ReplayCapture(Settings.ReplayMod_BackupInterval)); }
//Add your ChatBot here by uncommenting and adapting
//BotLoad(new ChatBots.YourBot());
}
/// <summary> /// <summary>
/// Retrieve messages from the queue and send. /// Retrieve messages from the queue and send.
/// Note: requires external locking. /// Note: requires external locking.
@ -714,6 +719,37 @@ namespace MinecraftClient
} }
} }
/// <summary>
/// Reload settings and bots
/// </summary>
/// <param name="hard">Marks if bots need to be hard reloaded</param>
public void ReloadSettings()
{
Program.ReloadSettings();
ReloadBots();
}
/// <summary>
/// Reload loaded bots (Only builtin bots)
/// </summary>
public void ReloadBots()
{
UnloadAllBots();
RegisterBots(true);
if (client.Client.Connected)
bots.ForEach(bot => bot.AfterGameJoined());
}
/// <summary>
/// Unload All Bots
/// </summary>
public void UnloadAllBots()
{
foreach (ChatBot bot in GetLoadedChatBots())
BotUnLoad(bot);
}
#endregion #endregion
#region Thread-Invoke: Cross-thread method calls #region Thread-Invoke: Cross-thread method calls
@ -823,6 +859,7 @@ namespace MinecraftClient
return; return;
} }
b.OnUnload();
bots.RemoveAll(item => object.ReferenceEquals(item, b)); bots.RemoveAll(item => object.ReferenceEquals(item, b));
// ToList is needed to avoid an InvalidOperationException from modfiying the list while it's being iterated upon. // ToList is needed to avoid an InvalidOperationException from modfiying the list while it's being iterated upon.

View file

@ -46,6 +46,7 @@ namespace MinecraftClient
private static Tuple<Thread, CancellationTokenSource>? offlinePrompt = null; private static Tuple<Thread, CancellationTokenSource>? offlinePrompt = null;
private static bool useMcVersionOnce = false; private static bool useMcVersionOnce = false;
private static string? settingsIniPath = null;
/// <summary> /// <summary>
/// The main entry point of Minecraft Console Client /// The main entry point of Minecraft Console Client
@ -104,10 +105,13 @@ namespace MinecraftClient
ConsoleIO.DebugReadInput(); ConsoleIO.DebugReadInput();
} }
settingsIniPath = "MinecraftClient.ini";
//Process ini configuration file //Process ini configuration file
if (args.Length >= 1 && System.IO.File.Exists(args[0]) && Settings.ToLowerIfNeed(Path.GetExtension(args[0])) == ".ini") if (args.Length >= 1 && System.IO.File.Exists(args[0]) && Settings.ToLowerIfNeed(Path.GetExtension(args[0])) == ".ini")
{ {
Settings.LoadFile(args[0]); Settings.LoadFile(args[0]);
settingsIniPath = args[0];
//remove ini configuration file from arguments array //remove ini configuration file from arguments array
List<string> args_tmp = args.ToList<string>(); List<string> args_tmp = args.ToList<string>();
@ -529,6 +533,15 @@ namespace MinecraftClient
} }
} }
/// <summary>
/// Reloads settings
/// </summary>
public static void ReloadSettings()
{
if (settingsIniPath != null)
Settings.LoadFile(settingsIniPath);
}
/// <summary> /// <summary>
/// Disconnect the current client from the server and restart it /// Disconnect the current client from the server and restart it
/// </summary> /// </summary>

View file

@ -223,6 +223,14 @@ general.available_cmd=Available commands: {0}
# Animation # Animation
cmd.animation.desc=Swing your arm. cmd.animation.desc=Swing your arm.
# Bots
cmd.bots.desc=List bots, unload a bot or all bots.
cmd.bots.list=Loaded bots
cmd.bots.notfound=Bot {0} is not loaded, check if you have made a typo!
cmd.bots.noloaded=No bots loaded!
cmd.bots.unloaded=Successfully unloaded bot: {0}
cmd.bots.unloaded_all=Successfully unloaded all bots!
# ChangeSlot # ChangeSlot
cmd.changeSlot.desc=Change slot in hotbar cmd.changeSlot.desc=Change slot in hotbar
cmd.changeSlot.nan=Could not change slot: Not a Number cmd.changeSlot.nan=Could not change slot: Not a Number
@ -365,6 +373,15 @@ cmd.move.chunk_not_loaded=The chunk where the target location resides has not ye
# Reco # Reco
cmd.reco.desc=restart and reconnect to the server. cmd.reco.desc=restart and reconnect to the server.
# Reload
cmd.reload.started=Reloading settings...
cmd.reload.warning1=This command will NOT affect certain settings which are used before connecting to a server!
cmd.reload.warning2=Some settings passed through the command line parameters might get overriden!
cmd.reload.warning3=You also might need to reconnect for some settings to take effect.
cmd.reload.warning4=Replay Chat Bot will not be hard reloaded due to technical limitations!
cmd.reload.finished=Reloaded Settings!
cmd.reload.desc=Reloads MCC settings.
# Respawn # Respawn
cmd.respawn.desc=Use this to respawn if you are dead. cmd.respawn.desc=Use this to respawn if you are dead.
cmd.respawn.done=You have respawned. cmd.respawn.done=You have respawned.

View file

@ -101,6 +101,11 @@ namespace MinecraftClient
/// </summary> /// </summary>
public virtual void Initialize() { } public virtual void Initialize() { }
/// <summary>
/// This method is called when the bot is being unloaded, you can use it to free up resources like DB connections
/// </summary>
public virtual void OnUnload() { }
/// <summary> /// <summary>
/// Called after the server has been joined successfully and chat messages are able to be sent. /// 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. /// This method is called again after reconnecting to the server, whereas Initialize() is called only once.