Exemple #1
0
        private async Task TrophyUnlockedAsync(TrophyUnlockedArgs args)
        {
            ICommandContext commandContext = args.Context.CommandContext;
            ICreator        creator        = args.Context.Creator;
            ITrophy         trophy         = args.TrophyInfo.Trophy;

            if (commandContext != null)
            {
                Discord.Messaging.IEmbed embed = new Discord.Messaging.Embed {
                    Title       = "🏆 Trophy unlocked!",
                    Description = string.Format("Congratulations {0}! You've earned the **{1}** trophy.", (await commandContext.Guild.GetUserAsync(creator.UserId.Value)).Mention, trophy.Name),
                    Footer      = trophy.Description,
                    Color       = System.Drawing.Color.FromArgb(255, 204, 77)
                };

                await commandContext.Channel.SendMessageAsync(embed : embed.ToDiscordEmbed());
            }
        }
        public async Task AwardTrophy(IGuildUser user, string trophyName)
        {
            ITrophy trophy = TrophyService.GetTrophies()
                             .Where(t => t.Name.Equals(trophyName, StringComparison.OrdinalIgnoreCase))
                             .FirstOrDefault();

            if (trophy is null)
            {
                await BotUtils.ReplyAsync_Error(Context, "No such trophy exists.");

                return;
            }

            // #todo Show warning and do nothing if the user already has the trophy

            await Db.UnlockTrophyAsync(new Creator(user.Id, user.Username), trophy);

            await BotUtils.ReplyAsync_Success(Context, string.Format("Successfully awarded **{0}** trophy to {1}.", trophy.Name, user.Mention));
        }
        public async Task Trophies(IUser user = null)
        {
            if (user is null)
            {
                user = Context.User;
            }

            ICreator creator = new Creator(user.Id, user.Username);

            IUnlockedTrophyInfo[] unlocked = (await Db.GetUnlockedTrophiesAsync(creator, TrophyService.GetTrophies())).ToArray();

            Array.Sort(unlocked, (x, y) => x.DateUnlocked.CompareTo(y.DateUnlocked));

            EmbedBuilder embed = new EmbedBuilder();

            embed.WithTitle(string.Format("{0}'s Trophies ({1:0.#}%)", user.Username, await Db.GetTrophyCompletionRateAsync(creator, TrophyService.GetTrophies())));
            embed.WithColor(new Color(255, 204, 77));

            StringBuilder description_builder = new StringBuilder();

            description_builder.AppendLine(string.Format("See a list of all available trophies with `{0}trophylist`.", Config.Prefix));

            foreach (IUnlockedTrophyInfo info in unlocked)
            {
                ITrophy trophy = info.Trophy;

                if (trophy is null)
                {
                    continue;
                }

                description_builder.AppendLine(string.Format("{0} **{1}** - Earned {2} ({3:0.#}%)",
                                                             trophy.Icon,
                                                             trophy.Name,
                                                             DateUtils.TimestampToShortDateString(DateUtilities.GetTimestampFromDate(info.DateUnlocked)),
                                                             await Db.GetTrophyCompletionRateAsync(trophy)
                                                             ));
            }

            embed.WithDescription(description_builder.ToString());

            await ReplyAsync("", false, embed.Build());
        }
        public static async Task <double> GetTrophyCompletionRateAsync(this SQLiteDatabase database, ICreator creator, IEnumerable <ITrophy> trophyList, bool includeOneTimeTrophies = false)
        {
            IEnumerable <IUnlockedTrophyInfo> unlocked = await database.GetUnlockedTrophiesAsync(creator, trophyList);

            int unlocked_count = unlocked
                                 .Where(x => {
                if (includeOneTimeTrophies)
                {
                    return(true);
                }

                ITrophy t = x.Trophy;

                return(t != null && !t.Flags.HasFlag(TrophyFlags.OneTime));
            })
                                 .Count();
            int trophy_count = trophyList.Where(x => includeOneTimeTrophies || !x.Flags.HasFlag(TrophyFlags.OneTime)).Count();

            return(trophy_count <= 0 ? 0.0 : (100.0 * unlocked_count / trophy_count));
        }
        public async Task RegisterTrophiesAsync(RegisterTrophiesOptions options = RegisterTrophiesOptions.None)
        {
            // Register all trophies in the assembly.

            await OnLogAsync(LogSeverity.Info, "Registering trophies");

            Assembly currentAssembly = Assembly.GetExecutingAssembly();

            IEnumerable <Type> trophyTypes = AppDomain.CurrentDomain.GetAssemblies()
                                             .Where(assembly => !options.HasFlag(RegisterTrophiesOptions.ExcludeDefaultTrophies) || assembly != currentAssembly)
                                             .SelectMany(assembly => assembly.GetTypes())
                                             .Where(type => !type.IsAbstract && typeof(ITrophy).IsAssignableFrom(type))
                                             .Where(type => type.GetConstructor(Type.EmptyTypes) != null);

            foreach (Type type in trophyTypes)
            {
                ITrophy instance = (ITrophy)Activator.CreateInstance(type);

                trophies.Add(instance);
            }

            if (!options.HasFlag(RegisterTrophiesOptions.ExcludeDefaultTrophies))
            {
                trophies.Add(new Trophy("To Infinity And Beyond", "Own a species that spreads to another zone."));
                trophies.Add(new Trophy("A New World", "Create a species that spreads across an ocean body."));
                trophies.Add(new Trophy("One To Rule Them All", "Create a species that turns into an apex predator."));
                trophies.Add(new Trophy("I Am Selection", "Create a species that is the direct cause of another species extinction."));

                trophies.Add(new Trophy("Colonization", "Be the first to create a eusocial species.", TrophyFlags.Hidden | TrophyFlags.OneTime));
                trophies.Add(new Trophy("Let There Be Light", "Be the first to create a species that makes light.", TrophyFlags.Hidden | TrophyFlags.OneTime));
                trophies.Add(new Trophy("Master Of The Skies", "Be the first to create a species capable of flight.", TrophyFlags.Hidden | TrophyFlags.OneTime));
                trophies.Add(new Trophy("Did You Hear That?", "Be the first to make a species that makes noise.", TrophyFlags.Hidden | TrophyFlags.OneTime));
                trophies.Add(new Trophy("Double Trouble", "Be the first to make a species with two legs.", TrophyFlags.Hidden | TrophyFlags.OneTime));
                trophies.Add(new Trophy("Can We Keep It?", "Be the first to create a species with fur.", TrophyFlags.Hidden | TrophyFlags.OneTime));
                trophies.Add(new Trophy("Turn On The AC!", "Be the first to create a warm-blooded species.", TrophyFlags.Hidden | TrophyFlags.OneTime));
                trophies.Add(new Trophy("Do You See What I See?", "Be the first to create a species with developed eyes.", TrophyFlags.Hidden | TrophyFlags.OneTime));
                trophies.Add(new Trophy("Imposter", "Be the first to create a species that mimics another species.", TrophyFlags.Hidden | TrophyFlags.OneTime));
            }

            await OnLogAsync(LogSeverity.Info, string.Format("Registered {0} trophies", trophies.Count()));
        }
Exemple #6
0
        //TODO: Add a boolean for assign that gets passed in from user input
        public ITrophy AssignTrophy(Week currentWeek, Team team, ITrophy trophyToAssign)
        {
            var start = 0;

            _driver.Navigate().GoToUrl($"http://games.espn.com/ffl/trophylist?leagueId=127291&start={start}");

            //http://games.espn.com/ffl/trophylist?leagueId=127291&start=12

            var foundTrophyLabel = _driver.FindElements(By.XPath("//table/tbody/tr/td/div/div/center/b[contains(.,'" + trophyToAssign.GetTrophyName() + "')]")).Count() == 1;

            if (!foundTrophyLabel)
            {
                start = 12;
                _driver.Navigate().GoToUrl($"http://games.espn.com/ffl/trophylist?leagueId=127291&start={start}");
            }

            _driver.FindElement(By.XPath("//table/tbody/tr/td/div/div/center/b[contains(.,'" + trophyToAssign.GetTrophyName() + "')]/parent::center/parent::div/div/a[contains(.,'Assign')]")).Click();
            _driver.WaitUntilElementExists(By.Id("assignTrophyDiv"));

            var dropdown       = _driver.FindElement(By.Id("assignTeamId"));
            var dropdownSelect = new SelectElement(dropdown);

            dropdownSelect.SelectByText(team.TeamName);

            _driver.FindElement(By.Name("headline")).SendKeys(trophyToAssign.GetHeadline(team));
            _driver.FindElement(By.Name("reason")).SendKeys(trophyToAssign.GetReason(team));

            var showcase         = _driver.FindElement(By.Id("isShowcase"));
            var showcaseDropdown = new SelectElement(showcase);

            showcaseDropdown.SelectByText("Yes");

            _driver.FindElement(By.Name("btnSubmit")).Click();
            _driver.WaitUntilElementExists(By.ClassName("bodyCopy"));

            Thread.Sleep(2000);

            return(trophyToAssign);
        }
        public static async Task <IEnumerable <IUnlockedTrophyInfo> > GetUnlockedTrophiesAsync(this SQLiteDatabase database, ICreator creator, IEnumerable <ITrophy> trophyList)
        {
            List <IUnlockedTrophyInfo> unlocked = new List <IUnlockedTrophyInfo>();

            using (SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM Trophies WHERE user_id = $user_id ")) {
                cmd.Parameters.AddWithValue("$user_id", creator.UserId);

                foreach (DataRow row in await database.GetRowsAsync(cmd))
                {
                    string trophyName    = row.Field <string>("trophy_name");
                    long   timesUnlocked = 0;

                    using (SQLiteCommand cmd2 = new SQLiteCommand("SELECT COUNT(*) FROM Trophies WHERE trophy_name = $trophy_name ")) {
                        cmd2.Parameters.AddWithValue("$trophy_name", trophyName);

                        timesUnlocked = await database.GetScalarAsync <long>(cmd2);
                    }

                    ITrophy trophy = trophyList
                                     .Where(t => t.Identifier.Equals(trophyName, StringComparison.OrdinalIgnoreCase))
                                     .FirstOrDefault();

                    if (trophy != null)
                    {
                        IUnlockedTrophyInfo info = new UnlockedTrophyInfo(creator, trophy)
                        {
                            TimesUnlocked = (int)timesUnlocked,
                            DateUnlocked  = DateUtilities.GetDateFromTimestamp(row.Field <long>("timestamp"))
                        };

                        unlocked.Add(info);
                    }
                }
            }

            return(unlocked);
        }
 public void RegisterTrophy(ITrophy trophy)
 {
     trophies.Add(trophy);
 }
        public async Task Profile(IUser user)
        {
            // Begin building the embed (add default parameters).

            EmbedBuilder embed = new EmbedBuilder();

            embed.WithTitle(string.Format("{0}'s profile", user.Username));
            embed.WithThumbnailUrl(user.GetAvatarUrl(size: 64));

            // Get basic information about the user.
            // This will return null if the user hasn't been seen before.

            ICreator userInfo = await Db.GetCreatorAsync(user.ToCreator(), UserInfoQueryFlags.MatchEither);

            if (userInfo is null)
            {
                embed.WithDescription(string.Format("{0} has not submitted any species.", user.Username));
            }
            else
            {
                long     daysSinceFirstSubmission = (DateUtilities.GetCurrentDateUtc() - userInfo.FirstSpeciesDate).Value.Days;
                UserRank userRank = await Db.GetRankAsync(userInfo, UserInfoQueryFlags.MatchEither);

                // Get the user's most active genus.

                IEnumerable <ISpecies> userSpecies = await Db.GetSpeciesAsync(userInfo, UserInfoQueryFlags.MatchEither);

                IGrouping <string, string> favoriteGenusGrouping = userSpecies
                                                                   .Select(x => x.Genus.GetName())
                                                                   .GroupBy(x => x)
                                                                   .OrderByDescending(x => x.Count())
                                                                   .FirstOrDefault();

                string favoriteGenus      = favoriteGenusGrouping is null ? "N/A" : favoriteGenusGrouping.First();
                int    favoriteGenusCount = favoriteGenusGrouping is null ? 0 : favoriteGenusGrouping.Count();

                int userSpeciesCount = userSpecies.Count();
                int speciesCount     = (int)await Db.GetSpeciesCountAsync();

                // Get the user's rarest trophy.

                string rarest_trophy = "N/A";

                IUnlockedTrophyInfo[] unlocked = (await Db.GetUnlockedTrophiesAsync(new Creator(user.Id, user.Username), TrophyService.GetTrophies())).ToArray();

                if (unlocked.Count() > 0)
                {
                    Array.Sort(unlocked, (lhs, rhs) => lhs.TimesUnlocked.CompareTo(rhs.TimesUnlocked));

                    ITrophy trophy = TrophyService.GetTrophies()
                                     .Where(t => t.Identifier.Equals(unlocked[0].Trophy.Identifier))
                                     .FirstOrDefault();

                    rarest_trophy = trophy.Name;
                }

                // Put together the user's profile.

                if (Config.GenerationsEnabled)
                {
                    int    generationsSinceFirstSubmission = (await Db.GetGenerationsAsync()).Where(x => x.EndDate > userInfo.FirstSpeciesDate).Count();
                    double speciesPerGeneration            = generationsSinceFirstSubmission <= 0 ? userSpeciesCount : (double)userSpeciesCount / generationsSinceFirstSubmission;

                    embed.WithDescription(string.Format("{0} made their first species during **{1}**.\nSince then, they have submitted **{2:0.0}** species per generation.\n\nTheir submissions make up **{3:0.0}%** of all species.",
                                                        user.Username,
                                                        await GetDateStringAsync(userInfo.FirstSpeciesDate),
                                                        speciesPerGeneration,
                                                        (double)userSpeciesCount / speciesCount * 100.0));
                }
                else
                {
                    embed.WithDescription(string.Format("{0} made their first species on **{1}**.\nSince then, they have submitted **{2:0.0}** species per day.\n\nTheir submissions make up **{3:0.0}%** of all species.",
                                                        user.Username,
                                                        await GetDateStringAsync(userInfo.FirstSpeciesDate),
                                                        daysSinceFirstSubmission == 0 ? userSpeciesCount : (double)userSpeciesCount / daysSinceFirstSubmission,
                                                        (double)userSpeciesCount / speciesCount * 100.0));
                }

                embed.AddField("Species", string.Format("{0} (Rank **#{1}**)", userSpeciesCount, userRank.Rank), inline: true);

                embed.AddField("Favorite genus", string.Format("{0} ({1} spp.)", StringUtilities.ToTitleCase(favoriteGenus), favoriteGenusCount), inline: true);

                if (Config.TrophiesEnabled)
                {
                    embed.AddField("Trophies", string.Format("{0} ({1:0.0}%)",
                                                             (await Db.GetUnlockedTrophiesAsync(new Creator(user.Id, user.Username), TrophyService.GetTrophies())).Count(),
                                                             await Db.GetTrophyCompletionRateAsync(new Creator(user.Id, user.Username), TrophyService.GetTrophies())), inline: true);

                    embed.AddField("Rarest trophy", rarest_trophy, inline: true);
                }
            }

            await ReplyAsync("", false, embed.Build());
        }
 public UnlockedTrophyInfo(ICreator creator, ITrophy trophy)
 {
     this.Creator = creator;
     this.Trophy  = trophy;
 }
        public async Task Trophy(string name)
        {
            // Find the trophy with this name.

            ITrophy trophy = TrophyService.GetTrophies()
                             .Where(t => t.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
                             .FirstOrDefault();

            // If no such trophy exists, return an error.

            if (trophy is null)
            {
                await BotUtils.ReplyAsync_Error(Context, "No such trophy exists.");

                return;
            }

            // Show trophy information.

            double completion_rate = await Db.GetTrophyCompletionRateAsync(trophy);

            bool hide_description = trophy.Flags.HasFlag(TrophyFlags.Hidden) && completion_rate <= 0.0;

            string embed_title       = string.Format("{0} {1} ({2:0.#}%)", trophy.Icon, trophy.Name, completion_rate);
            string embed_description = string.Format("_{0}_", hide_description ? TrophyBase.HiddenTrophyDescription : trophy.Description);
            long   times_unlocked    = await Db.GetTimesTrophyUnlockedAsync(trophy);

            embed_description += string.Format("\n\nThis trophy has been earned by **{0}** user{1} ({2:0.#}%).",
                                               times_unlocked,
                                               times_unlocked == 1 ? "" : "s",
                                               completion_rate);

            EmbedBuilder embed = new EmbedBuilder();

            embed.WithTitle(embed_title);
            embed.WithDescription(embed_description);
            embed.WithColor(new Color(255, 204, 77));

            // Show first/latest earners.

            IEnumerable <IUnlockedTrophyInfo> earners = (await Db.GetCreatorsWithTrophyAsync(trophy)).OrderBy(x => x.DateUnlocked);
            string date_format = "MMMM dd, yyyy";

            if (Context.Guild != null)
            {
                foreach (IUnlockedTrophyInfo trophy_user in earners)
                {
                    IUser user = await Context.Guild.GetUserAsync(trophy_user.Creator.UserId.Value);

                    if (!(user is null))
                    {
                        embed.AddField("First earned", string.Format("**{0}** ({1})", user.Username, trophy_user.DateUnlocked.ToString(date_format)), inline: true);

                        break;
                    }
                }

                foreach (IUnlockedTrophyInfo trophy_user in earners.Reverse())
                {
                    IUser user = await Context.Guild.GetUserAsync(trophy_user.Creator.UserId.Value);

                    if (!(user is null))
                    {
                        embed.AddField("Latest earned", string.Format("**{0}** ({1})", user.Username, trophy_user.DateUnlocked.ToString(date_format)), inline: true);

                        break;
                    }
                }
            }

            await ReplyAsync("", false, embed.Build());
        }
        public static async Task <double> GetTrophyCompletionRateAsync(this SQLiteDatabase database, ITrophy trophy)
        {
            // The completion rate is determined from the number of users who have earned the trophy and the number of users who have submitted species.

            long times_unlocked = await database.GetTimesTrophyUnlockedAsync(trophy);

            long total_users = 0;

            using (SQLiteCommand cmd = new SQLiteCommand("SELECT COUNT(*) FROM (SELECT user_id FROM Species GROUP BY user_id)"))
                total_users = await database.GetScalarAsync <long>(cmd);

            return((total_users <= 0) ? 0.0 : (100.0 * times_unlocked / total_users));
        }
        public static async Task <IEnumerable <IUnlockedTrophyInfo> > GetCreatorsWithTrophyAsync(this SQLiteDatabase database, ITrophy trophy)
        {
            List <IUnlockedTrophyInfo> results = new List <IUnlockedTrophyInfo>();

            using (SQLiteCommand cmd = new SQLiteCommand("SELECT user_id, timestamp FROM Trophies WHERE trophy_name = $trophy_name")) {
                cmd.Parameters.AddWithValue("$trophy_name", trophy.Identifier);

                IEnumerable <DataRow> rows = await database.GetRowsAsync(cmd);

                foreach (DataRow row in rows)
                {
                    ICreator       creator    = new Creator((ulong)row.Field <long>("user_id"), string.Empty);
                    DateTimeOffset dateEarned = DateUtilities.GetDateFromTimestamp(row.Field <long>("timestamp"));

                    results.Add(new UnlockedTrophyInfo(creator, trophy)
                    {
                        DateUnlocked  = dateEarned,
                        TimesUnlocked = rows.Count()
                    });
                }
            }

            return(results);
        }
        public static async Task <long> GetTimesTrophyUnlockedAsync(this SQLiteDatabase database, ITrophy trophy)
        {
            using (SQLiteCommand cmd = new SQLiteCommand("SELECT COUNT(*) FROM Trophies WHERE trophy_name = $trophy_name")) {
                cmd.Parameters.AddWithValue("$trophy_name", trophy.Identifier);

                return(await database.GetScalarAsync <long>(cmd));
            }
        }
        public static async Task UnlockTrophyAsync(this SQLiteDatabase database, ICreator creator, ITrophy trophy)
        {
            if (creator.UserId.HasValue)
            {
                using (SQLiteCommand cmd = new SQLiteCommand("INSERT OR IGNORE INTO Trophies(user_id, trophy_name, timestamp) VALUES($user_id, $trophy_name, $timestamp);")) {
                    cmd.Parameters.AddWithValue("$user_id", creator.UserId);
                    cmd.Parameters.AddWithValue("$trophy_name", trophy.Identifier);
                    cmd.Parameters.AddWithValue("$timestamp", DateUtilities.GetCurrentTimestampUtc());

                    await database.ExecuteNonQueryAsync(cmd);
                }
            }
        }