Example #1
0
        private static async Task <Message> GetLeaderboardMessageAsync(DatabaseContext dbContext, IConfigurationRoot configuration)
        {
            var users = await SharedLeaderboardManager.GetTopUsersAndTeams(dbContext, 20, configuration.GetValue <bool>("DynamicScoring"));

            var eb = new CustomEmbedBuilder();

            eb.WithTitle("Leaderboard");

            for (int i = 0; i < users.Count; i++)
            {
                if (users[i].IsTeam)
                {
                    eb.Description += $"\n**{i + 1}. {users[i].TeamName}** (team) - {users[i].Score} points";
                }
                else
                {
                    eb.Description += $"\n**{i + 1}. {users[i].WebsiteUser?.UserName ?? users[i].DiscordUsername}** - {users[i].Score} points";
                }
            }

            var builder = new ComponentBuilder().WithButton("Full Leaderboard", style: ButtonStyle.Link, url: "https://imaginaryctf.org/leaderboard");

            return(new Message {
                Embed = eb.Build(), MessageComponent = builder.Build(), Ephemeral = true
            });
        }
Example #2
0
        private static Embed GetHelpEmbed(CommandService commandService)
        {
            var eb = new CustomEmbedBuilder();

            eb.WithTitle("Available Commands");

            var mainCommandsNames = new string[] { "flag", "stats" };
            var mainCommands      = commandService.Commands.Where(x => mainCommandsNames.Contains(x.Name));

            eb.Description += "\n**Main Commands**";

            foreach (var command in mainCommands)
            {
                eb.Description += $"\n`.{command.Name}";
                foreach (var parameter in command.Parameters)
                {
                    if (parameter.IsOptional)
                    {
                        eb.Description += $" [{parameter.Name}]";
                    }
                    else
                    {
                        eb.Description += $" <{parameter.Name}>";
                    }
                }
                eb.Description += "`";
                var requirePermission = command.Preconditions.OfType <RequireUserPermissionAttribute>().FirstOrDefault();
                if (requirePermission != null)
                {
                    eb.Description += " :star:";
                }
                eb.Description += $"\n➜ {command.Summary}";
                var requireContext = command.Preconditions.OfType <RequireContextAttribute>().FirstOrDefault();
                if (requireContext != null)
                {
                    switch (requireContext.Contexts)
                    {
                    case ContextType.DM:
                        eb.Description += " (DMs only)";
                        break;

                    case ContextType.Guild:
                        eb.Description += " (Guild only)";
                        break;
                    }
                }
            }

            eb.Description += "\n\n**Other Commands**";

            foreach (var module in commandService.Modules)
            {
                eb.Description += $"\n`.help {module.Name}`";
            }

            eb.WithFooter("Starred commands require the user to have certain permissions");

            return(eb.Build());
        }
Example #3
0
        private static Embed GetAboutEmbed()
        {
            var eb = new CustomEmbedBuilder();

            eb.WithThumbnailUrl("https://cdn.discordapp.com/avatars/669798825765896212/572b97a2e8c1dc33265ac51679303c41.png?size=256");
            eb.WithTitle("About");
            eb.AddField("Author", "This bot was created by Et3rnos#6556");
            eb.AddField("Support", "If you want to support me you can visit my Patreon:\n<https://www.patreon.com/et3rnos>");
            return(eb.Build());
        }
Example #4
0
        private static async Task <Embed> GetStatsEmbedAsync(DiscordSocketClient client, DatabaseContext dbContext, IConfigurationRoot configuration, IUser user, User player)
        {
            bool isTeam         = player.Team != null;
            bool dynamicScoring = configuration.GetValue <bool>("DynamicScoring");

            SharedStatsManager.Stats stats;
            if (isTeam)
            {
                stats = await SharedStatsManager.GetTeamStats(dbContext, player.Team, dynamicScoring);
            }
            else
            {
                stats = await SharedStatsManager.GetStats(dbContext, player, dynamicScoring);
            }

            var solvedChallengesTitles   = stats.SolvedChallenges.Select(x => x.Challenge.Title).ToList();
            var unsolvedChallengesTitles = stats.UnsolvedChallenges.Select(x => x.Challenge.Title).ToList();

            var eb = new CustomEmbedBuilder();

            if (isTeam)
            {
                eb.WithTitle($"Stats for {player.Team.Name} (team)");
                eb.AddField("Score", $"{stats.Score} ({stats.Position}/{stats.PlayersCount})");
            }
            else
            {
                eb.WithTitle($"Stats for {user.Username}");
                eb.WithThumbnailUrl(user.GetAvatarUrl() ?? user.GetDefaultAvatarUrl());
                eb.AddField("Score", $"{stats.Score} ({stats.Position}/{stats.PlayersCount})");
            }

            if (solvedChallengesTitles.Count > 0)
            {
                eb.AddField("Solved Challenges", string.Join('\n', solvedChallengesTitles), true);
            }
            if (unsolvedChallengesTitles.Count > 0)
            {
                eb.AddField("Unsolved Challenges", string.Join('\n', unsolvedChallengesTitles), true);
            }

            return(eb.Build());
        }
Example #5
0
        private static Embed GetCategoryHelpEmbed(CommandService commandService, string category)
        {
            var module = commandService.Modules.FirstOrDefault(x => x.Name.ToLower() == category.ToLower());

            if (module == null)
            {
                return(null);
            }

            var eb = new CustomEmbedBuilder();

            eb.WithTitle("Available Commands");

            foreach (var command in module.Commands)
            {
                eb.Description += $"\n`.{command.Name}";
                foreach (var parameter in command.Parameters)
                {
                    if (parameter.IsOptional)
                    {
                        eb.Description += $" [{parameter.Name}]";
                    }
                    else
                    {
                        eb.Description += $" <{parameter.Name}>";
                    }
                }
                eb.Description += "`";
                var requirePermission = command.Preconditions.OfType <RequireUserPermissionAttribute>().FirstOrDefault();
                if (requirePermission != null)
                {
                    eb.Description += " :star:";
                }
                eb.Description += $"\n➜ {command.Summary}";
                var requireContext = command.Preconditions.OfType <RequireContextAttribute>().FirstOrDefault();
                if (requireContext != null)
                {
                    switch (requireContext.Contexts)
                    {
                    case ContextType.DM:
                        eb.Description += " (DMs only)";
                        break;

                    case ContextType.Guild:
                        eb.Description += " (Guild only)";
                        break;
                    }
                }
            }

            eb.WithFooter("Starred commands require the user to have certain permissions");

            return(eb.Build());
        }
Example #6
0
        public async Task Execute(IJobExecutionContext context)
        {
            Log.Information("Starting Challenge Release Job");

            SchedulerContext     schedulerContext = context.Scheduler.Context;
            DiscordSocketClient  client           = (DiscordSocketClient)schedulerContext.Get("client");
            IServiceScopeFactory scopeFactory     = (IServiceScopeFactory)schedulerContext.Get("scopeFactory");

            using var scope = scopeFactory.CreateScope();
            var dbContext = scope.ServiceProvider.GetService <DatabaseContext>();

            var config = dbContext.Configuration.FirstOrDefault();

            if (config == null || config.ChallengeReleaseChannelId == 0)
            {
                Log.Information("Aborting Challenge Release Job because some configuration values are not defined");
                return;
            }

            var channel = client.GetGuild(config.GuildId).GetTextChannel(config.ChallengeReleaseChannelId);

            var lastChall = await dbContext.Challenges.AsAsyncEnumerable().Where(x => x.State == 2).OrderByDescending(x => x.ReleaseDate).FirstOrDefaultAsync();

            var chall = ChallengesManager.GetChallengeToBeReleased(dbContext, release: true).GetAwaiter().GetResult();

            if (chall == null)
            {
                Log.Information("Aborting Challenge Release Job because no challenge is ready to be released");
                return;
            }

            if (config.TodaysChannelId != 0 && config.TodaysRoleId != 0)
            {
                Log.Information("Deleting and re-creating Today's Channel role");
                var oldRole = client.GetGuild(config.GuildId).GetRole(config.TodaysRoleId);
                var newRole = await client.GetGuild(config.GuildId).CreateRoleAsync(oldRole.Name, oldRole.Permissions, oldRole.Color, oldRole.IsHoisted, oldRole.IsMentionable);

                await client.GetGuild(config.GuildId).GetTextChannel(config.TodaysChannelId).AddPermissionOverwriteAsync(newRole, new OverwritePermissions(viewChannel: PermValue.Allow));

                await oldRole.DeleteAsync();

                config.TodaysRoleId = newRole.Id;
                await dbContext.SaveChangesAsync();

                Log.Information("Purging Today's Channel");
                var todaysChannel = client.GetGuild(config.GuildId).GetTextChannel(config.TodaysChannelId);
                var messages      = await todaysChannel.GetMessagesAsync(int.MaxValue).FlattenAsync();

                messages = messages.Where(x => (DateTimeOffset.UtcNow - x.Timestamp).TotalDays <= 14);
                if (messages.Any())
                {
                    await todaysChannel.DeleteMessagesAsync(messages);
                }

                Log.Information("Posting the challenge writeup on today's channel");
                if (!string.IsNullOrEmpty(chall.Writeup))
                {
                    var writeupEmbed = new CustomEmbedBuilder();
                    writeupEmbed.WithTitle("Intended Solution");
                    writeupEmbed.WithDescription(chall.Writeup);
                    var message = await todaysChannel.SendMessageAsync(embed : writeupEmbed.Build());

                    await message.PinAsync();
                }
            }

            if (!string.IsNullOrEmpty(chall.Writeup) && config.BoardWriteupsChannelId != 0)
            {
                Log.Information("Posting the challenge writeup on the board writeups channel");
                var writeupEmbed = new CustomEmbedBuilder();
                writeupEmbed.WithTitle($"Writeup for {chall.Title}");
                writeupEmbed.WithDescription($"{chall.Writeup}\n**Flag:** {chall.Flag}");
                var writeupsChannel = client.GetGuild(config.GuildId).GetTextChannel(config.BoardWriteupsChannelId);
                await writeupsChannel.SendMessageAsync(embed : writeupEmbed.Build());
            }

            Log.Information("Posting the challenge on Discord");
            var             embed = ChallengesManager.GetChallengeEmbed(chall);
            RestUserMessage challengeMessage;

            if (config.ChallengePingRoleId != 0)
            {
                challengeMessage = await channel.SendMessageAsync($"<@&{config.ChallengePingRoleId}>", embed : embed);
            }
            else
            {
                challengeMessage = await channel.SendMessageAsync(embed : embed);
            }
            if (channel is INewsChannel)
            {
                await challengeMessage.CrosspostAsync();
            }

            Log.Information("Ending Challenge Release Job");
        }
Example #7
0
        public async Task Config()
        {
            var config = await _context.Configuration.FirstOrDefaultAsync();

            if (config == null)
            {
                await Link();

                config = await _context.Configuration.FirstOrDefaultAsync();
            }

            var embed = new CustomEmbedBuilder();

            embed.WithTitle("Configuration");

            if (config.ChallengeReleaseChannelId == 0)
            {
                embed.Description += $"**Challenge Release Channel:** None\n";
            }
            else
            {
                embed.Description += $"**Challenge Release Channel:** <#{config.ChallengeReleaseChannelId}>\n";
            }

            if (config.ChallengeSolvesChannelId == 0)
            {
                embed.Description += $"**Challenge Solves Channel:** None\n";
            }
            else
            {
                embed.Description += $"**Challenge Solves Channel:** <#{config.ChallengeSolvesChannelId}>\n";
            }

            if (config.LeaderboardChannelId == 0)
            {
                embed.Description += $"**Leaderboard Channel:** None\n";
            }
            else
            {
                embed.Description += $"**Leaderboard Channel:** <#{config.LeaderboardChannelId}>\n";
            }

            if (config.TodaysChannelId == 0)
            {
                embed.Description += $"**Today's Challenge Channel:** None\n";
            }
            else
            {
                embed.Description += $"**Today's Challenge Channel:** <#{config.TodaysChannelId}>\n";
            }

            if (config.LogsChannelId == 0)
            {
                embed.Description += $"**Logs Channel:** None\n";
            }
            else
            {
                embed.Description += $"**Logs Channel:** <#{config.LogsChannelId}>\n";
            }

            if (config.BoardChannelId == 0)
            {
                embed.Description += $"**Board's Channel:** None\n";
            }
            else
            {
                embed.Description += $"**Board's Channel:** <#{config.BoardChannelId}>\n";
            }

            if (config.BoardWriteupsChannelId == 0)
            {
                embed.Description += $"**Board Writeups Channel:** None\n";
            }
            else
            {
                embed.Description += $"**Board Writeups Channel:** <#{config.BoardWriteupsChannelId}>\n";
            }

            if (config.BoardRoleId == 0)
            {
                embed.Description += $"**Board's Role:** None\n";
            }
            else
            {
                embed.Description += $"**Board's Role:** <@&{config.BoardRoleId}>\n";
            }

            if (config.FirstPlaceRoleId == 0 || config.SecondPlaceRoleId == 0 || config.ThirdPlaceRoleId == 0)
            {
                embed.Description += $"**Top Roles:** None\n";
            }
            else
            {
                embed.Description += $"**Top Roles:** <@&{config.FirstPlaceRoleId}> <@&{config.SecondPlaceRoleId}> <@&{config.ThirdPlaceRoleId}>\n";
            }

            if (config.TodaysRoleId == 0)
            {
                embed.Description += $"**Today's Challenge Role:** None\n";
            }
            else
            {
                embed.Description += $"**Today's Challenge Role:** <@&{config.TodaysRoleId}>\n";
            }

            if (config.ChallengePingRoleId == 0)
            {
                embed.Description += $"**Challenge Ping Role:** None\n";
            }
            else
            {
                embed.Description += $"**Challenge Ping Role:** <@&{config.ChallengePingRoleId}>\n";
            }

            embed.Description += $"**Release Time:** {config.ReleaseTime / 60}H{config.ReleaseTime % 60} UTC";
            await ReplyAsync(embed : embed.Build());
        }