DeukBot4/DeukBot4/MessageHandlers/CommandHandler/CommandContainerBase.cs

56 lines
2.4 KiB
C#

using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using DeukBot4.MessageHandlers.CommandHandler.RequestStructure;
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)
{
var commandAttributes = methodInfo.GetCustomAttributes(typeof(CommandAttribute), true)
.Select(x => x as CommandAttribute);
CommandHelpAttribute helpAttribute = null;
var helpAttributes = methodInfo.GetCustomAttributes(typeof(CommandHelpAttribute), true)
.Select(x => x as CommandHelpAttribute);
var commandHelpAttributes = helpAttributes as CommandHelpAttribute[] ?? helpAttributes.ToArray();
if (commandHelpAttributes.Any())
helpAttribute = commandHelpAttributes[0];
var parametersAttributes = methodInfo.GetCustomAttributes(typeof(CommandParametersAttribute), true)
.Select(x => x as CommandParametersAttribute);
var commandParametersAttributes = parametersAttributes as CommandParametersAttribute[] ??
parametersAttributes.ToArray();
var parameters = commandParametersAttributes.Select(x => x.Types).ToArray();
foreach (var commandAttribute in commandAttributes)
{
if (commandAttribute == null)
continue;
if (helpAttribute == null)
{
commands.Add(new Command(commandAttribute.Command, commandAttribute.Permission, parameters,
methodInfo, this));
}
else
{
commands.Add(new Command(commandAttribute.Command, commandAttribute.Permission,
helpAttribute.ShortHelp, helpAttribute.LongHelp, parameters, methodInfo, this));
}
}
}
return commands.ToArray();
}
}
}