コード例 #1
0
ファイル: MessageModule.cs プロジェクト: Blade12629/GAFBot
        /// <summary>
        /// Invoked when a user joins the guild
        /// </summary>
        public void OnUserJoinedGuild(GuildMemberAddEventArgs args)
        {
            Logger.Log($"MessageHandler: User joined guild: {args.Member.Id} {args.Member.DisplayName}");

            using (GAFContext context = new GAFContext())
            {
                var buser = context.BotUsers.FirstOrDefault(b => (ulong)b.DiscordId.Value == args.Member.Id);

                if (buser != null)
                {
                    if (buser.IsVerified)
                    {
                        Coding.Discord.AssignRole((ulong)buser.DiscordId, (ulong)Program.Config.DiscordGuildId, (ulong)Program.Config.VerifiedRoleId);
                    }
                }
            }

            if (!string.IsNullOrEmpty(Program.Config.WelcomeMessage) && Program.Config.WelcomeChannel != 0)
            {
                WelcomeMessage((ulong)Program.Config.WelcomeChannel, Program.Config.WelcomeMessage, args.Member.Mention);
            }

            DiscordUser user = Coding.Discord.GetUser(args.Member.Id);

            Register(user, args.Guild.Id);
        }
コード例 #2
0
            public void Handle(PacketReader reader, Client client)
            {
                string encryptedKey = reader.ReadString();

                Console.WriteLine("Recieved Auth Key: " + encryptedKey);

                byte      authenticated = 0;
                BotApiKey key;

                using (GAFContext context = new GAFContext())
                {
                    key = context.BotApiKey.FirstOrDefault(k => k.Key.Equals(encryptedKey));

                    if (key != null)
                    {
                        authenticated = 1;
                    }
                }

                if (authenticated == 1)
                {
                    client.LoadEncryptionKey((ulong)key.DiscordId);
                    client.Authenticated = true;
                }

                PacketWriter writer = new PacketWriter(this);

                Send(writer, client, authenticated);
            }
コード例 #3
0
        public BaseDBReader(GAFContext context = null)
        {
            if (context == null)
            {
                _context = new GAFContext();
            }
            else
            {
                _context = context;
            }

            Disposed = false;
        }
コード例 #4
0
ファイル: MessageModule.cs プロジェクト: Blade12629/GAFBot
        /// <summary>
        /// Gets the access level for the user
        /// </summary>
        /// <param name="user">discord user id to find</param>
        /// <returns>user access level</returns>
        public AccessLevel GetAccessLevel(ulong user)
        {
            BotUsers buser;

            using (GAFContext context = new GAFContext())
                buser = context.BotUsers.FirstOrDefault(b => (ulong)b.DiscordId.Value == user);


            if (buser == null)
            {
                return(AccessLevel.User);
            }

            return((AccessLevel)buser.AccessLevel);
        }
コード例 #5
0
            public void Handle(PacketReader reader, Client client)
            {
                try
                {
                    string apiKeyEncrypted = reader.ReadString();
                    string code            = reader.ReadString();
                    int    keyLength       = reader.ReadInt32();
                    byte[] key             = reader.ReadBytes(keyLength);

                    byte result    = 0;
                    long discordId = 0;
                    BotApiRegisterCode registerCode;
                    using (GAFContext context = new GAFContext())
                    {
                        registerCode = context.BotApiRegisterCode.FirstOrDefault(c => c.Code.Equals(code));

                        if (registerCode != null)
                        {
                            result    = 1;
                            discordId = registerCode.DiscordId;
                            context.BotApiRegisterCode.Remove(registerCode);
                        }

                        context.BotApiKey.Add(new BotApiKey()
                        {
                            DiscordId = registerCode.DiscordId,
                            Key       = apiKeyEncrypted
                        });

                        context.SaveChanges();
                    }

                    if (result == 1)
                    {
                        client.UpdateEncryptionKey((ulong)discordId, key);
                    }

                    PacketWriter writer = new PacketWriter(this);
                    Send(writer, client, result);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
コード例 #6
0
            public void Handle(PacketReader reader, Client client)
            {
                Console.WriteLine("Reading Match");
                string match = reader.ReadString();

                Console.WriteLine("Got Match " + match);

                BotPick[] picks;
                using (GAFContext context = new GAFContext())
                    picks = context.BotPick.Where(p => p.Match.Equals(match, StringComparison.CurrentCultureIgnoreCase)).ToArray();

                Picks = new Pick[picks.Length];

                for (int i = 0; i < picks.Length; i++)
                {
                    Picks[i] = new Pick(picks[i].PickedBy, picks[i].Team, picks[i].Match, picks[i].Image);
                }

                Console.WriteLine("Sending " + Picks.Length);

                PacketWriter writer = new PacketWriter(this);

                Send(writer, client);
            }
コード例 #7
0
 public SeasonPlayerReader(GAFContext context = null) : base(context)
 {
 }
コード例 #8
0
 public SeasonPlayerCardCacheReader(GAFContext context = null) : base(context)
 {
 }
コード例 #9
0
ファイル: MessageModule.cs プロジェクト: Blade12629/GAFBot
        /// <summary>
        /// starts the osu mp analyzer
        /// </summary>
        public void StartAnalyzer(string message, ulong channel, bool sendToApi = false, bool sendToDatabase = true)
        {
            Task.Run(() =>
            {
                try
                {
                    //<https://osu.ppy.sh/community/matches/53616778>
                    //<https://osu.ppy.sh/mp/53616778>

                    using (GAFContext context = new GAFContext())
                        if (!GAFBot.Statistic.StatsHandler.UpdateSeasonStatistics(message, Program.Config.CurrentSeason, context))
                        {
                            return;
                        }


                    GAFBot.Osu.Analyzer analyzer = new GAFBot.Osu.Analyzer();
                    var matchData = analyzer.ParseMatch(message);


                    const string BAN_PATTERN = "bans from";

                    string[] lineSplit = message.Split(new char[] { '\r', '\n' });
                    lineSplit[0]       = lineSplit[0].Replace("d!", "");

                    if (matchData.Item2 == -1 && matchData.Item1 == null)
                    {
                        return;
                    }

                    AnalyzerResult analyzerResult = analyzer.CreateStatistic(matchData.Item1, matchData.Item2);

                    DiscordEmbed embed;
                    using (GAFContext context = new GAFContext())
                        embed = GAFBot.Statistic.StatsHandler.GetMatchResultEmbed(analyzerResult.MatchId, context);

                    Coding.Discord.GetChannel((ulong)Program.Config.AnalyzeChannel).SendMessageAsync(embed: embed).Wait();

                    List <BanInfo> bans = new List <BanInfo>();
                    string mline, bannedBy;
                    string[] wSplit;
                    foreach (string line in lineSplit)
                    {
                        if (line.StartsWith("stage", StringComparison.CurrentCultureIgnoreCase))
                        {
                            wSplit               = line.Split('-');
                            string stage         = wSplit[1].TrimStart(' ').TrimEnd(' ');
                            analyzerResult.Stage = stage;

                            continue;
                        }
                        else if (!line.StartsWith(BAN_PATTERN, StringComparison.CurrentCultureIgnoreCase))
                        {
                            continue;
                        }

                        mline  = line.Remove(0, BAN_PATTERN.Length + 1);
                        wSplit = mline.Split(':');

                        bannedBy = wSplit[0];

                        wSplit = wSplit[1].Split(',');

                        string title, artist, version;
                        string[] mSplit;
                        for (int i = 0; i < wSplit.Length; i++)
                        {
                            wSplit[i] = wSplit[i].TrimStart(' ').TrimEnd(' ');
                            int index = wSplit[i].IndexOf('-');
                            mSplit    = new string[2];
                            mSplit[0] = wSplit[i].Substring(0, index);
                            mSplit[1] = wSplit[i].Remove(0, index + 1);

                            mSplit[0] = mSplit[0].TrimStart(' ').TrimEnd(' ');
                            mSplit[1] = mSplit[1].TrimStart(' ').TrimEnd(' ');

                            artist = mSplit[0].TrimStart(' ').TrimEnd(' ');

                            int versionStart = mSplit[1].IndexOf('[');

                            mSplit = mSplit.Where(s => !string.IsNullOrEmpty(s)).ToArray();


                            title   = mSplit[1].Substring(0, versionStart - 1);
                            version = mSplit[1].Substring(versionStart + 1, mSplit[1].Length - versionStart - 2);

                            bans.Add(new BanInfo(artist, title, version, bannedBy));
                        }
                    }
                    if (analyzerResult == null)
                    {
                        Logger.Log("Failed to create result", LogLevel.ERROR);
                        return;
                    }

                    analyzerResult.Bans = bans.ToArray();

                    if (sendToApi && Program.HTTPAPI != null)
                    {
                        Task.Run(() =>
                        {
                            try
                            {
                                Logger.Log("Api stats post result: " + Program.HTTPAPI.SendResults(analyzerResult).Result);
                            }
                            catch (Exception)
                            {
                                Logger.Log("Could not post result to api");
                            }
                        });
                    }

                    if (sendToDatabase)
                    {
                        using (GAFContext context = new GAFContext())
                        {
                            foreach (BanInfo bi in analyzerResult.Bans)
                            {
                                context.BotSeasonBanInfo.Add(new BotSeasonBaninfo()
                                {
                                    MatchId  = analyzerResult.MatchId,
                                    Artist   = bi.Artist,
                                    Title    = bi.Title,
                                    Version  = bi.Version,
                                    BannedBy = bi.BannedBy
                                });
                            }

                            context.SaveChanges();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Log(ex.ToString(), LogLevel.ERROR);

                    Coding.Discord.SendMessage(channel, "~ Place Holder ~\nMatch stats will be available at a later time");
                }
            });
        }
コード例 #10
0
ファイル: MessageModule.cs プロジェクト: Blade12629/GAFBot
        /// <summary>
        /// registers a new user
        /// </summary>
        /// <param name="duser"></param>
        /// <param name="guildId"></param>
        public void Register(DiscordUser duser, ulong guildId = 0)
        {
            BotUsers buser;

            using (GAFContext context = new GAFContext())
                buser = context.BotUsers.FirstOrDefault(b => (ulong)b.DiscordId.Value == duser.Id);

            if (buser != null)
            {
                if (!buser.IsVerified || guildId == 0)
                {
                    return;
                }

                DiscordGuild  guild  = Program.Client.GetGuildAsync(guildId).Result;
                DiscordMember member = guild.GetMemberAsync(duser.Id).Result;
                DiscordRole   role   = member.Roles.FirstOrDefault(r => r.Id == (ulong)Program.Config.VerifiedRoleId);

                if (role == null)
                {
                    role = guild.GetRole((ulong)Program.Config.VerifiedRoleId);
                    member.GrantRoleAsync(role, "Already verified").Wait();
                }
                else if (role != null && !buser.IsVerified)
                {
                    buser.IsVerified = true;

                    using (GAFContext context = new GAFContext())
                    {
                        context.BotUsers.Update(buser);
                        context.SaveChanges();
                    }
                }
            }

            Logger.Log("MessageHandler: Registering new user " + duser.Username, LogLevel.Trace);

            bool autoVerify = false;

            if (guildId > 0)
            {
                DiscordGuild  guild  = Program.Client.GetGuildAsync(guildId).Result;
                DiscordMember member = guild.GetMemberAsync(duser.Id).Result;
                foreach (DiscordRole role in member.Roles)
                {
                    if (role.Id == (ulong)Program.Config.VerifiedRoleId)
                    {
                        autoVerify = true;
                        break;
                    }
                }
            }

            BotUsers user = new BotUsers()
            {
                DiscordId    = (long)duser.Id,
                AccessLevel  = 0,
                IsVerified   = autoVerify,
                Points       = 0,
                PointsPickEm = 0,
                RegisteredOn = DateTime.UtcNow,
                OsuUsername  = ""
            };

            using (GAFContext context = new GAFContext())
            {
                context.BotUsers.Add(user);
                context.SaveChanges();
            }

            Logger.Log("MessageHandler: User registered", LogLevel.Trace);
        }
コード例 #11
0
ファイル: MessageModule.cs プロジェクト: Blade12629/GAFBot
        /// <summary>
        /// Processes newly recieved discord messages
        /// </summary>
        /// <param name="messageArgs">discord message</param>
        public void OnMessageRecieved(MessageCreateEventArgs messageArgs)
        {
            Task.Run(() =>
            {
                try
                {
                    string channel = (messageArgs.Channel == null || string.IsNullOrEmpty(messageArgs.Channel.Name) ? "null" : messageArgs.Channel.Name);

                    //Ignore web-changelog
                    if (messageArgs.Channel.Id == 651838498868953099)
                    {
                        return;
                    }

                    string logMsg = $"MessageHandler: New message: Channel: {channel}: User: {messageArgs.Author.Username}: {messageArgs.Message.Content}";

                    Logger.Log(logMsg);

                    string embed = "";
                    if (messageArgs.Message.Embeds != null && messageArgs.Message.Embeds.Count > 0)
                    {
                        for (int i = 0; i < messageArgs.Message.Embeds.Count; i++)
                        {
                            DiscordEmbed emb = messageArgs.Message.Embeds.ElementAt(i);

                            embed += $"ID: {i}: Title: {emb.Title ?? "null"}, Description: {emb.Description ?? "null"}";

                            if (emb.Fields != null)
                            {
                                foreach (var field in emb.Fields)
                                {
                                    embed += Environment.NewLine + $"Title: {field.Name ?? "null"}, Description: {field.Value ?? "null"}, Inline: {field.Inline}";
                                }
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(embed))
                    {
                        Logger.Log("Embeds: " + embed);
                    }

                    Register(messageArgs.Author);

                    string message = messageArgs.Message.Content;

                    if (messageArgs.Channel.Id == (ulong)Program.Config.AnalyzeChannel)
                    {
                        //check if we are in qualifier stage or not
                        string[] lineSplit = messageArgs.Message.Content.Split(new char[] { '\r', '\n' });
                        lineSplit[0]       = lineSplit[0].Replace("dq!", "");

                        StartAnalyzer(messageArgs);
                        return;
                    }

                    BotUsers buser;
                    using (GAFContext context = new GAFContext())
                        buser = context.BotUsers.FirstOrDefault(b => (ulong)b.DiscordId.Value == messageArgs.Author.Id);

                    //Hoaq == 154605183714852864
                    if (buser.DiscordId == 154605183714852864 && messageArgs.Message.Content.StartsWith("hiss~"))
                    {
                        Coding.Discord.SendMessage(messageArgs.Channel.Id, "https://media.tenor.com/images/bebeb96736fc75a7e1b0bb1a1e9b0359/tenor.gif");
                        return;
                    }

                    if (string.IsNullOrEmpty(message))
                    {
                        return;
                    }

                    if (!char.IsLetterOrDigit(message[0]))
                    {
                        Task.Run(() => Program.CommandHandler.ActivateCommand(messageArgs.Message, (AccessLevel)buser.AccessLevel));
                    }
                }
                catch (Exception ex)
                {
#if DEBUG
                    bool console = true;
#else
                    bool console = false;
#endif
                    Logger.Log(ex.ToString(), LogLevel.ERROR, console);
                }
            });
        }