Ejemplo n.º 1
0
        public async Task <DiscordEmbedBuilder> CreateEmbedForProfileAsync(FoxCommandContext ctx, string username)
        {
            var region  = ctx.DatabaseContext.Channel.Region;
            var profile = await Api.SummonerV4.GetBySummonerNameAsync(region, username);

            var championMasteryScore = await Api.ChampionMasteryV4.GetChampionMasteryScoreAsync(region, profile.Id);

            var championMasteries = (await Api.ChampionMasteryV4.GetAllChampionMasteriesAsync(region, profile.Id)).Take(5);

            var embed = new DiscordEmbedBuilder
            {
                Author = new DiscordEmbedBuilder.EmbedAuthor
                {
                    Name = $"League of Legends - Profile [{region.Key}]"
                },
                Color        = ConfigurationService.EmbedColor,
                Description  = "This page shows your basic `League of Legends` summoner profile informations.",
                ThumbnailUrl = $"https://ddragon.leagueoflegends.com/cdn/9.5.1/img/profileicon/{profile.ProfileIconId}.png"
            };

            embed.AddField("Username", profile.Name, true);
            embed.AddField("Level", profile.SummonerLevel.ToString(), true);
            embed.AddField($"Top 5 Champions ({championMasteryScore} of champion mastery score)", string.Join("\n", championMasteries.Select(x => $"{(x.ChestGranted ? ChestEmote.ToString() : Red.ToString())} Lv.`{x.ChampionLevel}` | `{((Champion)x.ChampionId).Name()}` - `{x.ChampionPoints.ToString("N0")}` pts {(x.ChampionLevel >= 5 && x.ChampionLevel < 7 ? $" - `{x.TokensEarned}/{x.ChampionLevel - 3}` tokens" : "")}")), true);

            return(embed);
        }
Ejemplo n.º 2
0
 public PaginatorService(FoxCommandContext ctx, ImmutableArray <Page> pages)
 {
     Client         = ctx.Client;
     Channel        = ctx.Channel;
     User           = ctx.User;
     Pages          = pages;
     _cursor        = 0;
     _stopped       = false;
     _hasPermission = ctx.Guild.CurrentMember.PermissionsIn(ctx.Channel).HasPermission(Permissions.ManageMessages) || ctx.Guild.CurrentMember.PermissionsIn(ctx.Channel).HasPermission(Permissions.Administrator);
 }
Ejemplo n.º 3
0
        private async Task OnMessageReceivedAsync(MessageCreateEventArgs e)
        {
            if (e.Author.IsBot)
            {
                return;
            }

            try
            {
                var ctxBase = new FoxContext(e, _services);

                _ = Task.Run(() => ExecuteReminderAsync(e));
                _ = Task.Run(() => ExecuteCustomCommandAsync(ctxBase));

                if (ctxBase.DatabaseContext.User.IsBlacklisted)
                {
                    return;
                }

                var prefixes = ctxBase.DatabaseContext.Guild.Prefixes;

                if (ctxBase.Message.MentionedUsers.Contains(ctxBase.Client.CurrentUser) && ctxBase.Message.Content.Contains("prefix", StringComparison.OrdinalIgnoreCase))
                {
                    await ctxBase.RespondAsync($"Prefixes for this guild: {string.Join(", ", prefixes.Select(x => $"`{x}`"))}");
                }

                if (!CommandUtilities.HasAnyPrefix(e.Message.Content, prefixes, StringComparison.OrdinalIgnoreCase,
                                                   out var prefix, out var content))
                {
                    return;
                }

                var context = new FoxCommandContext(ctxBase, prefix);
                var result  = await _commands.ExecuteAsync(content, context, _services);

                if (result.IsSuccessful)
                {
                    return;
                }

                await HandleCommandErroredAsync(result, context);
            }
            catch (Exception ex)
            {
                _logger.Print(LogLevel.Critical, "Handler", ex.StackTrace);
            }
        }
Ejemplo n.º 4
0
        private async Task HandleCommandErroredAsync(IResult result, FoxCommandContext ctx)
        {
            if (result is CommandNotFoundResult)
            {
                string cmdName;
                var    toLev = "";
                var    index = 0;
                var    split = ctx.Message.Content.Substring(ctx.Prefix.Length).Split(_commands.Separator, StringSplitOptions.RemoveEmptyEntries);

                do
                {
                    toLev += (index == 0 ? "" : _commands.Separator) + split[index];

                    cmdName = toLev.Levenshtein(_commands);
                    index++;
                } while (string.IsNullOrWhiteSpace(cmdName) && index < split.Length);

                if (string.IsNullOrWhiteSpace(cmdName))
                {
                    return;
                }

                string cmdParams = null;
                while (index < split.Length)
                {
                    cmdParams += " " + split[index++];
                }

                var tryResult = await _commands.ExecuteAsync(cmdName + cmdParams, ctx, _services);

                if (tryResult.IsSuccessful)
                {
                    return;
                }

                await HandleCommandErroredAsync(tryResult, ctx);
            }

            var str = new StringBuilder();

            Command command = null;
            Module  module  = null;

            switch (result)
            {
            case ChecksFailedResult err:
                command = err.Command;
                module  = err.Module;
                str.AppendLine("The following check(s) failed:");
                foreach ((var check, var error) in err.FailedChecks)
                {
                    str.AppendLine($"[`{((FoxCheckBaseAttribute)check).Name}`]: `{error}`");
                }
                break;

            case TypeParseFailedResult err:
                command = err.Parameter.Command;
                str.AppendLine(err.Reason);
                break;

            case ArgumentParseFailedResult err:
                command = err.Command;
                str.AppendLine($"The syntax of the command `{command.FullAliases[0]}` was wrong.");
                break;

            case OverloadsFailedResult err:
                command = err.FailedOverloads.First().Key;
                str.AppendLine($"I can't find any valid overload for the command `{command.Name}`.");
                foreach (var overload in err.FailedOverloads)
                {
                    str.AppendLine($" -> `{overload.Value.Reason}`");
                }
                break;

            case ParameterChecksFailedResult err:
                command = err.Parameter.Command;
                module  = err.Parameter.Command.Module;
                str.AppendLine("The following parameter check(s) failed:");
                foreach ((var check, var error) in err.FailedChecks)
                {
                    str.AppendLine($"[`{check.Parameter.Name}`]: `{error}`");
                }
                break;

            case ExecutionFailedResult _:     //this should be handled in the CommandErrored event or in the FoxResult case.
            case CommandNotFoundResult _:     //this is handled at the beginning of this method with levenshtein thing.
                break;

            case FoxResult err:
                command = err.Command;     //ctx.Command is not null because a FoxResult is returned in execution step.
                str.AppendLine(err.Message);
                break;

            case CommandOnCooldownResult err:
                command = err.Command;
                var remainingTime = err.Cooldowns.OrderByDescending(x => x.RetryAfter).FirstOrDefault();
                str.AppendLine($"You're being rate limited! Please retry after {remainingTime.RetryAfter.Humanize()}.");
                break;

            default:
                str.AppendLine($"Unknown error: {result}");
                break;
            }

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

            var embed = new DiscordEmbedBuilder
            {
                Color = ConfigurationService.EmbedColor,
                Title = "Something went wrong!"
            };

            embed.WithFooter($"Type '{ctx.Prefix}help {command?.FullAliases[0] ?? ctx.Command?.FullAliases[0] ?? ""}' for more information.");

            embed.AddField(Formatter.Underline("Command/Module"), command?.Name ?? ctx.Command?.Name ?? module?.Name ?? "Unknown command...", true);
            embed.AddField(Formatter.Underline("Author"), ctx.User.FormatUser(), true);
            embed.AddField(Formatter.Underline("Error(s)"), str.ToString());

            _logger.Print(LogLevel.Error, "Fox", $"{ctx.User.Id} - {ctx.Guild.Id} ::> Command errored: {command?.Name ?? "-unknown command-"}");
            await ctx.RespondAsync("", false, embed.Build());
        }
Ejemplo n.º 5
0
        public async Task <List <PaginatorService.Page> > CreatePaginatorPagesForChampionMasteriesAsync(FoxCommandContext ctx, string username)
        {
            var region  = ctx.DatabaseContext.Channel.Region;
            var profile = await Api.SummonerV4.GetBySummonerNameAsync(region, username);

            var championMasteries = await Api.ChampionMasteryV4.GetAllChampionMasteriesAsync(region, profile.Id);

            var maxPage = championMasteries.Length + 1;

            var embed = new DiscordEmbedBuilder
            {
                Author = new DiscordEmbedBuilder.EmbedAuthor
                {
                    Name = $"League of Legends - Champion Masteries [{region.Key}]"
                },
                Color        = ConfigurationService.EmbedColor,
                Description  = "This is a paginated command. Use the arrows to switch from the different pages. They contain your champion masteries informations.\n\nAdd a reaction to the 🔠 Emoji and type your champion name to switch to its stats.",
                ThumbnailUrl = $"https://ddragon.leagueoflegends.com/cdn/9.5.1/img/profileicon/{profile.ProfileIconId}.png",
                Footer       = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = $"{username} | Paginator - Page 1/{maxPage}"
                }
            };

            var pages = new List <PaginatorService.Page>
            {
                new PaginatorService.Page {
                    Embed = embed.Build()
                }
            };

            embed.Description = "";

            var currentPage = 2;

            foreach (var championMastery in championMasteries)
            {
                var championIdentifier = ((Champion)championMastery.ChampionId).Identifier();

                embed.ClearFields();
                embed.ThumbnailUrl = $"http://ddragon.leagueoflegends.com/cdn/9.5.1/img/champion/{championIdentifier}.png";
                embed.Footer       = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = $"{username} | Paginator - Page {currentPage}/{maxPage}"
                };

                embed.AddField("Level", championMastery.ChampionLevel.ToString(), true);
                embed.AddField("Points", championMastery.ChampionPoints.ToString("N0"), true);
                embed.AddField("Chest", $"{(!championMastery.ChestGranted ? "Not" : "")} Granted", true);

                if (championMastery.ChampionLevel >= 5 && championMastery.ChampionLevel < 7)
                {
                    embed.AddField("Tokens", $"{championMastery.TokensEarned}/{championMastery.ChampionLevel - 3} tokens for next level.", true);
                }

                embed.AddField("Last play time", DateTimeOffset.FromUnixTimeMilliseconds(championMastery.LastPlayTime).ToString("G"), true);

                currentPage++;

                pages.Add(new PaginatorService.Page {
                    Embed = embed.Build(), Identifier = championIdentifier
                });
            }

            return(pages);
        }
Ejemplo n.º 6
0
        public async Task <List <PaginatorService.Page> > CreatePaginatorPagesForSummonerLeaguesAsync(FoxCommandContext ctx, string username)
        {
            var region  = ctx.DatabaseContext.Channel.Region;
            var profile = await Api.SummonerV4.GetBySummonerNameAsync(region, username);

            var leagues = await Api.LeagueV4.GetAllLeaguePositionsForSummonerAsync(region, profile.Id);

            var maxPage = leagues.Length + 1;

            var embed = new DiscordEmbedBuilder
            {
                Author = new DiscordEmbedBuilder.EmbedAuthor
                {
                    Name = $"League of Legends - Summoner Leagues [{region.Key}]"
                },
                Description  = "This is a paginated command. Use the arrows to switch from the different pages. They contain your different leagues informations.\n\nThe trophy emoji mean you've been in this league for 100 games. The fire emoji mean you're on a win streak. The NEW emoji mean you're new to this league.",
                Color        = ConfigurationService.EmbedColor,
                ThumbnailUrl = $"https://ddragon.leagueoflegends.com/cdn/9.5.1/img/profileicon/{profile.ProfileIconId}.png",
                Footer       = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = $"{username} | Paginator - Page 1/{maxPage}"
                }
            };

            var pages = new List <PaginatorService.Page>
            {
                new PaginatorService.Page {
                    Embed = embed.Build()
                }
            };

            embed.Description = "";

            var currentPage = 2;

            foreach (var league in leagues)
            {
                embed.ClearFields();

                embed.ThumbnailUrl = $"https://riot.alnmrc.com/emblems/{league.Tier}.png";
                embed.Footer       = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = $"{username} | Paginator - Page {currentPage}/{maxPage}"
                };

                embed.AddField("League Name", league.LeagueName, true);
                embed.AddField("Queue Type", league.QueueType, true);

                embed.AddField("Tier", $"{league.Tier} {league.Rank} [{league.LeaguePoints} LP]\n{league.Wins}W {league.Losses}D\nWin Ratio {Math.Round((double)league.Wins / (league.Wins + league.Losses), 2) * 100}%", true);
                embed.AddField("Extra", $"{(league.Veteran ? Trophy : BlackTrophy)}, {(league.HotStreak ? Fire : BlackFire)}, {(league.FreshBlood ? New : BlackNew)}{(league.Inactive ? "\n\nYou're inactive. Warning, you are able to lose some LP/Tier/Ranks." : "")}", true);

                if (league.MiniSeries != null)
                {
                    embed.AddField($"Serie Progress (BO{league.MiniSeries.Target})", $"{league.MiniSeries.Progress}");
                }

                currentPage++;

                pages.Add(new PaginatorService.Page {
                    Embed = embed.Build()
                });
            }

            return(pages);
        }