Example #1
0
        public void Activate(CommandEventArg e)
        {
            int indexSpace = e.AfterCMD.IndexOf(' ');

            if (indexSpace <= 0)
            {
                Coding.Discord.SendMessage(e.ChannelID, DescriptionUsage);
                return;
            }
            if (!bool.TryParse(e.AfterCMD.Substring(0, indexSpace), out bool status))
            {
                Coding.Discord.SendMessage(e.ChannelID, "Could not parse status");
                return;
            }

            string message = null;

            if (e.AfterCMD.Length != indexSpace - 1)
            {
                message = e.AfterCMD.Remove(0, indexSpace + 1);
            }

            using (Database.GAFContext context = new Database.GAFContext())
            {
                int id = context.BotMaintenance.Max(m => m.Id);
                Database.Models.BotMaintenance maint = context.BotMaintenance.FirstOrDefault(m => m.Id == id);

                if (maint == null)
                {
                    context.BotMaintenance.Add(new Database.Models.BotMaintenance()
                    {
                        Enabled      = status,
                        Notification = message
                    });
                }
                else
                {
                    maint.Enabled = status;

                    if (message != null)
                    {
                        maint.Notification = message;
                    }
                }

                context.SaveChanges();
            }
        }
Example #2
0
        public DiscordEmbed CreateQualifierStatisticEmbed(AnalyzerQualifierResult ar, DiscordColor embedColor)
        {
            string analyzerMatchPlayed;

            using (Database.GAFContext context = new Database.GAFContext())
                analyzerMatchPlayed = context.BotLocalization.First(l => l.Code.Equals("analyzerMatchPlayed")).String;

            DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
            {
                Title       = "Qualifier Stats",
                Description = ".",
                Footer      = new DiscordEmbedBuilder.EmbedFooter()
                {
                    Text = $"{analyzerMatchPlayed} {ar.TimeStamp}",
                },
                Color = embedColor,
            };

            foreach (var team in ar.Teams)
            {
                string teamName       = team.TeamName;
                string playerScores   = "";
                long   totalTeamScore = 0;

                foreach (var player in team.Players)
                {
                    long totalPlayerScore = 0;

                    playerScores += player.UserName + ": ";

                    foreach (var score in player.Scores)
                    {
                        int scoreVal = score.Item2.score ?? 0;

                        totalPlayerScore += scoreVal;
                        totalTeamScore   += scoreVal;
                    }
                    playerScores += string.Format("{0:n0}", totalPlayerScore) + Environment.NewLine;
                }

                playerScores = playerScores.TrimEnd(Environment.NewLine.ToArray());

                builder.AddField($"Scores for {teamName} (TotalScore: {string.Format("{0:n0}", totalTeamScore)})", playerScores);
            }

            return(builder.Build());
        }
Example #3
0
        public void Activate(CommandEventArg e)
        {
            if (!string.IsNullOrEmpty(e.AfterCMD))
            {
                ICommand command = (Program.CommandHandler as CommandHandler).ActiveCommands.FirstOrDefault(c => (c.Activator.Equals(e.AfterCMD[0]) &&
                                                                                                                  c.CMD.Equals(e.AfterCMD.Remove(0, 1), StringComparison.CurrentCultureIgnoreCase)) ||
                                                                                                            c.CMD.Equals(e.AfterCMD, StringComparison.CurrentCultureIgnoreCase));

                if (command == null)
                {
                    Coding.Discord.SendMessage(e.ChannelID, "Command not found");
                    return;
                }

                DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
                {
                    Title = "Command Info for " + command.Activator + command.CMD
                };

                builder.AddField((!string.IsNullOrEmpty(command.Description) ? command.Description : "null"), (!string.IsNullOrEmpty(command.DescriptionUsage) ? command.DescriptionUsage : "null"));

                Coding.Discord.GetChannel(e.ChannelID).SendMessageAsync(embed: builder.Build());
                return;
            }

            ICommand[] commands = (Program.CommandHandler as CommandHandler).ActiveCommands.ToArray();
            string     response = "";

            Database.Models.BotUsers user;

            using (Database.GAFContext context = new Database.GAFContext())
                user = context.BotUsers.First(u => u.DiscordId == (long)e.DUserID);

            AccessLevel access = user == null ? AccessLevel.User : (AccessLevel)user.AccessLevel;

            foreach (ICommand cmd in commands)
            {
                if (cmd.AccessLevel <= access)
                {
                    response += Environment.NewLine + $"{cmd.Activator}{cmd.CMD}: {cmd.Description}";
                }
            }

            Coding.Discord.SendMessage(e.ChannelID, $"```{Environment.NewLine}{response}{Environment.NewLine}```");
        }
Example #4
0
        public bool ActivateCommand(DSharpPlus.Entities.DiscordMessage message, AccessLevel access)
        {
            try
            {
                if (message == null || string.IsNullOrEmpty(message.Content) || char.IsLetterOrDigit(message.Content[0]))
                {
                    return(false);
                }

                if (ActiveCommands == null)
                {
                    ActiveCommands = new List <ICommand>();
                }

                string[] cmdsplit = message.Content.Split(' ');

                if (cmdsplit == null || cmdsplit.Length == 0)
                {
                    return(false);
                }

                ulong  id        = message.Author.Id;
                string name      = message.Author.Username;
                var    guild     = message.Channel.Guild;
                var    guildid   = (ulong?)message.Channel.GuildId;
                ulong  chid      = message.Channel.Id;
                char   activator = message.Content[0];
                string _cmd      = cmdsplit[0].Substring(1, cmdsplit[0].Length - 1);
                string aftercmd  = "";
                if (message.Content.Length > cmdsplit[0].Length + 1)
                {
                    aftercmd = message.Content.Remove(0, cmdsplit[0].Length + 1);
                }

                CommandEventArg arg = new CommandEventArg(id, name, (guild == null ? (ulong?)null : guildid), chid, activator, _cmd, aftercmd);


                ICommand cmd = null;

                //For now i hardcode this cause I'm lazy
                if (activator.Equals('>'))
                {
                    Console.WriteLine(">");
                    //TextCommand.OnTextCommand(arg);
                    return(true);
                }

                cmd = ActiveCommands.Find(cmd_ => cmd_.Activator.Equals(arg.Activator) && cmd_.CMD.Equals(arg.CMD));

                if (cmd == null)
                {
                    return(false);
                }

                if ((int)cmd.AccessLevel > (int)access)
                {
                    return(false);
                }

                using (Database.GAFContext context = new Database.GAFContext())
                {
                    int dbid  = context.BotMaintenance.Max(m => m.Id);
                    var maint = context.BotMaintenance.FirstOrDefault(m => m.Id == dbid);

                    if (maint.Enabled && access < AccessLevel.Admin)
                    {
                        Coding.Discord.SendMessage(chid, "Bot is currently in maintenance, please try again later" + Environment.NewLine +
                                                   "Info: " + maint.Notification ?? "no information");

                        return(false);
                    }
                }

                cmd.Activate(arg);

                return(true);
            }
            catch (Exception ex)
            {
                Logger.Log(ex.ToString(), LogLevel.Trace);
                return(false);
            }
        }
Example #5
0
        public void Activate(CommandEventArg e)
        {
            try
            {
                Team team;
                using (Database.GAFContext context = new Database.GAFContext())
                    team = context.Team.FirstOrDefault(t => t.Name.Equals(e.AfterCMD, StringComparison.CurrentCultureIgnoreCase));

                if (team == null)
                {
                    Coding.Discord.SendMessage(e.ChannelID, "Could not find team " + e.AfterCMD);
                    return;
                }

                List <int> playerIds = new List <int>();

                using (Database.GAFContext context = new Database.GAFContext())
                    playerIds.AddRange(context.TeamPlayerList.Where(tpl => tpl.TeamId == team.Id).Select(tpl => (int)tpl.PlayerListId));

                List <Player> players = new List <Player>();

                using (Database.GAFContext context = new Database.GAFContext())
                {
                    foreach (int playerId in playerIds)
                    {
                        Player player = context.Player.FirstOrDefault(p => p.Id == (long)playerId);

                        if (player == null)
                        {
                            Logger.Log("Could not find player: " + playerId, LogLevel.WARNING);
                            continue;
                        }

                        players.Add(player);
                    }
                }

                Dictionary <string, string> countryCodes = new Dictionary <string, string>();

                foreach (Player p in players)
                {
                    if (countryCodes.Keys.FirstOrDefault(k => k.Equals(p.Country, StringComparison.CurrentCultureIgnoreCase)) == null)
                    {
                        countryCodes.Add(p.Country, null);
                    }
                }

                using (Database.GAFContext context = new Database.GAFContext())
                {
                    for (int i = 0; i < countryCodes.Keys.Count; i++)
                    {
                        countryCodes[countryCodes.Keys.ElementAt(i)] = context.BotCountryCode
                                                                       .FirstOrDefault(c => c.CountryCode.Equals(countryCodes.Keys.ElementAt(i),
                                                                                                                 StringComparison.CurrentCultureIgnoreCase))
                                                                       .Country;
                    }
                }

                DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
                {
                    Title        = "Country info for team: " + e.AfterCMD,
                    ThumbnailUrl = team.Image ?? null,
                    Description  = "Average/Median PP: " + $"{team.AveragePP ?? '?'}/{team.MedianPP ?? '?'}",
                    Timestamp    = DateTime.UtcNow
                };

                for (int i = 0; i < players.Count; i++)
                {
                    builder.AddField("Player", players[i].Nickname, true);
                    builder.AddField("Location", countryCodes[countryCodes.Keys.First(k => k.Equals(players[i].Country, StringComparison.CurrentCultureIgnoreCase))].Trim('"'), true);
                    builder.AddField("PP Raw", $"{players[i].PPRaw ?? '?'}", true);
                }

                DiscordEmbed embed = builder.Build();

                DiscordChannel channel = Coding.Discord.GetChannel(e.ChannelID);
                channel.SendMessageAsync(embed: embed).Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #6
0
        public DiscordEmbed CreateStatisticEmbed(AnalyzerResult ar, DiscordColor embedColor)
        {
            string analyzerTeam, analyzerWon;
            string analyzerMatchPlayed;
            string analyzerMVP, analyzerTeamBlue, analyzerGeneratedPerformanceScore;
            string analyzerTeamRed;
            string analyzerHighestScore, analyzerHighestAcc;
            string analyzerOnMap, analyzerWith, analyzerWithPoints, analyzerAcc;
            string analyzerFirst, analyzerSecond, analyzerThird;
            string analyzerAverageAcc;

            using (Database.GAFContext context = new Database.GAFContext())
            {
                analyzerTeam        = context.BotLocalization.First(l => l.Code.Equals("analyzerTeam")).String;
                analyzerWon         = context.BotLocalization.First(l => l.Code.Equals("analyzerWon")).String;
                analyzerMatchPlayed = context.BotLocalization.First(l => l.Code.Equals("analyzerMatchPlayed")).String;
                analyzerMVP         = context.BotLocalization.First(l => l.Code.Equals("analyzerMVP")).String;
                analyzerTeamBlue    = context.BotLocalization.First(l => l.Code.Equals("analyzerTeamBlue")).String;
                analyzerGeneratedPerformanceScore = context.BotLocalization.First(l => l.Code.Equals("analyzerGeneratedPerformanceScore")).String;
                analyzerTeamRed      = context.BotLocalization.First(l => l.Code.Equals("analyzerTeamRed")).String;
                analyzerHighestScore = context.BotLocalization.First(l => l.Code.Equals("analyzerHighestScore")).String;
                analyzerHighestAcc   = context.BotLocalization.First(l => l.Code.Equals("analyzerHighestAcc")).String;
                analyzerOnMap        = context.BotLocalization.First(l => l.Code.Equals("analyzerOnMap")).String;
                analyzerWith         = context.BotLocalization.First(l => l.Code.Equals("analyzerWith")).String;
                analyzerWithPoints   = context.BotLocalization.First(l => l.Code.Equals("analyzerWithPoints")).String;
                analyzerAcc          = context.BotLocalization.First(l => l.Code.Equals("analyzerAcc")).String;
                analyzerFirst        = context.BotLocalization.First(l => l.Code.Equals("analyzerFirst")).String;
                analyzerSecond       = context.BotLocalization.First(l => l.Code.Equals("analyzerSecond")).String;
                analyzerThird        = context.BotLocalization.First(l => l.Code.Equals("analyzerThird")).String;
                analyzerAverageAcc   = context.BotLocalization.First(l => l.Code.Equals("analyzerAverageAcc")).String;
            }

            string description = string.Format("{0} {1} {2} ({3}:{4})", analyzerTeam, ar.WinningTeam, analyzerWon, ar.WinningTeamWins, ar.LosingTeamWins);

            DiscordEmbedBuilder discordEmbedBuilder = new DiscordEmbedBuilder()
            {
                Title       = ar.MatchName,
                Description = description,
                Footer      = new DiscordEmbedBuilder.EmbedFooter()
                {
                    Text = $"{analyzerMatchPlayed} {ar.TimeStamp}",
                },
                Color = embedColor,
            };

            var playersBlue = ar.HighestScoresRanking.Where(r => r.Player.Scores.ElementAt(r.Player.Scores.Length - 1).multiplayer.team.Trim(' ').Equals("blue", StringComparison.CurrentCultureIgnoreCase)).OrderByDescending(f => f.Player.MVPScore).ToList();
            var playersRed  = ar.HighestScoresRanking.Where(r => r.Player.Scores.ElementAt(r.Player.Scores.Length - 1).multiplayer.team.Trim(' ').Equals("red", StringComparison.CurrentCultureIgnoreCase)).OrderByDescending(f => f.Player.MVPScore).ToList();

            var playerBlue = playersBlue.ElementAt(0).Player;
            var playerRed  = playersRed.ElementAt(0).Player;

            //generated performance score = gps
            discordEmbedBuilder.AddField(analyzerMVP, $"{analyzerTeamBlue}: {playerBlue.UserName} ({playerBlue.MVPScore} {analyzerGeneratedPerformanceScore}){Environment.NewLine}{analyzerTeamRed}: {playerRed.UserName} ({playerRed.MVPScore} {analyzerGeneratedPerformanceScore})");

            discordEmbedBuilder.AddField(analyzerHighestScore, string.Format("{0} on the map {1} - {2} [{3}] ({4}*) with {5:n0} Points and {6}% Accuracy!",
                                                                             ar.HighestScoreUser.UserName, ar.HighestScoreBeatmap.beatmapset.artist,
                                                                             ar.HighestScoreBeatmap.beatmapset.title, ar.HighestScoreBeatmap.version,
                                                                             ar.HighestScoreBeatmap.difficulty_rating,
                                                                             string.Format("{0:n0}", ar.HighestScoreUser.HighestScore.score),
                                                                             Math.Round(ar.HighestScoreUser.HighestScore.accuracy.Value * 100.0f, 2, MidpointRounding.AwayFromZero)));

            discordEmbedBuilder.AddField(analyzerHighestAcc, string.Format("{0} {1} {2} - {3} [{4}] ({5}*) {6} {7:n0} {8} {9}% {10}!",
                                                                           ar.HighestAccuracyUser.UserName,
                                                                           analyzerOnMap,
                                                                           ar.HighestAccuracyBeatmap.beatmapset.artist,
                                                                           ar.HighestAccuracyBeatmap.beatmapset.title,
                                                                           ar.HighestAccuracyBeatmap.version,
                                                                           ar.HighestAccuracyBeatmap.difficulty_rating,
                                                                           analyzerWith,
                                                                           string.Format("{0:n0}", ar.HighestAccuracyScore.score),
                                                                           analyzerWithPoints,
                                                                           Math.Round(ar.HighestAccuracyScore.accuracy.Value * 100.0f, 2, MidpointRounding.AwayFromZero),
                                                                           analyzerAcc));

            for (int i = 1; i < 4; i++)
            {
                Rank place = ar.HighestAverageAccuracyRanking.Last(ob => ob.Place == i);
                (string, string)placeString = GetPlaceString(place);
                discordEmbedBuilder.AddField(placeString.Item1, placeString.Item2);
            }

            return(discordEmbedBuilder.Build());

            (string, string) GetPlaceString(Rank place)
            {
                switch (place.Place)
                {
                case 1:
                    return(analyzerFirst, $"{ place.Player.UserName}: {analyzerAverageAcc}: { place.Player.AverageAccuracyRounded}%");

                case 2:
                    return(analyzerSecond, $"{ place.Player.UserName}: {analyzerAverageAcc}: { place.Player.AverageAccuracyRounded}%");

                case 3:
                    return(analyzerThird, $"{place.Player.UserName}: {analyzerAverageAcc}: { place.Player.AverageAccuracyRounded}%");

                //Normally unused
                case 4:
                    return("Fourth Place", $"{place.Player.UserName}: Average Acc: { place.Player.AverageAccuracyRounded}%");

                default:
                    return($"{place.Place} Place", $"{ place.Player.UserName}: Average Acc: { place.Player.AverageAccuracyRounded}%");
                }
            }
        }