DeukBot4/DeukBot4/MessageHandlers/CommandHandler/CommandContainerBase.cs

65 lines
2.7 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)
{
// grab all command attributes, cast them properly
var commandAttributes = methodInfo.GetCustomAttributes(typeof(CommandAttribute), true)
.Select(x => x as CommandAttribute);
// 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();
foreach (var commandAttribute in commandAttributes)
{
if (commandAttribute == null)
continue;
if (helpAttribute == null)
{
commands.Add(new Command(commandAttribute.Command, commandAttribute.Permission, parameters,
forbidPm, matchParametersExactly, methodInfo, this));
}
else
{
commands.Add(new Command(commandAttribute.Command, commandAttribute.Permission,
helpAttribute.ShortHelp, helpAttribute.LongHelp, parameters, forbidPm,
matchParametersExactly, methodInfo, this));
}
}
}
return commands.ToArray();
}
}
}