示例#1
0
        public async Task SetLanguage(string language)
        {
            var eb = new EmbedBuilder();
            var ts = await TranslationManager.CreateFor(Context.Channel);

            eb.Title = ts.GetMessage("commands/language:embed_title");

            try
            {
                CultureInfo lang = new CultureInfo(language);
                if (!TranslationManager.HasLanguage(lang))
                {
                    // Please translate :)
                    eb = EmbedFactory.CreateError()
                         .WithTitle(ts.GetMessage("commands/language:embed_title"))
                         .WithDescription(MessageFormatter.Format(ts.GetMessage("commands/language:error_language_not_found"), lang.TwoLetterISOLanguageName));
                }
                else
                {
                    eb.Color       = EmbedFactory.Success;
                    eb.Description = MessageFormatter.Format(ts.GetMessage("commands/language:language_set_message"), lang.TwoLetterISOLanguageName);
                    await TranslationManager.SetLanguageAsync(TranslationManager.GetId(Context.Channel), lang);
                }
            }
            catch (CultureNotFoundException)
            {
                eb.Description = ts.GetMessage("commands/language:error_unknown_language");
                eb.Color       = EmbedFactory.Error;
            }
            await ReplyAsync(embed : eb.Build());
        }
        private async Task ProcessCommandAsync(SocketMessage arg)
        {
            // Source filter
            if (arg.Source != MessageSource.User)
            {
                return;
            }
            var message = (SocketUserMessage)arg;

            // Get the prefix
            string pfx;

            try
            {
                pfx = await GetPrefix(arg);
            }
            catch (Exception e)
            {
                string src = message.Channel is IGuildChannel gc ? $"{gc.Guild.Name} ({gc.Guild.Id})" : $"{message.Channel.Name}";
                Logger.GetLogger("Commands").Warning($"Failed to get prefix. {src}", e);
                return;
            }

            // Command check
            int argPos = 0;

            if (message.HasStringPrefix(pfx, ref argPos))
            {
                // Refresh the cached prefix
                if (message.Channel is IGuildChannel c)
                {
                    pm.RestoreCache(c.GuildId).Release();
                }
                var context = new SocketCommandContext(client, message);
                // Log message for debugging (doesn't check if the command exists)
                Logger.GetLogger("Commands").Debug($"Executing command: {GetExecutionInfo(context)}");
                // Execute command
                await commands.ExecuteAsync(context, argPos, services);
            }
            else if (message.Content.TrimEnd() == $"{pm.DefaultPrefix}prefix")
            {
                // Info
                var context = new SocketCommandContext(client, message);
                Logger.GetLogger("Commands").Debug($"Executing prefix get with default prefix: {GetExecutionInfo(context)}");
                var ts = await TranslationManager.CreateFor(context.Channel);

                message.Channel.SendMessageAsync(embed: EmbedFactory.CreateSuccess()
                                                 .WithTitle(ts.GetMessage("commands/prefix:embed_title"))
                                                 .WithDescription(MessageFormatter.Format(ts.GetMessage("commands/prefix:my_prefix_is"),
                                                                                          PrefixManagerService.PrettyPrefix(pfx)))
                                                 .Build()).Release();
            }
        }
示例#3
0
        public async Task Purge([Remainder] string args = null)
        {
            // Delete message
            await Context.Message.DeleteAsync();

            // Respond
            var ts = await TranslationManager.CreateFor(Context.Channel);

            var m = await ReplyAsync(ts.GetMessage("commands/purge:delet_this_success"));

            m.DeleteAfterDelay(5000).Release();
        }
        private async Task CommandExecutedAsync(Optional <CommandInfo> command, ICommandContext ctx, IResult result)
        {
            // Some error occured in command execution
            if (!result.IsSuccess)
            {
                var ts = await TranslationManager.CreateFor(ctx.Channel);

                string message;
                if (command.IsSpecified)
                {
                    try
                    {
                        message = ts.GetMessage(result.ErrorReason);
                    }
                    catch (FormatException)
                    {
                        message = ts.GetMessage("errors:command_errored");
                    }
                }
                else
                {
                    message = ts.GetMessage("command_not_found");
                }

                await ctx.Channel.SendMessageAsync(message)
                .ContinueWith(t =>
                {
                    if (!t.IsCompletedSuccessfully)
                    {
                        Logger.GetLogger("Commands").Info($"Failed to send error message: {t.Exception.InnerException.Message}");
                    }
                    else
                    {
                        t.Result.DeleteAfterDelay(5000).GetAwaiter().GetResult();
                    }
                }).ConfigureAwait(false);
            }

            // Log
            var sb = new StringBuilder();

            if (!command.IsSpecified)
            {
                sb.Append("Unspecified command: ");
            }
            else
            {
                sb.Append("Executed command: ");
            }
            sb.AppendLine(GetExecutionInfo(ctx));
            Logger.GetLogger("Commands").Info(sb.ToString());
        }
示例#5
0
        public async Task ResetPrefix()
        {
            // Prepare reply
            var ts = await TranslationManager.CreateFor(Context.Channel);

            var eb = EmbedFactory.CreateSuccess()
                     .WithTitle(ts.GetMessage("commands/prefix:embed_title"));

            var messageSend = ReplyAsync(embed: eb.Build());

            await pm.CachePrefix(Context.Guild.Id, pm.DefaultPrefix);

            await pm.SetPrefixAsync(Context.Guild.Id, pm.DefaultPrefix);

            await messageSend;
        }
示例#6
0
        public async Task <Embed> HelpAsync(ICommandContext context, string query, SearchContext searchContext)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (query is null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            var commands = (await SearchCommands(context, query, searchContext)).ToList();

            if (commands.Count == 0)
            {
                var ts = await TranslationManager.CreateFor(context.Channel);

                return(EmbedFactory.CreateNeutral()
                       .WithTitle(ts.GetMessage("help:embed_title"))
                       .WithDescription(ts.GetMessage("help:command_not_found"))
                       .Build());
            }

            // NOTE: This system breaks when there are two commands with the same alias. Avoid using same aliases
            if (commands.Count > 1)
            {
                var ts = await TranslationManager.CreateFor(context.Channel);

                return(EmbedFactory.CreateNeutral()
                       .WithTitle(ts.GetMessage("help:embed_title"))
                       .WithDescription($"{ts.GetMessage("help:multiple_matches")}\n{String.Join("\n", commands.Select(x => Format.Code(x.GetUsage())))}")
                       .Build());
            }
            else
            {
                return(await commands[0].CreateHelpEmbedAsync(context));
            }
        }
示例#7
0
        public async Task Purge(int limit, [Remainder] string args = null)
        {
            // Delete the command
            await Context.Message.DeleteAsync();

            // Get messages and delete
            var messages = await Context.Channel.GetMessagesAsync(limit).FlattenAsync();

            bool failedToDelete = false;

            try
            {
                await(Context.Channel as ITextChannel)?.DeleteMessagesAsync(messages);
            }
            catch (ArgumentOutOfRangeException)
            {
                // One or more of messages older than two weeks
                failedToDelete = true;
            }
            // Respond
            var ts = await TranslationManager.CreateFor(Context.Channel);

            string message;

            if (failedToDelete)
            {
                message = ts.GetMessage("commands/purge:error_older_than_two_weeks");
            }
            else
            {
                message = ts.GetMessage("commands/purge:delete_success");
            }
            // Send response
            await Context.Channel.SendMessageFormatted(message, args : messages.Count())
            .ContinueWith(async msg => await msg.Result.DeleteAfterDelay(5000)).ConfigureAwait(false);
        }
示例#8
0
        /// <summary>
        /// Creates a help embed for the command.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="command"></param>
        /// <returns></returns>
        public static async Task <Embed> CreateHelpEmbedAsync(this CommandInfo command, ICommandContext context)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (command is null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            var ts = await TranslationManager.CreateFor(context.Channel);

            var eb = EmbedFactory.CreateNeutral()
                     .WithTitle(ts.GetMessage("help:embed_title"))
                     // Name
                     .AddField(ts.GetMessage("help:field_name"), command.Aliases[0])
                     // Description
                     .AddField(x =>
            {
                x.Name = ts.GetMessage("help:field_description");
                if (String.IsNullOrEmpty(command.Summary))
                {
                    x.Value = ts.GetMessage("help:no_description");
                }
                else
                {
                    x.Value = ts.GetMessage(command.Summary);
                }
            });

            // Remarks
            if (!String.IsNullOrEmpty(command.Remarks))
            {
                eb.AddField(ts.GetMessage("help:field_remarks"), command.Remarks);
            }

            // Categories
            if (command.Preconditions.FirstOrDefault(p => p is CategoriesAttribute) is CategoriesAttribute ca)
            {
                eb.AddField(ts.GetMessage("help:field_categories"), String.Join(", ", ca.Categories.Select(x => Format.Code(x))));
            }

            // Tags
            var tags = command.GetTags();

            if (tags.Any())
            {
                eb.AddField(ts.GetMessage("help:field_tags"), String.Join(", ", tags.Select(t => Format.Code(t))));
            }

            // Usage and aliases
            eb.AddField(ts.GetMessage("help:field_usage"), Format.Code(GetUsage(command)))
            .AddField(ts.GetMessage("help:field_aliases"), String.Join(", ", command.Aliases.Select(x => Format.Code(x))));

            // Parameters
            if (command.Parameters.Any())
            {
                eb.AddField(ts.GetMessage("help:field_parameters"), String.Join("\n", command.Parameters.Select(p =>
                {
                    var sb = new StringBuilder();
                    sb.Append($"{Format.Code(p.Name)}: ");
                    if (String.IsNullOrEmpty(p.Summary))
                    {
                        sb.Append(ts.GetMessage("help:no_description"));
                    }
                    else
                    {
                        sb.Append(ts.GetMessage(p.Summary));
                    }
                    return(sb.ToString());
                })));
            }
            return(eb.Build());
        }
示例#9
0
        public async Task Prefix([Summary("commands/prefix:parameter_prefix")][Remainder] string prefix = null)
        {
            // Prepare reply
            EmbedBuilder eb;
            var          reply = new StringBuilder();
            var          ts    = await TranslationManager.CreateFor(Context.Channel);

            // Get the prefix
            if (prefix is null)
            {
                // Get prefix
                var prefixGet = pm.GetPrefixAsync(Context.Guild?.Id);

                // Prepare message
                eb = EmbedFactory.CreateSuccess()
                     .WithTitle(ts.GetMessage("commands/prefix:embed_title"));

                // Send a message
                reply.AppendLine(MessageFormatter.Format(ts.GetMessage("commands/prefix:my_prefix_is"), PrefixManagerService.PrettyPrefix(await prefixGet)));
                if (Context.IsPrivate)
                {
                    reply.AppendLine(ts.GetMessage("commands/prefix:error_private_messages"));
                }
                eb.Description = reply.ToString();
                await ReplyAsync(embed : eb.Build());

                // Return!
                return;
            }

            // Check if in guild
            if (Context.Guild is null)
            {
                // No
                eb = EmbedFactory.CreateError()
                     .WithTitle(ts.GetMessage("errors:permission_denied"));
                reply.AppendLine(ts.GetMessage("commands/prefix:error_private_messages"));
            }
            else
            {
                // In guild
                string currentPrefix = await pm.GetPrefixAsync(Context.Guild.Id);

                if (currentPrefix == prefix)
                {
                    eb = EmbedFactory.CreateError()
                         .WithTitle(ts.GetMessage("errors:permission_denied"));
                    reply.AppendLine(ts.GetMessage("commands/prefix:error_same_prefix"));
                }
                else
                {
                    if (!Regex.IsMatch(prefix, @"[A-Za-zÅÖÄåöä0-9!?+\/%$#]*"))
                    {
                        eb = EmbedFactory.CreateError()
                             .WithTitle(ts.GetMessage("commands/prefix:embed_title"))
                             .WithDescription("commands/prefix:error_invalid_prefix");
                        await ReplyAsync(embed : eb.Build());

                        return;
                    }

                    // Update the prefix cache
                    await pm.CachePrefix(Context.Guild.Id, prefix);

                    // Send the info message here for seemingly better performance. The prefix is cached in Redis so it will still work.
                    eb = EmbedFactory.CreateSuccess()
                         .WithTitle(ts.GetMessage("commands/prefix:embed_title"));
                    reply.AppendLine(MessageFormatter.Format(ts.GetMessage("commands/prefix:prefix_set_message"),
                                                             PrefixManagerService.PrettyPrefix(prefix)));

                    // Send message
                    eb.Description = reply.ToString();
                    ReplyAsync(embed: eb.Build()).Release();

                    try
                    {
                        // Set prefix in the actual database.
                        await pm.SetPrefixAsync(Context.Guild.Id, prefix);
                    }
                    catch (Exception e)
                    {
                        // Log the error so that it can be debugged
                        var log = Logger.GetLogger(this);
                        log.Warning($"Failed to store prefix for guild {Context.Guild.Name} ({Context.Guild.Id}): pfx: {prefix} Exception:", e);
                    }
                    return;
                }
            }

            // Send message
            eb.Description = reply.ToString();
            await ReplyAsync(embed : eb.Build());
        }