78 lines
2.7 KiB
C#
78 lines
2.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using DeukBot4.MessageHandlers.CommandHandler.RequestStructure;
|
|
using DeukBot4.MessageHandlers.Permissions;
|
|
using DeukBot4.Utilities;
|
|
using Discord;
|
|
using Discord.WebSocket;
|
|
|
|
namespace DeukBot4.MessageHandlers.CommandHandler
|
|
{
|
|
public static class CommandHandler
|
|
{
|
|
public static Dictionary<string, Command> Commands { get; private set; } = new Dictionary<string, Command>();
|
|
public const char CommandTrigger = '!';
|
|
|
|
public static void Build()
|
|
{
|
|
var commandContainers = typeof(CommandHandler).Assembly.GetTypes()
|
|
.Where(x => typeof(CommandContainerBase).IsAssignableFrom(x) && !x.IsAbstract);
|
|
|
|
foreach (var commandContainer in commandContainers)
|
|
{
|
|
if (!(Activator.CreateInstance(commandContainer) is CommandContainerBase obj))
|
|
continue;
|
|
var commands = obj.GetCommands();
|
|
foreach (var command in commands)
|
|
{
|
|
Commands.Add(command.Name.ToLowerInvariant(), command);
|
|
}
|
|
|
|
Logger.Log($"Loaded following commands for container {obj.Name}: {commands.Select(x => x.Name).Join(", ")}");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
public static async Task HandleMessage(SocketMessage message)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(message.Content))
|
|
return;
|
|
|
|
if (message.Content[0] != CommandTrigger) return;
|
|
var req = await CommandRequest.Create(message);
|
|
var resultCode = req.Item2;
|
|
if (resultCode == CommandRequest.RequestCode.Invalid)
|
|
{
|
|
await Logger.LogError("Invalid content: " + message.Content);
|
|
return;
|
|
}
|
|
else if (resultCode == CommandRequest.RequestCode.Forbidden)
|
|
{
|
|
await Logger.Log(
|
|
$"Unauthorized user tried to run command: {message.Author.Username} -> {message.Content}");
|
|
}
|
|
|
|
else if (resultCode == CommandRequest.RequestCode.OK)
|
|
{
|
|
if (!(message.Channel is IGuildChannel) && req.Item1.Command.ForbidInPm)
|
|
{
|
|
await Logger.Log(
|
|
$"User is trying to use blocked command in PM: {message.Author.Username}");
|
|
return;
|
|
}
|
|
|
|
await req.Item1.Command.Invoke(req.Item1);
|
|
|
|
}
|
|
}
|
|
|
|
public static Command GetCommand(string name)
|
|
{
|
|
return Commands.TryGetValue(name.ToLowerInvariant(), out var com) ? com : null;
|
|
}
|
|
}
|
|
} |