Exemple #1
0
        public static EmbedBuilder GetHelpListEmbed(IDMCommandContext context)
        {
            string contextType = "";

            if (GuildCommandContext.TryConvert(context, out IGuildCommandContext guildContext))
            {
                contextType = "Guild";
            }
            else
            {
                contextType = "PM";
            }

            string embedTitle = "List of all Commands";
            string embedDesc  = "This list only shows commands where all preconditions have been met!";

            List <EmbedFieldBuilder> helpFields = new List <EmbedFieldBuilder>();

            foreach (CommandCollection collection in CommandCollection.AllCollections)
            {
                bool collectionAllowed = true;
                if (context.IsGuildContext)
                {
                    collectionAllowed = guildContext.ChannelMeta.allowedCommandCollections.Count == 0 || guildContext.ChannelMeta.allowedCommandCollections.Contains(collection.Name);
                }
                int availableCommands = collection.ViewableCommands(context, guildContext);
                if (availableCommands > 0 && collectionAllowed)
                {
                    helpFields.Add(Macros.EmbedField($"Collection \"{collection.Name}\"", $"{availableCommands} commands.{(string.IsNullOrEmpty(collection.Description) ? string.Empty : $" {collection.Description}.")} Use `{MessageHandler.CommandParser.CommandSyntax("man")}` to see a summary of commands in this command family!", true));
                }
            }
Exemple #2
0
        protected override Task <ArgumentParseResult> ParseArguments(IDMCommandContext context)
        {
            SystemName = context.Arguments.First;

            if (context.Arguments.TotalCount == 1)
            {
                Mode      = CommandMode.Default;
                JumpRange = 20;
                return(Task.FromResult(ArgumentParseResult.SuccessfullParse));
            }

            context.Arguments.Index++;

            if (!Enum.TryParse(context.Arguments.First, out Mode))
            {
                return(Task.FromResult(new ArgumentParseResult(Arguments[1])));
            }

            if (context.Arguments.TotalCount == 2)
            {
                JumpRange = 20;
                return(Task.FromResult(ArgumentParseResult.SuccessfullParse));
            }

            context.Arguments.Index++;

            if (!double.TryParse(context.Arguments.First, out JumpRange))
            {
                return(Task.FromResult(new ArgumentParseResult(Arguments[2])));
            }

            return(Task.FromResult(ArgumentParseResult.SuccessfullParse));
        }
Exemple #3
0
        private Task <ArgumentParseResult> parseArguments(IDMCommandContext context, IGuildCommandContext guildContext)
        {
            switch (ArgumentParserMethod)
            {
            case HandledContexts.None:
                return(Task.FromResult(ArgumentParseResult.DefaultNoArguments));

            case HandledContexts.DMOnly:
                return(ParseArguments(context));

            case HandledContexts.GuildOnly:
                return(ParseArgumentsGuildAsync(guildContext));

            case HandledContexts.Both:
                if (context.IsGuildContext)
                {
                    return(ParseArgumentsGuildAsync(guildContext));
                }
                else
                {
                    return(ParseArguments(context));
                }
            }
            return(Task.FromResult(new ArgumentParseResult("INTERNAL ERROR")));
        }
Exemple #4
0
 internal static bool TryParseArgument <T>(IDMCommandContext context, out T value, out string error) where T : class
 {
     if (parsers.TryGetValue(typeof(T), out ArgumentParser rawParser))
     {
         ArgumentParser <T> parser = rawParser as ArgumentParser <T>;
         if (parser != null)
         {
             if (parser.TryParseArgument(context, out value))
             {
                 error = null;
                 return(true);
             }
             else
             {
                 error = parser.ErrorMessage;
                 return(false);
             }
         }
         else
         {
             value = null;
             error = $"Internal Error at: {Macros.GetCodeLocation()}";
             return(false);
         }
     }
     else
     {
         value = null;
         error = $"Could not locate an argument parser for the type \"{typeof(T)}\"!";
         return(false);
     }
 }
Exemple #5
0
        /// <summary>
        /// Parses a user given a commandcontext. Because it works without guild context it needs to be asynchronous
        /// </summary>
        /// <param name="context">The commandcontext to parse the user from</param>
        /// <param name="argument">The argument string to parse the user from</param>
        /// <param name="allowMention">Wether mentioning is enabled for parsing user</param>
        /// <param name="allowSelf">Wether pointing to self is allowed</param>
        /// <param name="allowId">Wether the ulong id is enabled for parsing user</param>
        /// <returns>The parsed user if parsing succeeded, null instead</returns>
        public static async Task <SocketUser> ParseUser(IDMCommandContext context, string argument, bool allowMention = true, bool allowSelf = true, bool allowId = true)
        {
            SocketUser result = null;

            if (allowSelf && argument.Equals("self"))
            {
                result = context.User;
            }
            else if (allowMention && argument.StartsWith("<@") && argument.EndsWith('>') && argument.Length > 3)
            {
                if (ulong.TryParse(argument.Substring(2, argument.Length - 3), out ulong userId))
                {
                    result = await context.Channel.GetUserAsync(userId) as SocketUser;
                }
            }
            else if (allowMention && argument.StartsWith("<@!") && argument.EndsWith('>') && argument.Length > 3)
            {
                if (ulong.TryParse(argument.Substring(3, argument.Length - 3), out ulong userId))
                {
                    result = await context.Channel.GetUserAsync(userId) as SocketUser;
                }
            }
            else if (allowId && ulong.TryParse(argument, out ulong userId))
            {
                result = await context.Channel.GetUserAsync(userId) as SocketUser;
            }

            return(result);
        }
Exemple #6
0
        private static bool TryParseUlongArgument(IDMCommandContext context, out ObjectWrapper <ulong> value)
        {
            bool success = ulong.TryParse(context.Arguments.First, out ulong rawValue);

            value = rawValue;
            return(success);
        }
        protected override async Task Execute(IDMCommandContext context)
        {
            string            webrequest    = WebRequestService.EDSM_MultipleSystemsInfo_URL(new string[] { SystemA_name, SystemB_name }, showId: true, showCoords: true);
            RequestJSONResult requestResult = await WebRequestService.GetWebJSONAsync(webrequest);

            if (requestResult.IsSuccess)
            {
                if (requestResult.JSON.IsArray && requestResult.JSON.Array.Count < 1)
                {
                    await context.Channel.SendEmbedAsync("System not found in database!", true);
                }
                else
                {
                    if (printJson)
                    {
                        await context.Channel.SendEmbedAsync("General System Info", string.Format("```json\n{0}```", requestResult.JSON.Build(true).MaxLength(2037)));
                    }
                    EmbedBuilder distanceEmbed = GetDistanceEmbed(requestResult.JSON);
                    await context.Channel.SendEmbedAsync(distanceEmbed);
                }
            }
            else if (requestResult.IsException)
            {
                await context.Channel.SendEmbedAsync(string.Format("Could not connect to EDSMs services. Exception Message: `{0}`", requestResult.ThrownException.Message), true);
            }
            else
            {
                await context.Channel.SendEmbedAsync(string.Format("Could not connect to EDSMs services. HTTP Error: `{0} {1}`", (int)requestResult.Status, requestResult.Status.ToString()), true);
            }
        }
        private Task executeAsyncMode(IDMCommandContext context, IGuildCommandContext guildContext, object parsedArgs)
        {
            switch (ExecutionMethod)
            {
            case HandledContexts.None:
                return(context.Channel.SendEmbedAsync("INTERNAL ERROR", true));

            case HandledContexts.DMOnly:
                AsyncCommandContainer.NewAsyncCommand(Execute, context, parsedArgs);
                break;

            case HandledContexts.GuildOnly:
                AsyncCommandContainer.NewAsyncCommand(ExecuteGuild, guildContext, parsedArgs);
                break;

            case HandledContexts.Both:
                if (context.IsGuildContext)
                {
                    AsyncCommandContainer.NewAsyncCommand(ExecuteGuild, guildContext, parsedArgs);
                }
                else
                {
                    AsyncCommandContainer.NewAsyncCommand(Execute, context, parsedArgs);
                }
                break;
            }
            return(Task.CompletedTask);
        }
Exemple #9
0
        private static bool TryParseDoubleArgument(IDMCommandContext context, out ObjectWrapper <double> value)
        {
            bool success = double.TryParse(context.Arguments.First, out double rawValue);

            value = rawValue;
            return(success);
        }
Exemple #10
0
        private static void NewAsyncCommand(AsyncDelegate task, IDMCommandContext context)
        {
            AsyncCommandContainer container = new AsyncCommandContainer(task, context);

            container.typingState = context.Channel.EnterTypingState();
            AsyncCommandHandler.AddCommandContainer(container);
        }
        private Task executeSyncMode(IDMCommandContext context, IGuildCommandContext guildContext, object parsedArgs)
        {
            switch (ExecutionMethod)
            {
            case HandledContexts.None:
                return(context.Channel.SendEmbedAsync("INTERNAL ERROR", true));

            case HandledContexts.DMOnly:
                return(Execute(context, parsedArgs));

            case HandledContexts.GuildOnly:
                return(ExecuteGuild(guildContext, parsedArgs));

            case HandledContexts.Both:
                if (context.IsGuildContext)
                {
                    return(ExecuteGuild(guildContext, parsedArgs));
                }
                else
                {
                    return(Execute(context, parsedArgs));
                }

            default:
                return(Task.CompletedTask);
            }
        }
Exemple #12
0
        private bool CheckPreconditions(Precondition[] preconditions, IDMCommandContext context, IGuildCommandContext guildContext, bool isBotAdmin, out List <string> errors)
        {
            errors = new List <string>();
            if (!context.IsGuildContext && RequireGuildContext)
            {
                errors.Add("This command can not be used in DM channels!");
                return(false);
            }

            foreach (Precondition precondition in preconditions)
            {
                if (precondition.RequireGuild)
                {
                    if (!precondition.PreconditionCheckGuild(guildContext, out string error))
                    {
                        if (!precondition.OverrideAsBotadmin || !precondition.OverrideAsBotadmin)
                        {
                            errors.Add(error);
                        }
                    }
                }
                else
                {
                    if (!precondition.PreconditionCheck(context, out string error))
                    {
                        if (!precondition.OverrideAsBotadmin || !precondition.OverrideAsBotadmin)
                        {
                            errors.Add(error);
                        }
                    }
                }
            }

            return(errors.Count == 0);
        }
Exemple #13
0
        public static Task SendHelpList(IDMCommandContext context, ISocketMessageChannel outputchannel = null)
        {
            EmbedBuilder embed = GetHelpListEmbed(context);

            if (outputchannel == null)
            {
                outputchannel = context.Channel;
            }
            return(outputchannel.SendEmbedAsync(embed));
        }
Exemple #14
0
        public static Task SendCommandCollectionHelp(IDMCommandContext context, CommandCollection collection, ISocketMessageChannel outputchannel = null)
        {
            EmbedBuilder embed = GetCommandCollectionEmbed(context, collection);

            if (outputchannel == null)
            {
                outputchannel = context.Channel;
            }
            return(outputchannel.SendEmbedAsync(embed));
        }
 private Task execute(IDMCommandContext context, IGuildCommandContext guildContext, object parsedArgs)
 {
     if (RunInAsyncMode)
     {
         return(executeAsyncMode(context, guildContext, parsedArgs));
     }
     else
     {
         return(executeSyncMode(context, guildContext, parsedArgs));
     }
 }
Exemple #16
0
 protected override Task Execute(IDMCommandContext context, object argObj)
 {
     if (AboutEmbed.Author == null)
     {
         AboutEmbed.Author = new EmbedAuthorBuilder()
         {
             IconUrl = BotCore.Client.CurrentUser.GetDefaultAvatarUrl()
         };
     }
     return(context.Channel.SendEmbedAsync(AboutEmbed));
 }
Exemple #17
0
        protected override async Task Execute(IDMCommandContext context)
        {
            string requestSystem   = WebRequestService.EDSM_SystemInfo_URL(systemName, true, true, true, true, true);
            string requestStations = WebRequestService.EDSM_SystemStations_URL(systemName);
            string requestTraffic  = WebRequestService.EDSM_SystemTraffic_URL(systemName);
            string requestDeaths   = WebRequestService.EDSM_SystemDeaths_URL(systemName);

            if (webRequests)
            {
                EmbedBuilder embed = new EmbedBuilder()
                {
                    Title       = "Webrequests",
                    Color       = BotCore.EmbedColor,
                    Description = $"[System]({requestSystem}) `{requestSystem}`\n[Stations]({requestStations}) `{requestStations}`\n[Traffic]({requestTraffic}) `{requestTraffic}`\n[Deaths]({requestDeaths}) `{requestDeaths}`"
                };
                await context.Channel.SendEmbedAsync(embed);
            }
            RequestJSONResult requestResultSystem = await WebRequestService.GetWebJSONAsync(requestSystem);

            RequestJSONResult requestResultStations = await WebRequestService.GetWebJSONAsync(requestStations);

            RequestJSONResult requestResultTraffic = await WebRequestService.GetWebJSONAsync(requestTraffic);

            RequestJSONResult requestResultDeaths = await WebRequestService.GetWebJSONAsync(requestDeaths);

            if (requestResultSystem.IsSuccess)
            {
                if (requestResultSystem.JSON.IsArray && requestResultSystem.JSON.Array.Count < 1)
                {
                    await context.Channel.SendEmbedAsync("System not found in database!", true);
                }
                else
                {
                    if (printJson)
                    {
                        await context.Channel.SendEmbedAsync("General System Info", string.Format("```json\n{0}```", requestResultSystem.JSON.Build(true).MaxLength(2037)));

                        await context.Channel.SendEmbedAsync("Station Info", string.Format("```json\n{0}```", requestResultStations.JSON.Build(true).MaxLength(2037)));
                    }
                    EmbedBuilder systemEmbed = GetSystemInfoEmbed(requestResultSystem.JSON, requestResultStations.JSON, requestResultTraffic.JSON, requestResultDeaths.JSON, out List <EmbedFieldBuilder> allStations);
                    await context.Channel.SendEmbedAsync(systemEmbed);
                }
            }
            else if (requestResultSystem.IsException)
            {
                await context.Channel.SendEmbedAsync(string.Format("Could not connect to EDSMs services. Exception Message: `{0}`", requestResultSystem.ThrownException.Message), true);
            }
            else
            {
                await context.Channel.SendEmbedAsync(string.Format("Could not connect to EDSMs services. HTTP Error: `{0} {1}`", (int)requestResultSystem.Status, requestResultSystem.Status.ToString()), true);
            }
        }
Exemple #18
0
 public override bool PreconditionCheck(IDMCommandContext context, out string message)
 {
     if (context.UserInfo.IsBotAdmin)
     {
         message = null;
         return(true);
     }
     else
     {
         message = "BotAdmin privileges required!";
         return(false);
     }
 }
Exemple #19
0
        public int ViewableCommands(IDMCommandContext context, IGuildCommandContext guildContext)
        {
            int count = 0;

            foreach (Command c in commandsInCollection)
            {
                if (c.CanView(context, guildContext, context.UserInfo.IsBotAdmin, out _))
                {
                    count++;
                }
            }
            return(count);
        }
        private static bool tryGetCommandCollectionEmbedField(IDMCommandContext context, IGuildCommandContext guildContext, CommandCollection collection, out EmbedFieldBuilder embedField)
        {
            bool collectionAllowed = true;

            if (context.IsGuildContext)
            {
                collectionAllowed = guildContext.ChannelMeta.allowedCommandCollections.Count == 0 || guildContext.ChannelMeta.allowedCommandCollections.Contains(collection.Name);
            }
            int availableCommands = collection.ViewableCommands(context, guildContext);

            if (availableCommands > 0 && collectionAllowed)
            {
                embedField = Macros.EmbedField($"Collection \"{collection.Name}\"", $"{availableCommands} commands.{(string.IsNullOrEmpty(collection.Description) ? string.Empty : $" {collection.Description}.")} Use `{MessageHandler.CommandParser.CommandSyntax("man", collection.Name)}` to see a summary of commands in this command family!", true);
                return(true);
            }
Exemple #21
0
        protected override Task <ArgumentParseResult> ParseArguments(IDMCommandContext context)
        {
            if (context.Message.Content.Length > Identifier.Length + 1)
            {
                string embedText = context.ArgumentSection.Replace("[3`]", "```");

                if (JSONContainer.TryParse(embedText, out JSONContainer json, out string errormessage))
                {
                    return(Task.FromResult(EmbedHelper.TryParseEmbedFromJSONObject(json, out embed, out messageContent)));
                }
                else
                {
                    return(Task.FromResult(new ArgumentParseResult(Arguments[0], $"Unable to parse JSON text to a json data structure! Error: `{errormessage}`")));
                }
            }
Exemple #22
0
 public static bool TryParseGuild(IDMCommandContext context, string argument, out SocketGuild guild, bool allowthis = true, bool allowId = true)
 {
     if (allowthis && argument.ToLower() == "this" && GuildCommandContext.TryConvert(context, out IGuildCommandContext guildContext))
     {
         guild = guildContext.Guild;
         return(guild != null);
     }
     else if (allowId && ulong.TryParse(argument, out ulong guildId))
     {
         guild = BotCore.Client.GetGuild(guildId);
         return(guild != null);
     }
     guild = null;
     return(false);
 }
Exemple #23
0
 protected override Task Execute(IDMCommandContext context)
 {
     if (collection != null)
     {
         return(CommandManual.SendCommandCollectionHelp(context, collection));
     }
     else if (command != null)
     {
         return(CommandManual.SendCommandHelp(context, command));
     }
     else
     {
         return(CommandManual.SendHelpList(context));
     }
 }
Exemple #24
0
        public static EmbedBuilder GetCommandCollectionEmbed(IDMCommandContext context, CommandCollection collection)
        {
            string contextType = "";

            if (GuildCommandContext.TryConvert(context, out IGuildCommandContext guildContext))
            {
                contextType = "Guild";
            }
            else
            {
                contextType = "PM";
            }

            string embedTitle = $"Command Collection \"{collection.Name}\"";
            string embedDesc  = "This list only shows commands where all preconditions have been met!";

            List <EmbedFieldBuilder> helpFields = new List <EmbedFieldBuilder>();

            foreach (Command command in collection.Commands)
            {
                if (command.CanView(context, guildContext, context.UserInfo.IsBotAdmin, out _))
                {
                    helpFields.Add(Macros.EmbedField(command.Syntax, command.Summary, true));
                }
            }

            if (helpFields.Count == 0)
            {
                embedDesc = "No command's precondition has been met!";
                return(new EmbedBuilder()
                {
                    Title = embedTitle, Description = embedDesc, Color = BotCore.ErrorColor, Footer = new EmbedFooterBuilder()
                    {
                        Text = "Context: " + contextType
                    }
                });
            }
            else
            {
                return(new EmbedBuilder()
                {
                    Title = embedTitle, Description = embedDesc, Color = BotCore.EmbedColor, Footer = new EmbedFooterBuilder()
                    {
                        Text = "Context: " + contextType
                    }, Fields = helpFields
                });
            }
        }
Exemple #25
0
        protected override Task <ArgumentParseResult> ParseArguments(IDMCommandContext context)
        {
            cmdrName = context.Arguments.First;

            if (context.Arguments.TotalCount == 1)
            {
                printJson = false;
                return(Task.FromResult(ArgumentParseResult.SuccessfullParse));
            }

            context.Arguments.Index++;

            printJson = context.Arguments.First.Contains("json");

            return(Task.FromResult(ArgumentParseResult.SuccessfullParse));
        }
Exemple #26
0
        protected override Task Execute(IDMCommandContext context, object argObj)
        {
            ArgumentContainer args = argObj as ArgumentContainer;

            if (args != null)
            {
                if (args.collection != null)
                {
                    return(CommandManual.SendCommandCollectionHelp(context, args.collection));
                }
                else if (args.command != null)
                {
                    return(CommandManual.SendCommandHelp(context, args.command));
                }
            }
            return(CommandManual.SendHelpList(context));
        }
Exemple #27
0
        internal async Task HandleCommandAsync(IDMCommandContext context, IGuildCommandContext guildContext)
        {
            string stage = "Checking Preconditions";

            try
            {
                if (CanExecute(context, guildContext, context.UserInfo.IsBotAdmin, out List <string> errors))
                {
                    stage = "Parsing Arguments";
                    ArgumentParseResult parseResult = await parseArguments(context, guildContext);

                    if (!parseResult.Success)
                    {
                        EmbedBuilder parseFailed = new EmbedBuilder()
                        {
                            Color       = BotCore.ErrorColor,
                            Title       = "Argument Parsing Failed!",
                            Description = parseResult.ToString()
                        };
                        await context.Channel.SendEmbedAsync(parseFailed);
                    }
                    else
                    {
                        stage = "Executing Command";
                        await execute(context, guildContext);
                    }
                }
                else
                {
                    EmbedBuilder embed = new EmbedBuilder()
                    {
                        Title       = "Command Execution Failed",
                        Color       = BotCore.ErrorColor,
                        Description = errors.Join("\n")
                    };
                    await context.Channel.SendEmbedAsync(embed);
                }
            }
            catch (Exception e)
            {
                await context.Channel.SendMessageAsync($"Exception at stage `{stage}`", embed : Macros.EmbedFromException(e).Build());
            }
        }
Exemple #28
0
        protected override Task <ArgumentParseResult> ParseArguments(IDMCommandContext context)
        {
            systemName = context.Arguments.First;

            if (context.Arguments.TotalCount == 1)
            {
                webRequests     = false;
                printJson       = false;
                listAllStations = false;
                return(Task.FromResult(ArgumentParseResult.SuccessfullParse));
            }

            context.Arguments.Index++;

            webRequests     = context.Arguments.First.Contains("webrequests");
            printJson       = context.Arguments.First.Contains("json");
            listAllStations = context.Arguments.First.Contains("list");

            return(Task.FromResult(ArgumentParseResult.SuccessfullParse));
        }
        protected override Task <ArgumentParseResult> ParseArguments(IDMCommandContext context)
        {
            SystemA_name = context.Arguments.First;

            context.Arguments.Index++;

            SystemB_name = context.Arguments.First;

            if (context.Arguments.TotalCount == 2)
            {
                printJson = false;
            }
            else
            {
                context.Arguments.Index++;

                printJson = context.Arguments.First.ToLower().Contains("json");
            }
            return(Task.FromResult(ArgumentParseResult.SuccessfullParse));
        }
Exemple #30
0
        protected override Task <ArgumentParseResult> ParseArguments(IDMCommandContext context)
        {
            if (context.Arguments.TotalCount == 0)
            {
                identifier = null;
                command    = null;
                return(Task.FromResult(ArgumentParseResult.DefaultNoArguments));
            }

            identifier = context.Arguments.First;
            if (!CommandCollection.TryFindCommand(identifier, out command))
            {
                if (!CommandCollection.AllCollections.TryFind(collection => { return(collection.Name.ToLower() == identifier.ToLower()); }, out collection))
                {
                    return(Task.FromResult(ArgumentParseResult.SuccessfullParse));
                }
            }

            return(Task.FromResult(ArgumentParseResult.SuccessfullParse));
        }