Reload Settings and Chat Bots, Fixed PlayerListLogger Chat Bot, Added %datetime%

Reload Settings and Chat Bots, Fixed PlayerListLogger Chat Bot, Added %datetime%
This commit is contained in:
Anon 2022-09-25 20:33:54 +00:00 committed by GitHub
commit 94a7ef2c2c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 246 additions and 58 deletions

View file

@ -54,29 +54,6 @@ namespace MinecraftClient.ChatBots
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()
{
isFishing = false;
@ -262,7 +239,7 @@ namespace MinecraftClient.ChatBots
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));
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(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

@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static System.Net.Mime.MediaTypeNames;
namespace MinecraftClient.ChatBots
{
@ -34,19 +35,26 @@ namespace MinecraftClient.ChatBots
count++;
if (count == timeping)
{
SendText("/list");
count = 0;
}
}
string[] playerList = GetOnlinePlayers();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < playerList.Length; i++)
{
sb.Append(playerList[i]);
// Do not add a comma after the last username
if (i != playerList.Length - 1)
sb.Append(", ");
}
LogDebugToConsole("Saving Player List");
public override void GetText(string text)
{
if (text.Contains("Joueurs en ligne") || text.Contains("Connected:") || text.Contains("online:"))
{
LogToConsole("Saving Player List");
DateTime now = DateTime.Now;
string TimeStamp = "[" + now.Year + '/' + now.Month + '/' + now.Day + ' ' + now.Hour + ':' + now.Minute + ']';
System.IO.File.AppendAllText(file, TimeStamp + "\n" + GetVerbatim(text) + "\n\n");
System.IO.File.AppendAllText(file, TimeStamp + "\n" + sb.ToString() + "\n\n");
count = 0;
}
}
}

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();
if (botsOnHold.Count == 0)
{
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());
}
RegisterBots();
}
try
@ -287,6 +266,33 @@ 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)); }
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());
}
/// <summary>
/// Retrieve messages from the queue and send.
/// Note: requires external locking.
@ -714,6 +720,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
#region Thread-Invoke: Cross-thread method calls
@ -823,6 +860,7 @@ namespace MinecraftClient
return;
}
b.OnUnload();
bots.RemoveAll(item => object.ReferenceEquals(item, b));
// 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 bool useMcVersionOnce = false;
private static string? settingsIniPath = null;
/// <summary>
/// The main entry point of Minecraft Console Client
@ -104,10 +105,13 @@ namespace MinecraftClient
ConsoleIO.DebugReadInput();
}
settingsIniPath = "MinecraftClient.ini";
//Process ini configuration file
if (args.Length >= 1 && System.IO.File.Exists(args[0]) && Settings.ToLowerIfNeed(Path.GetExtension(args[0])) == ".ini")
{
Settings.LoadFile(args[0]);
settingsIniPath = args[0];
//remove ini configuration file from arguments array
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>
/// Disconnect the current client from the server and restart it
/// </summary>

View file

@ -275,4 +275,10 @@ backupinterval=300 # How long should replay file be auto-saved, i
# this might clog the thread for terain handling) and thus slow the bot even more.
enabled=false
update_limit=10 # The rate at which the bot does calculations (10 = 1s) (Default: 5) (You can tweak this if you feel the bot is too slow)
stop_at_distance=3 # Do not follow the player if he is in the range of 3 blocks (prevents the bot from pushing a player in an infinite loop)
stop_at_distance=3 # Do not follow the player if he is in the range of 3 blocks (prevents the bot from pushing a player in an infinite loop)
[PlayerListLogger]
# Log the list of players periodically into a textual file
enabled=false
log_file=playerlog.txt
log_delay=600 # 10 = 1s

View file

@ -223,6 +223,14 @@ general.available_cmd=Available commands: {0}
# Animation
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
cmd.changeSlot.desc=Change slot in hotbar
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
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
cmd.respawn.desc=Use this to respawn if you are dead.
cmd.respawn.done=You have respawned.

View file

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

View file

@ -10,6 +10,8 @@ using MinecraftClient.Mapping;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using MinecraftClient.ChatBots;
using System.Diagnostics.CodeAnalysis;
namespace MinecraftClient
{
@ -256,7 +258,7 @@ namespace MinecraftClient
private static string ServerAliasTemp = null;
//Mapping for settings sections in the INI file
private enum Section { Default, Main, AppVars, Proxy, MCSettings, AntiAFK, Hangman, Alerts, ChatLog, AutoRelog, ScriptScheduler, RemoteControl, ChatFormat, AutoRespond, AutoAttack, AutoFishing, AutoEat, AutoCraft, AutoDrop, Mailer, ReplayMod, FollowPlayer, Logging, Signature };
private enum Section { Default, Main, AppVars, Proxy, MCSettings, AntiAFK, Hangman, Alerts, ChatLog, AutoRelog, ScriptScheduler, RemoteControl, ChatFormat, AutoRespond, AutoAttack, AutoFishing, AutoEat, AutoCraft, AutoDrop, Mailer, ReplayMod, FollowPlayer, PlayerListLogger, Logging, Signature };
/// <summary>
/// Get settings section from name
@ -854,6 +856,14 @@ namespace MinecraftClient
case "stop_at_distance": FollowPlayer_StopAtDistance = str2int(argValue); return true;
}
break;
case Section.PlayerListLogger:
switch (ToLowerIfNeed(argName))
{
case "enabled": PlayerLog_Enabled = str2bool(argValue); return true;
case "log_file": PlayerLog_File = argValue; return true;
case "log_delay": PlayerLog_Delay = str2int(argValue); return true;
}
break;
}
return false;
}
@ -1146,6 +1156,17 @@ namespace MinecraftClient
case "login": result.Append(Login); break;
case "serverip": result.Append(ServerIP); break;
case "serverport": result.Append(ServerPort); break;
case "datetime":
DateTime time = DateTime.Now;
result.Append(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")));
break;
default:
if (localVars != null && localVars.ContainsKey(varname_lower))
{