Add command auto-unregister mechanism (#1492)

* Add command auto-unregister mechanism

* Improve logic
This commit is contained in:
ReinforceZwei 2021-03-07 14:21:19 +08:00 committed by GitHub
parent 4853871ea1
commit 62c985376e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 2 deletions

View file

@ -40,6 +40,7 @@ namespace MinecraftClient
private McClient _handler = null; private McClient _handler = null;
private ChatBot master = null; private ChatBot master = null;
private List<string> registeredPluginChannels = new List<String>(); private List<string> registeredPluginChannels = new List<String>();
private List<string> registeredCommands = new List<string>();
private McClient Handler private McClient Handler
{ {
get get
@ -781,6 +782,10 @@ namespace MinecraftClient
/// </summary> /// </summary>
protected void UnloadBot() protected void UnloadBot()
{ {
foreach (string cmdName in registeredCommands)
{
Handler.UnregisterCommand(cmdName);
}
Handler.BotUnLoad(this); Handler.BotUnLoad(this);
} }
@ -1261,7 +1266,7 @@ namespace MinecraftClient
} }
/// <summary> /// <summary>
/// Register a command in command prompt /// Register a command in command prompt. Command will be automatically unregistered when unloading ChatBot
/// </summary> /// </summary>
/// <param name="cmdName">Name of the command</param> /// <param name="cmdName">Name of the command</param>
/// <param name="cmdDesc">Description/usage of the command</param> /// <param name="cmdDesc">Description/usage of the command</param>
@ -1269,7 +1274,10 @@ namespace MinecraftClient
/// <returns>True if successfully registered</returns> /// <returns>True if successfully registered</returns>
protected bool RegisterChatBotCommand(string cmdName, string cmdDesc, string cmdUsage, CommandRunner callback) protected bool RegisterChatBotCommand(string cmdName, string cmdDesc, string cmdUsage, CommandRunner callback)
{ {
return Handler.RegisterCommand(cmdName, cmdDesc, cmdUsage, callback); bool result = Handler.RegisterCommand(cmdName, cmdDesc, cmdUsage, callback);
if (result)
registeredCommands.Add(cmdName.ToLower());
return result;
} }
/// <summary> /// <summary>

View file

@ -629,6 +629,26 @@ namespace MinecraftClient
} }
} }
/// <summary>
/// Unregister a console command
/// </summary>
/// <remarks>
/// There is no check for the command is registered by above method or is embedded command.
/// Which mean this can unload any command
/// </remarks>
/// <param name="cmdName">The name of command to be unregistered</param>
/// <returns></returns>
public bool UnregisterCommand(string cmdName)
{
if (cmds.ContainsKey(cmdName.ToLower()))
{
cmds.Remove(cmdName.ToLower());
cmd_names.Remove(cmdName.ToLower());
return true;
}
else return false;
}
#region Management: Load/Unload ChatBots and Enable/Disable settings #region Management: Load/Unload ChatBots and Enable/Disable settings
/// <summary> /// <summary>