Beispiel #1
0
        public async Task HelpAsync()
        {
            var modules = await Task.WhenAll(_commands.GetAllModules().Where(x => !x.Attributes.Any(y => y is HiddenAttribute) && x.Parent is null && x.Aliases.Count > 0).Select(async x =>
            {
                var result = await x.RunChecksAsync(Context);
                return(result.IsSuccessful ? x : null);
            }).Where(x => x != null));

            var commands = (await Task.WhenAll(_commands.GetAllCommands().Where(x => !x.Attributes.Any(y => y is HiddenAttribute) && x.Module.Aliases.Count == 0).Select(async x =>
            {
                var result = await x.RunChecksAsync(Context);
                return(result.IsSuccessful ? x : null);
            }))).Where(x => x != null && x.Module.Parent is null).DistinctBy(x => x.Name).ToArray();

            var embed = new LocalEmbedBuilder
            {
                Title       = "Help",
                Description = "This embed contains a list of every available modules. If you want to see every command of a module, use `!help <module>`.",
                Footer      = new LocalEmbedFooterBuilder
                {
                    Text = $"{modules.Length} modules and {commands.Length} commands available in this context."
                }
            };

            embed.AddField("Modules", string.Join(", ", modules.Select(x => $"`{x.Name}`")));
            embed.AddField("Commands", string.Join(", ", commands.Select(x => $"`{x.Name}`")));

            await ReplyAsync(embed : embed.Build());
        }
Beispiel #2
0
        public async Task <LocalEmbedBuilder> CreateCommandEmbedAsync(Command command, DiscordCommandContext context)
        {
            var embed = new LocalEmbedBuilder
            {
                Title       = "Command information",
                Description =
                    $"{Markdown.Code(command.FullAliases.First())}: {command.Description ?? "No description provided."}",
                Color = Color.Pink
            };

            if (command.Remarks != null)
            {
                embed.Description += " " + command.Remarks;
            }

            if (command.FullAliases.Count > 1)
            {
                embed.AddField("Aliases", string.Join(", ", command.FullAliases.Skip(1)), true);
            }

            if (command.Parameters.Count > 0)
            {
                embed.AddField("Parameters",
                               string.Join("\n", command.Parameters.Select(p => FormatParameter(context, p))));
            }

            if (command.CustomArgumentParserType == null)
            {
                var cExecString =
                    $"{context.Prefix}{command.FullAliases.First()} {string.Join(" ", command.Parameters.Select(a => $"{(a.IsOptional ? "[" : "{")}{a.Name}{(a.IsOptional ? "]" : "}")}"))}";
                embed.AddField("Usage", cExecString);
            }
Beispiel #3
0
        public async Task WordSearchAsync(string word)
        {
            var response = await _search.GetResponseAsync($"https://jisho.org/api/v1/search/words?keyword={word}").ConfigureAwait(false);

            var result = JsonConvert.DeserializeObject <JObject>(response);

            var embed = new LocalEmbedBuilder()
                        .WithTitle($"Jisho:")
                        .WithDescription($"Word: {result["data"][0]["japanese"][0]["word"]}\n(Furigana: `{result["data"][0]["japanese"][0]["reading"]}`)")
                        .AddField("JLPT Level", result["data"][0]["jlpt"][0], true);

            StringBuilder englishDefinitions = new StringBuilder();

            foreach (var entry in result["data"][0]["senses"][0]["english_definitions"])
            {
                englishDefinitions.Append($"{entry}, ");
            }

            StringBuilder speechParts = new StringBuilder();

            foreach (var entry in result["data"][0]["senses"][0]["parts_of_speech"])
            {
                speechParts.Append($"{entry}, ");
            }

            embed.AddField("English Meaning", englishDefinitions);
            embed.AddField("Part of Speech", speechParts, true);

            await Context.Message.Channel.EmbedAsync(embed).ConfigureAwait(false);
        }
        public static LocalEmbedBuilder GetTranslationEmbed(TranslateResponse result, IUserMessage message)
        {
            if (result.TranslateResult == null)
            {
                return(null);
            }

            var embed = new LocalEmbedBuilder().WithAuthor(message.Author);

            embed.AddField($"Original Message [{result.TranslateResult.SourceLanguage}]", result.TranslateResult.SourceText.FixLength());
            embed.AddField($"Translated Message [{result.TranslateResult.DestinationLanguage}]", result.TranslateResult.TranslatedText.FixLength());

            if (message is RestUserMessage restMsg)
            {
                embed.AddField("Original", $"[Original](https://discordapp.com/channels/{restMsg.GuildId?.RawValue.ToString() ?? "@me"}/{restMsg.ChannelId.RawValue}/{message.Id.RawValue}/)");
            }
            else if (message is CachedUserMessage cMsg)
            {
                var gid = cMsg.Guild == null ? "@me" : cMsg.Guild.Id.RawValue.ToString();
                embed.AddField("Original", $"[Original](https://discordapp.com/channels/{gid}/{cMsg.Channel.Id.RawValue}/{message.Id.RawValue}/)");
            }

            embed.Color = Color.Green;
            return(embed);
        }
Beispiel #5
0
        public async Task MasteriesAsync(Region region, [Remainder] string summonerName)
        {
            summonerName ??= DbContext.User.LeagueProfile.Username;

            if (string.IsNullOrWhiteSpace(summonerName))
            {
                await RespondEmbedAsync("You need to specify a nickname or set yours up.");

                return;
            }

            var summoner = await _riot.Summoner.GetSummonerByNameAsync(region, summonerName);

            if (summoner is null)
            {
                await RespondEmbedAsync("Unknown summoner. Try another region.");

                return;
            }

            var versions = await _staticEndpoints.Versions.GetAllAsync();

            var champions = await _staticEndpoints.Champions.GetAllAsync(versions.First());

            var masteries = await _riot.ChampionMastery.GetChampionMasteriesAsync(region, summoner.Id);

            var maxPage     = masteries.Count;
            var currentPage = 1;
            var pages       = new List <Page>();

            foreach (var mastery in masteries)
            {
                var page = new Page {
                    Identifier = champions.Keys[(int)mastery.ChampionId]
                };

                var embed = new LocalEmbedBuilder
                {
                    Color        = Color.Goldenrod,
                    Description  = $"Mastery for champion {page.Identifier}",
                    ThumbnailUrl =
                        $"http://ddragon.leagueoflegends.com/cdn/{versions.First()}/img/champion/{page.Identifier}.png"
                };
                embed.WithFooter($"{summonerName} | Paginator - Page {currentPage}/{maxPage}");

                embed.AddField("Level", mastery.ChampionLevel, true);
                embed.AddField("Points", mastery.ChampionPoints.ToString("N0"), true);
                embed.AddField("Chest", $"{(!mastery.ChestGranted ? "Not" : "")} granted", true);
                embed.AddField("Last play time", mastery.LastPlayTime.ToString("G"), true);

                page.Embed = embed.Build();

                currentPage++;

                pages.Add(page);
            }

            await PaginateAsync(pages.ToImmutableArray());
        }
Beispiel #6
0
        private Task OnCommandExecutionFailed(CommandExecutionFailedEventArgs e)
        {
            var ctx = (AatroxCommandContext)e.Context;

            _logger.Error($"Command errored: {e.Context.Command.Name} by {ctx.User.Id} in {ctx.Guild.Id}", e.Result.Exception);

            var str = new StringBuilder();

            switch (e.Result.Exception)
            {
            case DiscordHttpException ex when ex.HttpStatusCode == HttpStatusCode.Unauthorized:
                str.AppendLine("I don't have enough power to perform this action. (please check that the hierarchy of the bot is correct)");
                break;

            case DiscordHttpException ex when ex.HttpStatusCode == HttpStatusCode.BadRequest:
                str.AppendLine($"The requested action has been stopped by Discord: `{ex.Message}`");
                break;

            case DiscordHttpException ex:
                str.AppendLine($":angry: | Something bad happened: [{ex.HttpStatusCode}] {ex.Message}");
                break;

            case ArgumentException ex:
                str.AppendLine($"{ex.Message}\n");
                str.AppendLine($"Are you sure you didn't fail when typing the command? Please do `{ctx.Prefix}help {e.Result.Command.FullAliases[0]}`");
                break;

            default:
                str.AppendLine($"{e.Result.Exception.GetType()} occured.");
                str.AppendLine($"{e.Result.Exception.Message}");
                str.AppendLine($"{e.Result.Exception.StackTrace}");
                _logger.Error($"{e.Result.Exception.GetType()} occured.", e.Result.Exception);
                break;
            }

            if (str.Length == 0)
            {
                return(Task.CompletedTask);
            }

            var embed = new LocalEmbedBuilder
            {
                Color = _configuration.DefaultEmbedColor,
                Title = "Something went wrong!"
            };

            embed.AddField("__Command__", e.Result.Command.Name, true);
            embed.AddField("__Author__", ctx.User.FullName(), true);
            embed.AddField("__Error(s)__", str.ToString());
            embed.WithFooter($"Type '{ctx.Prefix}help {ctx.Command.FullAliases[0].ToLowerInvariant()}' for more information.");

            return(ctx.Channel.SendMessageAsync("", false, embed.Build()));
        }
Beispiel #7
0
        public async Task HandleAsync(MemberUpdatedEventArgs args)
        {
            var oldMember = args.OldMember;
            var newMember = args.NewMember;

            using var ctx = new AdminDatabaseContext(_provider);
            var language = (await ctx.GetOrCreateGuildAsync(args.NewMember.Guild.Id)).Language;
            var builder  = new LocalEmbedBuilder()
                           .WithSuccessColor()
                           .WithDescription(newMember.Format(false))
                           .WithTimestamp(DateTimeOffset.UtcNow);

            CachedTextChannel channel = null;

            // nickname
            if (!(newMember.Nick ?? string.Empty).Equals(oldMember.Nick ?? string.Empty,
                                                         StringComparison.OrdinalIgnoreCase))
            {
                channel = await ctx.GetLoggingChannelAsync(oldMember.Guild.Id, LogType.NicknameUpdate);

                builder.WithTitle(_localization.Localize(language, "logging_member_nickname"))
                .AddField(_localization.Localize(language, "logging_member_prevnick"),
                          oldMember.Nick?.Sanitize() ??
                          Markdown.Italics(_localization.Localize(language, "logging_member_noprevnick")))
                .AddField(_localization.Localize(language, "logging_member_newnick"),
                          newMember.Nick?.Sanitize() ??
                          Markdown.Italics(_localization.Localize(language, "logging_member_nonewnick")));
            }
            // role update
            else if (newMember.Roles.Count != oldMember.Roles.Count)
            {
                channel = await ctx.GetLoggingChannelAsync(oldMember.Guild.Id, LogType.UserRoleUpdate);

                var removedRoles = oldMember.Roles.Values.Where(x => !newMember.Roles.ContainsKey(x.Id)).ToList();
                var addedRoles   = newMember.Roles.Values.Where(x => !oldMember.Roles.ContainsKey(x.Id)).ToList();

                builder.WithTitle(_localization.Localize(language, "logging_member_roleupdate"));

                if (addedRoles.Count > 0)
                {
                    builder.AddField(_localization.Localize(language, "logging_member_addedroles"),
                                     string.Join('\n', addedRoles.Select(x => x.Format(false))));
                }

                if (removedRoles.Count > 0)
                {
                    builder.AddField(_localization.Localize(language, "logging_member_removedroles"),
                                     string.Join('\n', removedRoles.Select(x => x.Format(false))));
                }
            }

            if (channel is { })
        public static LocalEmbedBuilder GetModuleHelp(Module module)
        {
            if (module.Commands.Count == 0)
            {
                return(new LocalEmbedBuilder()
                       .WithTitle(module.FullAliases.FirstOrDefault() ?? module.Aliases.FirstOrDefault() ?? module.Name));
            }
            else if (module.Commands.Count <= 25)
            {
                var commandInfos = module.Commands.Select(x => GetCommandInfoField(x));
                var builder      = new LocalEmbedBuilder();
                foreach (var info in commandInfos)
                {
                    builder.AddField(info);
                }
                builder.Description = GetModuleInfoDescription(module);

                // TODO: Split based on max embed length (or x amount of fields + specific max length)
                return(builder
                       .WithTitle(module.FullAliases.FirstOrDefault() ?? module.Aliases.FirstOrDefault() ?? module.Name));
            }
            else
            {
                var commandInfos = module.Commands.Select(x => GetCommandHelp(x));

                // TODO: Split based on max embed length (or x amount of fields + specific max length)
                return(new LocalEmbedBuilder()
                       .WithDescription(string.Join("\n", commandInfos)).WithTitle(module.FullAliases.First()));
            }
        }
Beispiel #9
0
        public async Task ProfileAsync()
        {
            var id          = Context.User.Id;
            var color       = Color.Red;
            var description = "You are not registered!";
            var embed       = new LocalEmbedBuilder()
                              .WithTitle("User profile");
            var player = ContrackerService.Contracker
                         .GetPlayer(discordId: id.ToString());

            if (player != null)
            {
                description = "You are gamer.";
                color       = Color.Green;
                var steamname = SteamService.GetSteamName(player.Steam);
                embed.AddField("Discord", Discord.MentionUser(Context.User))
                .AddField("Steam", $"[{steamname}](https://steamcommunity.com/profiles/{player.Steam})")
                .AddField("Total CP", player.Cp)
                .AddField("Stars", player.Stars);
            }

            await ReplyAsync(embed : embed
                             .WithDescription(description)
                             .WithColor(color)
                             .Build()).ConfigureAwait(true);
        }
Beispiel #10
0
        public async Task EvalAsync([Remainder] string rawCode)
        {
            var code            = CommandHelper.GetCode(rawCode);
            var sw              = Stopwatch.StartNew();
            var script          = CSharpScript.Create(code, CommandHelper.RoslynScriptOptions, typeof(RoslynCommandContext));
            var diagnostics     = script.Compile();
            var compilationTime = sw.ElapsedMilliseconds;

            if (diagnostics.Any(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error))
            {
                var builder = new LocalEmbedBuilder {
                    Title       = "Compilation Failure",
                    Color       = Color.Red,
                    Description = $"Compilation took {compilationTime}ms but failed due to..."
                };
                foreach (var diagnostic in diagnostics)
                {
                    var message = diagnostic.GetMessage();
                    builder.AddField(diagnostic.Id,
                                     message.Substring(0, Math.Min(500, message.Length)));
                }

                await ReplyAsync(embed : builder.Build());

                return;
            }

            var context = new RoslynCommandContext(Context);
            var result  = await script.RunAsync(context);

            sw.Stop();
            await ReplyAsync(result.ReturnValue.ToString());
        }
Beispiel #11
0
        public async Task HandleAsync(MessageDeletedEventArgs args)
        {
            if (!(args.Channel is CachedTextChannel channel) ||
                !args.Message.HasValue || args.Message.Value.Author.IsBot) // TODO: What to do when message doesn't have value, other than ignore
            {
                return;
            }

            using var ctx = new AdminDatabaseContext(_provider);
            var guild = await ctx.GetOrCreateGuildAsync(channel.Guild.Id);

            if (!(await ctx.GetLoggingChannelAsync(channel.Guild.Id, LogType.MessageDelete) is { } logChannel))
            {
                return;
            }

            var builder = new LocalEmbedBuilder()
                          .WithErrorColor()
                          .WithTitle(_localization.Localize(guild.Language, "logging_message_delete", channel.Tag))
                          .WithDescription(args.Message.Value.Author.Format(false))
                          .AddField(_localization.Localize(guild.Language, "info_id"), args.Message.Id)
                          .WithTimestamp(DateTimeOffset.UtcNow);

            if (!string.IsNullOrWhiteSpace(args.Message.Value.Content))
            {
                builder.AddField(_localization.Localize(guild.Language, "info_content"),
                                 args.Message.Value.Content.TrimTo(1024, true));
            }

            if (channel.Guild.CurrentMember.Permissions.ViewAuditLog)
            {
                await Task.Delay(TimeSpan.FromSeconds(1));

                var logs = await channel.Guild.GetAuditLogsAsync <RestMessagesDeletedAuditLog>(10);

                if (logs.FirstOrDefault(x =>
                                        x.TargetId == args.Message.Value.Author.Id && x.ChannelId == args.Channel.Id) is { } log)
                {
                    var moderator = await args.Client.GetOrDownloadUserAsync(log.ResponsibleUserId);

                    builder.WithTitle(_localization.Localize(guild.Language, "logging_message_delete_moderator", moderator.Tag, channel.Tag));
                }
            }

            if (_temporaryImages.Remove(args.Message.Id, out var attachment))
            {
                using (attachment)
                {
                    await logChannel.SendMessageAsync(attachment,
                                                      embed : builder
                                                      .WithImageUrl($"attachment://{attachment.FileName}")
                                                      .Build());
                }

                return;
            }

            await logChannel.SendMessageAsync(embed : builder.Build());
        }
Beispiel #12
0
        public async Task HelpAsync()
        {
            var embed = new LocalEmbedBuilder
            {
                Color  = RiasUtilities.ConfirmColor,
                Author = new LocalEmbedAuthorBuilder
                {
                    Name    = GetText(Localization.HelpTitle, RiasBot.CurrentUser.Name, Rias.Version),
                    IconUrl = RiasBot.CurrentUser.GetAvatarUrl()
                },
                Footer = new LocalEmbedFooterBuilder().WithText("© 2018-2020 Copyright: Koneko#0001")
            };

            embed.WithDescription(GetText(Localization.HelpInfo, Context.Prefix));

            var          links     = new StringBuilder();
            const string delimiter = " • ";

            if (!string.IsNullOrEmpty(Credentials.OwnerServerInvite))
            {
                var ownerServer = RiasBot.GetGuild(Credentials.OwnerServerId);
                links.Append(delimiter)
                .Append(GetText(Localization.HelpSupportServer, ownerServer.Name, Credentials.OwnerServerInvite))
                .Append("\n");
            }

            if (links.Length > 0)
            {
                links.Append(delimiter);
            }
            if (!string.IsNullOrEmpty(Credentials.Invite))
            {
                links.Append(GetText(Localization.HelpInviteMe, Credentials.Invite)).Append("\n");
            }

            if (links.Length > 0)
            {
                links.Append(delimiter);
            }
            if (!string.IsNullOrEmpty(Credentials.Website))
            {
                links.Append(GetText(Localization.HelpWebsite, Credentials.Website)).Append("\n");
            }

            if (links.Length > 0)
            {
                links.Append(delimiter);
            }
            if (!string.IsNullOrEmpty(Credentials.Patreon))
            {
                links.Append(GetText(Localization.HelpDonate, Credentials.Patreon)).Append("\n");
            }

            embed.AddField(GetText(Localization.HelpLinks), links.ToString());
            await ReplyAsync(embed);
        }
Beispiel #13
0
        public async Task <DiscordResponseCommandResult> EvalAsync([Remainder] string code)
        {
            code = SanityUtilities.ExtractCode(code);
            var script       = CSharpScript.Create(code, _options, typeof(Globals));
            var compileTimer = Stopwatch.StartNew();
            var diagnostics  = script.Compile();

            compileTimer.Stop();
            var errors = diagnostics.Where(x => x.Severity == DiagnosticSeverity.Error).Select(x => $"Error {x.Id} at {x.Location.GetLineSpan()}\nMessage: {x.GetMessage()}").ToArray();

            if (errors.Length != 0)
            {
                var embed = new LocalEmbedBuilder()
                {
                    Title       = "Script failed to compile",
                    Description = string.Join("\n", errors),
                    Color       = Disqord.Color.Red
                };

                return(Reply(embed));
            }

            compileTimer.Stop();
            var executionTimer = Stopwatch.StartNew();
            var result         = await script.RunAsync(new Globals()
            {
                Bot     = Context.Bot,
                Context = Context
            });

            executionTimer.Stop();


            var resultEmbed = new LocalEmbedBuilder()
            {
                Title  = "Evaluation sucessful",
                Color  = Disqord.Color.GreenYellow,
                Footer = new LocalEmbedFooterBuilder()
                {
                    Text = $"Compilation Time: {compileTimer.ElapsedMilliseconds} ms | Execution Time: {executionTimer.ElapsedMilliseconds} ms"
                }
            };

            var value = result.ReturnValue;

            if (value is null)
            {
                resultEmbed.Description = "null";
            }
            else
            {
                resultEmbed.AddField(value.GetType().ToString(), value);
            }

            return(Reply(resultEmbed));
        }
Beispiel #14
0
        public static async Task HandleMessageDeletedAsync(VerificationBot bot, MessageDeletedEventArgs e)
        {
            if (e.GuildId == null || e.Message == null)
            {
                return;
            }

            LocalEmbedBuilder embed = null;

            foreach (ConfigChannel channel in bot.Config
                     .GetOrAddGuild(e.GuildId.Value).Channels.Values
                     .Where(c => c.ChangelogChannels.Contains(e.ChannelId)))
            {
                if (embed == null)
                {
                    embed = new LocalEmbedBuilder()
                            .WithTitle("Message deleted")
                            .AddField("Channel", $"<#{e.Message.ChannelId}>")
                            .AddField("Author", e.Message.Author.Mention);

                    if (e.Message.Content.Length > 0)
                    {
                        embed.AddField("Content", e.Message.Content);
                    }

                    if (e.Message.Attachments.Count > 0)
                    {
                        embed.AddField("Attachments", string.Join('\n', e.Message.Attachments.Select(a => a.Url)));
                    }
                }

                if (await bot.GetChannelAsync(channel.GuildId, channel.Id) is ITextChannel textChannel)
                {
                    await textChannel.SendMessageAsync
                    (
                        new LocalMessageBuilder()
                        .WithEmbed(embed)
                        .Build()
                    );
                }
            }
        }
Beispiel #15
0
        public async Task LanguagesAsync()
        {
            var embed = new LocalEmbedBuilder();

            foreach (var languageGroup in TranslateService.GetAvailableLanguages().GroupBy(x => x.BaseCulture.Name.ToCharArray().First()).OrderBy(x => x.Key))
            {
                var resContent = languageGroup.Select(x => $"`{x.BaseCulture.Name}` - **{x.BaseCulture.DisplayName}** {x.BaseCulture.NativeName}").ToArray();
                embed.AddField(languageGroup.Key.ToString(CultureInfo.CurrentCulture), string.Join("\n", resContent));
            }

            await ReplyAsync("", false, embed.Build());
        }
Beispiel #16
0
        private LocalEmbedBuilder CreateModuleHelpEmbed(
            Module module,
            string commandNamesString,
            string commandAliasesString,
            string submoduleString)
        {
            var helpEmbedBuilder = new LocalEmbedBuilder {
                Color  = Constants.EspeonColour,
                Title  = $"{module.Name} Help",
                Author = new LocalEmbedAuthorBuilder {
                    IconUrl = Context.Member.GetAvatarUrl(),
                    Name    = Context.Member.DisplayName
                },
                ThumbnailUrl = Context.Guild.CurrentMember.GetAvatarUrl(),
                Description  = module.Description,
                Footer       = new LocalEmbedFooterBuilder {
                    Text = $"Execute \"{GetPrefix()} command\" to view help for that specific command"
                }
            };

            if (module.Parent != null)
            {
                helpEmbedBuilder.AddField("Parent Module", Markdown.Code(module.Parent.Name));
            }

            if (module.FullAliases.Count > 0)
            {
                helpEmbedBuilder.AddField("Module Aliases", string.Join(", ", module.FullAliases.Select(Markdown.Code)));
            }

            helpEmbedBuilder.AddField("Command Names", commandNamesString);
            helpEmbedBuilder.AddField("Command Aliases", commandAliasesString);

            if (submoduleString.Length > 0)
            {
                helpEmbedBuilder.AddField("Submodules", submoduleString);
            }

            return(helpEmbedBuilder);
        }
Beispiel #17
0
        public async Task HandleAsync(MessageUpdatedEventArgs args)
        {
            if (!(args.Channel is CachedTextChannel channel) ||
                !args.OldMessage.HasValue ||                                                            // TODO: What to do when message doesn't have value, other than ignore
                args.OldMessage.Value.Content?.Equals(args.NewMessage.Content ?? string.Empty) == true) // message content is identical
            {
                return;
            }

            using var ctx = new AdminDatabaseContext(_provider);
            var guild = await ctx.GetOrCreateGuildAsync(channel.Guild.Id);

            if (!(await ctx.GetLoggingChannelAsync(channel.Guild.Id, LogType.MessageUpdate) is { } logChannel))
            {
                return;
            }

            var builder = new LocalEmbedBuilder()
                          .WithErrorColor()
                          .WithTitle(_localization.Localize(guild.Language, "logging_message_update", channel.Tag))
                          .WithDescription(args.NewMessage.Author.Format(false))
                          .AddField(_localization.Localize(guild.Language, "info_id"), args.NewMessage.Id)
                          .WithTimestamp(DateTimeOffset.UtcNow);

            if (!string.IsNullOrWhiteSpace(args.OldMessage.Value.Content))
            {
                builder.AddField(_localization.Localize(guild.Language, "logging_message_update_oldcontent"),
                                 args.OldMessage.Value.Content.TrimTo(1024, true));
            }

            if (!string.IsNullOrWhiteSpace(args.NewMessage.Content))
            {
                builder.AddField(_localization.Localize(guild.Language, "logging_message_update_newcontent"),
                                 args.NewMessage.Content.TrimTo(1024, true));
            }

            await logChannel.SendMessageAsync(embed : builder.Build());
        }
        public async Task TopB()
        {
            var klenght     = Math.Min(Data.ImposterKings.Count, 25);
            var qlenght     = Math.Min(Data.ImposterQueens.Count, 25);
            var kingorder   = Data.ImposterKings.Take(klenght).OrderByDescending(x => x.count);
            var queensorder = Data.ImposterQueens.Take(qlenght).OrderByDescending(x => x.count);
            var eb          = new LocalEmbedBuilder();
            var sb          = new StringBuilder();

            foreach (var(id, count) in kingorder)
            {
                var user = Context.Guild.GetMember(id);
                sb.AppendLine($"{user.DisplayName}  {(Data.WhitelistedIds.Any(x => x == user.Id) ? $"has betrayed trust: {count} times " : "user is not whitelisted as imposter")}");
            }
            eb.AddField("Top Kings", sb.ToString(), true);
            sb.Clear();
            foreach (var(id, count) in queensorder)
            {
                var user = Context.Guild.GetMember(id);
                sb.AppendLine($"{user.DisplayName}  {(Data.WhitelistedIds.Any(x => x == user.Id) ? $"has betrayed trust: {count} times " : "user is not whitelisted as imposter")}");
            }
            eb.AddField("Top Queens", sb.ToString(), true);
            await ReplyAsync("", eb, LocalMentions.None);
        }
Beispiel #19
0
        public async Task Emojis()
        {
            using (var db = new DataContext())
            {
                var embed = new LocalEmbedBuilder();

                if (Context.Guild != null)
                {
                    var matches = db.TranslatePairs.Where(x => x.GuildId == Context.Guild.Id).ToArray().GroupBy(x => x.DestLang);
                    embed.Description = string.Join("\n", matches.Select(x => $"{x.Key}: {string.Join(" ", x.Select(p => p.Source))}")).FixLength(2047);
                }

                embed.AddField("Defaults", string.Join("\n", TranslateService.DefaultMap.Select(x => $"{x.LanguageString}: {string.Join(" ", x.EmoteMatches)}")));
                await ReplyAsync("", false, embed.Build());
            }
        }
Beispiel #20
0
        public async Task CommandsAsync([Remainder] string name)
        {
            var module = _commandService.GetAllModules().FirstOrDefault(m => m.Name.StartsWith(name, StringComparison.InvariantCultureIgnoreCase));

            if (module is null)
            {
                await ReplyErrorAsync(Localization.HelpModuleNotFound, Context.Prefix);

                return;
            }

            var isOwner = Context.User.Id == Credentials.MasterId;

            var modulesCommands = GetModuleCommands(module, isOwner);

            if (modulesCommands.Count == 0)
            {
                await ReplyErrorAsync(Localization.HelpModuleNotFound, Context.Prefix);

                return;
            }

            var commandsAliases = GetCommandsAliases(modulesCommands, Context.Prefix);

            var embed = new LocalEmbedBuilder
            {
                Color = RiasUtilities.ConfirmColor,
                Title = GetText(module.Parent != null ? Localization.HelpAllCommandsForSubmodule : Localization.HelpAllCommandsForModule, module.Name)
            }.AddField(module.Name, string.Join("\n", commandsAliases), true);

            foreach (var submodule in module.Submodules)
            {
                var submoduleCommands = GetModuleCommands(submodule, isOwner);
                if (submoduleCommands.Count == 0)
                {
                    continue;
                }

                var submoduleCommandsAliases = GetCommandsAliases(submoduleCommands, Context.Prefix);

                embed.AddField(submodule.Name, string.Join("\n", submoduleCommandsAliases), true);
            }

            embed.WithFooter(GetText(Localization.HelpCommandInfo, Context.Prefix));
            embed.WithCurrentTimestamp();
            await ReplyAsync(embed);
        }
            private async Task SendMessageAsync(CachedMember member, string moderationType, string fromWhere, string?reason)
            {
                var embed = new LocalEmbedBuilder
                {
                    Color        = RiasUtilities.ErrorColor,
                    Title        = GetText(moderationType),
                    ThumbnailUrl = member.GetAvatarUrl()
                }.AddField(GetText(Localization.CommonUser), member, true)
                .AddField(GetText(Localization.CommonId), member.Id, true)
                .AddField(GetText(Localization.AdministrationModerator), Context.User, true);

                if (!string.IsNullOrEmpty(reason))
                {
                    embed.AddField(GetText(Localization.CommonReason), reason, true);
                }

                var channel = Context.Channel;
                var guildDb = await DbContext.GetOrAddAsync(x => x.GuildId == Context.Guild !.Id, () => new GuildsEntity { GuildId = Context.Guild !.Id });
        public Task SendTargetRevocationEmbedAsync(RevocablePunishment punishment, IUser target,
                                                   LocalizedLanguage language)
        {
            var typeName = punishment.GetType().Name.ToLower();
            var builder  = new LocalEmbedBuilder().WithWarnColor()
                           .WithTitle(_localization.Localize(language, $"punishment_{typeName}") +
                                      $" - {_localization.Localize(language, "punishment_case", punishment.Id)}")
                           .WithDescription(_localization.Localize(language, $"punishment_{typeName}_revoke_description", Markdown.Bold(_client.GetGuild(punishment.GuildId).Name.Sanitize())))
                           .AddField(_localization.Localize(language, "title_reason"),
                                     punishment.RevocationReason ?? _localization.Localize(language, "punishment_noreason"))
                           .WithTimestamp(punishment.RevokedAt ?? DateTimeOffset.UtcNow);

            if (punishment is Mute channelMute && channelMute.ChannelId.HasValue)
            {
                builder.AddField(_localization.Localize(language, "punishment_mute_channel"),
                                 _client.GetGuild(punishment.GuildId).GetTextChannel(channelMute.ChannelId.Value).Mention);
            }

            return(target.SendMessageAsync(embed: builder.Build()));
        }
Beispiel #23
0
        public async Task ModulesAsync()
        {
            var embed = new LocalEmbedBuilder
            {
                Color  = RiasUtilities.ConfirmColor,
                Title  = GetText(Localization.HelpModulesListTitle),
                Footer = new LocalEmbedFooterBuilder().WithText(GetText(Localization.HelpModulesListFooter, Context.Prefix))
            };

            var isOwner = Context.User.Id == Credentials.MasterId;

            var modules = isOwner
                ? _commandService.GetAllModules()
                          .Where(m => m.Parent is null)
                          .OrderBy(m => m.Name)
                          .ToArray()
                : _commandService.GetAllModules()
                          .Where(m => m.Parent is null && m.Commands.All(c => !c.Checks.Any(x => x is OwnerOnlyAttribute)))
                          .OrderBy(m => m.Name)
                          .ToArray();

            foreach (var module in modules)
            {
                var fieldValue = "\u200B";
                if (module.Submodules.Count != 0)
                {
                    fieldValue = string.Join("\n", isOwner
                        ? module.Submodules
                                             .OrderBy(m => m.Name)
                                             .Select(x => x.Name)
                        : module.Submodules
                                             .Where(m => m.Commands.All(c => !c.Checks.Any(x => x is OwnerOnlyAttribute)))
                                             .OrderBy(m => m.Name)
                                             .Select(x => x.Name));
                }

                embed.AddField(module.Name, fieldValue, true);
            }

            await ReplyAsync(embed);
        }
        public async Task SendLoggingRevocationEmbedAsync(RevocablePunishment punishment, IUser target, IUser moderator,
                                                          CachedTextChannel logChannel, LocalizedLanguage language)
        {
            var typeName = punishment.GetType().Name.ToLower();
            var builder  = new LocalEmbedBuilder().WithWarnColor()
                           .WithTitle(_localization.Localize(language, $"punishment_{typeName}") +
                                      $" - {_localization.Localize(language, "punishment_case", punishment.Id)}")
                           .WithDescription(_localization.Localize(language, $"punishment_{typeName}_revoke_description_guild",
                                                                   $"**{target}** (`{target.Id}`)"))
                           .AddField(_localization.Localize(language, "title_reason"),
                                     punishment.RevocationReason ?? _localization.Localize(language, "punishment_noreason"))
                           .WithFooter(_localization.Localize(language, "punishment_moderator", moderator.Tag),
                                       moderator.GetAvatarUrl())
                           .WithTimestamp(punishment.RevokedAt ?? DateTimeOffset.UtcNow);

            if (punishment is Mute channelMute && channelMute.ChannelId.HasValue)
            {
                builder.AddField(_localization.Localize(language, "punishment_mute_channel"),
                                 _client.GetGuild(punishment.GuildId).GetTextChannel(channelMute.ChannelId.Value)?.Mention ?? "???");
            }

            await logChannel.SendMessageAsync(embed : builder.Build());
        }
Beispiel #25
0
        public async Task GlobalXpLeaderboardAsync(int page = 1)
        {
            page--;
            if (page < 0)
            {
                page = 0;
            }

            var xpLeaderboard = await DbContext.GetOrderedListAsync <UsersEntity, int>(x => x.Xp, true, (page * 15)..((page + 1) * 15));

            if (xpLeaderboard.Count == 0)
            {
                await ReplyErrorAsync(Localization.XpLeaderboardEmpty);

                return;
            }

            var embed = new LocalEmbedBuilder
            {
                Color = RiasUtilities.ConfirmColor,
                Title = GetText(Localization.XpLeaderboard)
            };

            var index = page * 15;

            foreach (var userDb in xpLeaderboard)
            {
                var user = (IUser)RiasBot.GetUser(userDb.UserId) ?? await RiasBot.GetUserAsync(userDb.UserId);

                embed.AddField($"{++index}. {user}",
                               $"{GetText(Localization.XpLevelX, RiasUtilities.XpToLevel(userDb.Xp, XpService.XpThreshold))} | {GetText(Localization.XpXp)} {userDb.Xp}",
                               true);
            }

            await ReplyAsync(embed);
        }
        public async ValueTask <AdminCommandResult> GetBackpackProfileAsync([Remainder] BackpackUser user)
        {
            var now     = DateTimeOffset.UtcNow;
            var builder = new LocalEmbedBuilder()
                          .WithSuccessColor()
                          .WithTitle(Localize("backpack_info_title", user.Name))
                          .WithThumbnailUrl(user.AvatarUrl.ToString())
                          .AddField(Localize("info_id"), user.Id)
                          .AddField(Localize("backpack_info_lastonline"),
                                    string.Join('\n', user.LastOnline.ToString("g", Context.Language.Culture),
                                                (now - user.LastOnline).HumanizeFormatted(Localization, Context.Language, TimeUnit.Second,
                                                                                          true)))
                          .AddField(Localize("backpack_info_flags"),
                                    user.Flags == BackpackUserFlags.None
                        ? Localize("info_none")
                        : user.Flags.Humanize(LetterCasing.Title));

            if (user.AmountDonated != default)
            {
                builder.AddField(Localize("backpack_info_donated"), $"${user.AmountDonated:F} USD");
            }

            if (user.PremiumMonthsGifted != default)
            {
                builder.AddField(Localize("backpack_info_premiumgifts"), user.PremiumMonthsGifted);
            }

            if (user.Trust.Negative != default || user.Trust.Positive != default)
            {
                var netTrust = user.Trust.Positive - user.Trust.Negative;

                builder.AddField(Localize("backpack_info_trust"),
                                 $"{(netTrust > 0 ? "+" : string.Empty)}{netTrust} (+{user.Trust.Positive}/-{user.Trust.Negative})");
            }

            var currencies = await BackpackClient.GetCurrenciesAsync();

            var inventoryValue = user.Inventory.Keys * currencies.CrateKey.Price.Value + user.Inventory.Metal +
                                 user.Inventory.Value;

            builder.AddField(Localize("backpack_info_worth"),
                             Localize("backpack_info_worth_text", (inventoryValue / currencies.CrateKey.Price.Value).ToString("F"),
                                      inventoryValue.ToString("F"),
                                      (inventoryValue * currencies.RefinedMetal.Price.Value).ToString("F")));


            if (!user.SiteBans.IsDefaultOrEmpty ||
                user.Flags.HasFlag(BackpackUserFlags.SteamCommunityBanned) ||
                user.Flags.HasFlag(BackpackUserFlags.SteamRepCaution) ||
                user.Flags.HasFlag(BackpackUserFlags.SteamRepScammer) ||
                user.Flags.HasFlag(BackpackUserFlags.SteamVACBanned) ||
                user.Flags.HasFlag(BackpackUserFlags.SteamEconomyBanned) ||
                user.Flags.HasFlag(BackpackUserFlags.ValveGameBanned))
            {
                builder.WithErrorColor()
                .WithFooter(Localize("backpack_info_caution",
                                     Markdown.Code($"{Context.Prefix}backpack bans <user>")));
            }


            return(CommandSuccess(embed: builder.Build()));
        }
        public static bool TryParseEmbed(string json, out LocalEmbedBuilder embed)
        {
            embed = new LocalEmbedBuilder();
            try
            {
                var embedDeserialized = JsonConvert.DeserializeObject <JsonEmbed>(json);

                var author      = embedDeserialized.Author;
                var title       = embedDeserialized.Title;
                var description = embedDeserialized.Description;

                var colorString = embedDeserialized.Color;
                var thumbnail   = embedDeserialized.Thumbnail;
                var image       = embedDeserialized.Image;
                var fields      = embedDeserialized.Fields;
                var footer      = embedDeserialized.Footer;
                var timestamp   = embedDeserialized.Timestamp;

                if (author != null)
                {
                    embed.WithAuthor(author);
                }

                if (!string.IsNullOrEmpty(title))
                {
                    embed.WithTitle(title);
                }

                if (!string.IsNullOrEmpty(description))
                {
                    embed.WithDescription(description);
                }

                if (!string.IsNullOrEmpty(colorString))
                {
                    embed.WithColor(HexToInt(colorString) ?? 0xFFFFFF);
                }

                if (!string.IsNullOrEmpty(thumbnail))
                {
                    embed.WithThumbnailUrl(thumbnail);
                }
                if (!string.IsNullOrEmpty(image))
                {
                    embed.WithImageUrl(image);
                }

                if (fields != null)
                {
                    foreach (var field in fields)
                    {
                        var fieldName   = field.Name;
                        var fieldValue  = field.Value;
                        var fieldInline = field.IsInline;

                        if (!string.IsNullOrEmpty(fieldName) && !string.IsNullOrEmpty(fieldValue))
                        {
                            embed.AddField(fieldName, fieldValue, fieldInline);
                        }
                    }
                }

                if (footer != null)
                {
                    embed.WithFooter(footer);
                }

                if (timestamp.HasValue)
                {
                    embed.WithTimestamp(timestamp.Value);
                }
                else if (embedDeserialized.WithCurrentTimestamp)
                {
                    embed.WithCurrentTimestamp();
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Beispiel #28
0
        protected override async Task <IUserMessage> InitialiseAsync()
        {
            var tempDict = new Dictionary <string, (Module Module, LocalEmbedBuilder Embed, string Title)>();

            foreach (var module in CommandService.GetAllModules())
            {
                if (module.Attributes
                    .FirstOrDefault(x => x.GetType()
                                    .Equals(typeof(HelpMetadataAttribute))) is HelpMetadataAttribute attMatch)
                {
                    var title = $"{attMatch.ButtonCode} {module.Name}";
                    if (!tempDict.TryAdd(
                            attMatch.ButtonCode,
                            (module, HelpService.GetModuleHelp(module).WithColor(attMatch.Color),
                             title)))
                    {
                        // TODO: warn about module being ignored due to duplicate button.
                    }
                }
            }

            var footerTitles = new List <string>
            {
                $"{HelpPageEmote} Help"
            };

            footerTitles.AddRange(tempDict.Values.Select(x => x.Title));
            var footerContent = string.Join(", ", footerTitles);
            var homeBuilder   = new LocalEmbedBuilder()
                                .WithTitle("Modules")
                                .WithColor(Color.Aqua)
                                .WithFooter(footerContent);

            foreach (var dPage in tempDict)
            {
                if (dPage.Value.Module.Commands.Count == 0)
                {
                    homeBuilder.AddField(new LocalEmbedFieldBuilder
                    {
                        Name  = dPage.Value.Title,
                        Value = "No Commands."
                    });
                }
                else
                {
                    homeBuilder.AddField(new LocalEmbedFieldBuilder
                    {
                        Name  = dPage.Value.Title,
                        Value = string.Join(", ", dPage.Value.Module.Commands.Select(c => '`' + c.Name + '`').Distinct())
                    });

                    pages.Add(dPage.Key, dPage.Value.Embed.WithFooter(footerContent).Build());
                }
            }

            homePage = homeBuilder.Build();

            var message = await Channel.SendMessageAsync("", false, homePage);

            await AddButtonAsync(new Button(new LocalEmoji(HelpPageEmote), x =>
            {
                return(Message.ModifyAsync(m => m.Embed = homePage));
            }));

            foreach (var page in pages)
            {
                await AddButtonAsync(new Button(new LocalEmoji(page.Key), x =>
                {
                    return(Message.ModifyAsync(m => m.Embed = page.Value));
                }));
            }

            return(message);
        }
        private async Task SendTargetEmbedAsync(Punishment punishment, IUser target, Punishment additionalPunishment, LocalizedLanguage language)
        {
            var typeName = punishment.GetType().Name.ToLower();
            var builder  = new LocalEmbedBuilder().WithErrorColor()
                           .WithTitle(_localization.Localize(language, $"punishment_{typeName}") +
                                      $" - {_localization.Localize(language, "punishment_case", punishment.Id)}")
                           .AddField(_localization.Localize(language, "title_reason"),
                                     punishment.Reason ?? _localization.Localize(language, "punishment_noreason"))
                           .WithTimestamp(punishment.CreatedAt);

            if (!(additionalPunishment is null))
            {
                builder.AddField(FormatAdditionalPunishment(additionalPunishment, language));
            }

            if (punishment is Warning)
            {
                using var ctx = new AdminDatabaseContext(_provider);

                var warningCount = await ctx.Punishments.OfType <Warning>().CountAsync(x =>
                                                                                       x.TargetId == target.Id && x.GuildId == punishment.GuildId && !x.RevokedAt.HasValue);

                builder.WithDescription(_localization.Localize(language, "punishment_warning_description",
                                                               Markdown.Bold(_client.GetGuild(punishment.GuildId).Name.Sanitize()),
                                                               Markdown.Bold(warningCount.ToOrdinalWords(language.Culture))));
            }
            else
            {
                builder.WithDescription(_localization.Localize(language, $"punishment_{typeName}_description",
                                                               _client.GetGuild(punishment.GuildId).Name));
            }

            if (punishment is RevocablePunishment revocable)
            {
                var field = new LocalEmbedFieldBuilder()
                            .WithName(_localization.Localize(language, "punishment_appeal"));

                switch (revocable)
                {
                case Ban ban:
                    field.WithValue(!ban.Duration.HasValue || ban.Duration.Value > TimeSpan.FromDays(1)
                            ? GetAppealInstructions()
                            : _localization.Localize(language, "punishment_tooshort",
                                                     ban.Duration.Value.Humanize(minUnit: TimeUnit.Minute, culture: language.Culture)));
                    break;

                case Mute mute:
                    field.WithValue(!mute.Duration.HasValue || mute.Duration.Value > TimeSpan.FromDays(1)
                            ? GetAppealInstructions()
                            : _localization.Localize(language, "punishment_tooshort",
                                                     mute.Duration.Value.Humanize(minUnit: TimeUnit.Minute, culture: language.Culture)));
                    break;

                default:
                    field = null;
                    break;
                }

                if (!(field is null))
                {
                    builder.AddField(field);
                }

                string GetAppealInstructions()
                {
                    return(_localization.Localize(language, "punishment_appeal_instructions",
                                                  Markdown.Code(punishment.Id.ToString()),
                                                  Markdown.Code($"{_config.DefaultPrefix}appeal {punishment.Id} [{_localization.Localize(language, "title_reason").ToLower()}]")));
                }
            }

            if (punishment is Mute channelMute && channelMute.ChannelId.HasValue)
            {
                builder.AddField(_localization.Localize(language, "punishment_mute_channel"),
                                 _client.GetGuild(punishment.GuildId).GetTextChannel(channelMute.ChannelId.Value).Mention);
            }

            if (punishment.Format != ImageFormat.Default)
            {
                builder.WithImageUrl($"attachment://attachment.{punishment.Format.ToString().ToLower()}");
                _ = target.SendMessageAsync(new LocalAttachment(punishment.Image,
                                                                $"attachment.{punishment.Format.ToString().ToLower()}"), embed: builder.Build());

                return;
            }

            _ = target.SendMessageAsync(embed: builder.Build());
        }
 public static LocalEmbedBuilder AddInlineCodeBlockField(this LocalEmbedBuilder eb, string name, object value)
 => eb.AddField(name, Markdown.CodeBlock("csharp", value.ToString()), true);