DeukBot4/DeukBot4/MessageHandlers/CommandHandler/CommandContainerBase.cs

67 lines
2.8 KiB
C#

using System.Collections.Generic;
using System.Linq;
namespace DeukBot4.MessageHandlers.CommandHandler
{
public abstract class CommandContainerBase
{
public abstract string Name { get; }
public Command[] GetCommands()
{
var funcs = GetType().GetMethods()
.Where(x => x.GetCustomAttributes(typeof(CommandAttribute), true).Length > 0);
var commands = new List<Command>();
foreach (var methodInfo in funcs)
{
// grab all command attributes, cast them properly
var commandAttributes = methodInfo.GetCustomAttributes(typeof(CommandAttribute), true)
.Select(x => x as CommandAttribute).ToArray();
// get the help attribute if it exists
CommandHelpAttribute helpAttribute = null;
var helpAttributes = methodInfo.GetCustomAttributes(typeof(CommandHelpAttribute), true)
.Select(x => x as CommandHelpAttribute).ToArray();
if (helpAttributes.Any())
helpAttribute = helpAttributes[0];
// grab all of the potential parameter type arrays
var parameters = methodInfo.GetCustomAttributes(typeof(CommandParametersAttribute), true)
.Select(x => (CommandParametersAttribute) x)
.Select(x => x.Types.ToArray())
.ToArray();
// check if the function has the attribute for blocking usage in PMs
var forbidPm = methodInfo.GetCustomAttributes(typeof(BlockUsageInPmAttribute), true).Any();
var matchParametersExactly =
methodInfo.GetCustomAttributes(typeof(RequireParameterMatchAttribute), true).Any();
var firstCommand = commandAttributes.First();
Command command;
if (helpAttribute == null)
{
command = (new Command(firstCommand.Command, firstCommand.Permission, parameters,
forbidPm, matchParametersExactly, methodInfo, this));
}
else
{
command = (new Command(firstCommand.Command, firstCommand.Permission,
helpAttribute.ShortHelp, helpAttribute.LongHelp, parameters, forbidPm,
matchParametersExactly, methodInfo, this));
}
for (var i = 1; i < commandAttributes.Length; i++)
{
var cmd = commandAttributes[i];
if (cmd == null)
continue;
command.Alternatives.Add(cmd.Command);
}
commands.Add(command);
}
return commands.ToArray();
}
}
}