chaosbot/ChaosBot/Discord/Services/CustomCommandHandler.cs

67 lines
2.5 KiB
C#

using System;
using System.Linq;
using System.Threading.Tasks;
using ChaosBot.Models;
using ChaosBot.Services;
using ChaosBot.Services.ProgrammingLanguageInterpreter;
using Discord;
using Discord.Commands;
namespace ChaosBot.Discord.Services
{
public static class CustomCommandHandler
{
public static async Task<bool> CheckCommand(SocketCommandContext context, int argPos)
{
try
{
await using ChaosbotContext dbContext = new ChaosbotContext();
string command = context.Message.Content.Substring(argPos);
IQueryable<CustomCommand> customCommandQuery = dbContext.CustomCommands;
CustomCommand customCommand = customCommandQuery
.Where(cc => cc.DiscordGuildId == context.Guild.Id)
.FirstOrDefault(cc => command.StartsWith(cc.Command));
if (customCommand == null) return false;
LoggingFacade.Info($"Running custom command [{context.User.Username}#{context.User.Discriminator} -> {customCommand.Command}]");
if (customCommand.Type == CustomCommandType.Basic)
{
await context.Channel.SendMessageAsync(customCommand.Content);
}
else if(customCommand.Type == CustomCommandType.CustomLua)
{
if (!ProgrammingLanguageInterpreterFacade.TryInterpret(context, customCommand,
out string errorReason))
{
await context.Channel.SendMessageAsync(errorReason);
throw new Exception($"Could not execute code for command '{customCommand.Command}': {errorReason}");
}
}
else if (customCommand.Type == CustomCommandType.Embed)
{
EmbedBuilder embedBuilder = new EmbedBuilder();
CustomCommandEmbedBuilderFacade.SetDetails(embedBuilder, customCommand.Content);
Embed embed = embedBuilder.Build();
await context.Channel.SendMessageAsync(embed: embed);
}
else
{
throw new NotImplementedException($"No support for command type ${customCommand.Type}");
}
return true;
}
catch (Exception ex)
{
LoggingFacade.Exception(ex);
}
return false;
}
}
}