Beispiel #1
0
        public void Update(DiscordApiData data)
        {
            Name            = data.GetString("name");
            Icon            = data.GetString("icon");
            Splash          = data.GetString("splash");
            RegionId        = data.GetString("region");
            AfkTimeout      = data.GetInteger("afk_timeout").Value;
            IsEmbedEnabled  = data.GetBoolean("embed_enabled") ?? false;
            OwnerId         = data.GetSnowflake("owner_id").Value;
            AfkChannelId    = data.GetSnowflake("afk_channel_id");
            EmbedChannelId  = data.GetSnowflake("embed_channel_id");
            ApplicationId   = data.GetSnowflake("application_id");
            IsWidgetEnabled = data.GetBoolean("widget_enabled") ?? false;
            WidgetChannelId = data.GetSnowflake("widget_channel_id");
            SystemChannelId = data.GetSnowflake("system_channel_id");

            ExplicitContentFilter       = (GuildExplicitContentFilterLevel)data.GetInteger("explicit_content_filter").Value;
            VerificationLevel           = (GuildVerificationLevel)data.GetInteger("verification_level").Value;
            DefaultMessageNotifications = (GuildNotificationOption)(data.GetInteger("default_message_notifications") ?? 0);
            MfaLevel = (GuildMfaLevel)data.GetInteger("mfa_level").Value;

            // Deserialize features
            IList <DiscordApiData> featuresArray = data.GetArray("features");
            List <string>          features      = new List <string>(featuresArray.Count);

            for (int i = 0; i < features.Count; i++)
            {
                features[i] = featuresArray[i].ToString();
            }

            Features = features;

            // Deserialize roles
            Roles.Clear();
            IList <DiscordApiData> rolesArray = data.GetArray("roles");

            for (int i = 0; i < rolesArray.Count; i++)
            {
                DiscordRole role = new DiscordRole(Http, Id, rolesArray[i]);
                Roles[role.Id] = role;
            }

            // Deserialize emojis
            Emojis.Clear();
            IList <DiscordApiData> emojisArray = data.GetArray("emojis");

            for (int i = 0; i < emojisArray.Count; i++)
            {
                DiscordEmoji emoji = new DiscordEmoji(emojisArray[i]);
                Emojis[emoji.Id] = emoji;
            }

            Dirty();
        }
Beispiel #2
0
        void HandleGuildEmojisUpdateEvent(DiscordApiData data)
        {
            Snowflake guildId = data.GetSnowflake("guild_id").Value;

            if (cache.Guilds.TryGetValue(guildId, out MutableGuild mutableGuild))
            {
                // Clear existing emojis
                mutableGuild.Emojis.Clear();

                // Deseralize new emojis
                IList <DiscordApiData> emojisArray = data.GetArray("emojis");
                for (int i = 0; i < emojisArray.Count; i++)
                {
                    DiscordEmoji emoji = new DiscordEmoji(emojisArray[i]);
                    mutableGuild.Emojis[emoji.Id] = emoji;
                }

                // Dirty the guild
                mutableGuild.Dirty();

                // Invoke the event
                OnGuildEmojisUpdated?.Invoke(this, new GuildEventArgs(shard, mutableGuild.ImmutableEntity));
            }
            else
            {
                throw new ShardCacheException($"Guild {guildId} was not in the cache!");
            }
        }
Beispiel #3
0
        void HandleChannelCreateEvent(DiscordApiData data)
        {
            Snowflake          id   = data.GetSnowflake("id").Value;
            DiscordChannelType type = (DiscordChannelType)data.GetInteger("type").Value;

            if (type == DiscordChannelType.DirectMessage)
            {
                // DM channel
                DiscordApiData recipientData = data.GetArray("recipients").First();
                Snowflake      recipientId   = recipientData.GetSnowflake("id").Value;

                MutableUser recipient;
                if (!cache.Users.TryGetValue(recipientId, out recipient))
                {
                    recipient = new MutableUser(recipientId, false, http);
                    cache.Users[recipientId] = recipient;
                }

                recipient.Update(recipientData);

                MutableDMChannel mutableDMChannel;
                if (!cache.DMChannels.TryGetValue(id, out mutableDMChannel))
                {
                    mutableDMChannel     = new MutableDMChannel(id, recipient, http);
                    cache.DMChannels[id] = mutableDMChannel;
                }

                OnDMChannelCreated?.Invoke(this, new DMChannelEventArgs(shard, mutableDMChannel.ImmutableEntity));
            }
            else if (type == DiscordChannelType.GuildText || type == DiscordChannelType.GuildVoice)
            {
                // Guild channel
                Snowflake guildId = data.GetSnowflake("guild_id").Value;

                DiscordGuildChannel channel;

                if (type == DiscordChannelType.GuildText)
                {
                    channel = new DiscordGuildTextChannel(http, data, guildId);
                }
                else if (type == DiscordChannelType.GuildVoice)
                {
                    channel = new DiscordGuildVoiceChannel(http, data, guildId);
                }
                else if (type == DiscordChannelType.GuildCategory)
                {
                    channel = new DiscordGuildCategoryChannel(http, data, guildId);
                }
                else
                {
                    throw new NotImplementedException($"Guild channel type \"{type}\" has no implementation!");
                }

                cache.GuildChannels[id] = channel;

                OnGuildChannelCreated?.Invoke(this, new GuildChannelEventArgs(shard, guildId, channel));
            }
        }
Beispiel #4
0
        void HandleMessageDeleteBulkEvent(DiscordApiData data)
        {
            Snowflake channelId = data.GetSnowflake("channel_id").Value;

            IList <DiscordApiData> idArray = data.GetArray("ids");

            for (int i = 0; i < idArray.Count; i++)
            {
                Snowflake messageId = idArray[i].ToSnowflake().Value;
                OnMessageDeleted?.Invoke(this, new MessageDeleteEventArgs(shard, messageId, channelId));
            }
        }
Beispiel #5
0
        void UpdateRoles(DiscordApiData data)
        {
            IList <DiscordApiData> rolesArray = data.GetArray("roles");

            Snowflake[] roleIds = new Snowflake[rolesArray.Count];

            for (int i = 0; i < rolesArray.Count; i++)
            {
                roleIds[i] = rolesArray[i].ToSnowflake().Value;
            }

            RoleIds = roleIds;
        }
Beispiel #6
0
        void HandleSessionDescription(DiscordApiData payload, DiscordApiData data)
        {
            IList <DiscordApiData> secretKey = data.GetArray("secret_key");

            byte[] key = new byte[secretKey.Count];
            for (int i = 0; i < key.Length; i++)
            {
                key[i] = (byte)secretKey[i].ToInteger();
            }

            string mode = data.GetString("mode");

            log.LogVerbose($"[SessionDescription] mode = {mode}");

            SessionDescriptionQueue.Add(new VoiceSessionDescriptionEventArgs(key, mode));
        }
Beispiel #7
0
        void HandleMessageUpdateEvent(DiscordApiData data)
        {
            // Get author
            DiscordApiData authorData = data.Get("author");

            if (authorData != null)
            {
                Snowflake authorId      = authorData.GetSnowflake("id").Value;
                bool      isWebhookUser = !string.IsNullOrWhiteSpace(data.GetString("webhook_id"));

                MutableUser mutableAuthor;
                if (!cache.Users.TryGetValue(authorId, out mutableAuthor))
                {
                    mutableAuthor         = new MutableUser(authorId, isWebhookUser, http);
                    cache.Users[authorId] = mutableAuthor;
                }

                mutableAuthor.Update(authorData);
            }

            // Get mentioned users
            IList <DiscordApiData> mentionsArray = data.GetArray("mentions");

            if (mentionsArray != null)
            {
                for (int i = 0; i < mentionsArray.Count; i++)
                {
                    DiscordApiData userData = mentionsArray[i];
                    Snowflake      userId   = userData.GetSnowflake("id").Value;

                    MutableUser mutableUser;
                    if (!cache.Users.TryGetValue(userId, out mutableUser))
                    {
                        mutableUser         = new MutableUser(userId, false, http);
                        cache.Users[userId] = mutableUser;
                    }

                    mutableUser.Update(userData);
                }
            }

            // Create message
            DiscordMessage message = new DiscordMessage(http, data);

            OnMessageUpdated?.Invoke(this, new MessageUpdateEventArgs(shard, message));
        }
        void HandleReadyPayload(DiscordApiData payload, DiscordApiData data)
        {
            int port = data.GetInteger("port").Value;
            int ssrc = data.GetInteger("ssrc").Value;

            IList <DiscordApiData> modesArray = data.GetArray("modes");

            string[] modes = new string[modesArray.Count];
            for (int i = 0; i < modes.Length; i++)
            {
                modes[i] = modesArray[i].ToString();
            }

            log.LogVerbose($"[Ready] ssrc = {ssrc}, port = {port}");

            // Notify
            ReadyQueue.Add(new VoiceReadyEventArgs(port, ssrc, modes));
        }
Beispiel #9
0
        void HandleGuildMembersChunkEvent(DiscordApiData data)
        {
            Snowflake guildId = data.GetSnowflake("guild_id").Value;

            // Get every member and ensure they are cached
            IList <DiscordApiData> membersData = data.GetArray("members");

            DiscordGuildMember[] members = new DiscordGuildMember[membersData.Count];
            for (int i = 0; i < membersData.Count; i++)
            {
                DiscordApiData memberData = membersData[i];

                DiscordApiData userData = memberData.Get("user");
                Snowflake      userId   = userData.GetSnowflake("id").Value;

                // Get user
                MutableUser mutableUser;
                if (!cache.Users.TryGetValue(userId, out mutableUser))
                {
                    mutableUser         = new MutableUser(userId, false, http);
                    cache.Users[userId] = mutableUser;
                }

                mutableUser.Update(userData);

                // Get or create member
                MutableGuildMember mutableMember;
                if (!cache.GuildMembers.TryGetValue(guildId, userId, out mutableMember))
                {
                    mutableMember = new MutableGuildMember(mutableUser, guildId, http);
                    mutableMember.Update(memberData);

                    cache.GuildMembers[guildId, userId] = mutableMember;
                }

                members[i] = mutableMember.ImmutableEntity;
            }

            // Fire event
            OnGuildMembersChunk?.Invoke(this, new GuildMemberChunkEventArgs(shard, guildId, members));
        }
Beispiel #10
0
        void LogServerTrace(string prefix, DiscordApiData data)
        {
            IList <DiscordApiData> traceArray = data.GetArray("_trace");

            if (traceArray != null)
            {
                StringBuilder sb = new StringBuilder();

                for (int i = 0; i < traceArray.Count; i++)
                {
                    if (i > 0)
                    {
                        sb.Append(", ");
                    }

                    sb.Append(traceArray[i].ToString());
                }

                log.LogVerbose($"[{prefix}] trace = {sb}");
            }
        }
Beispiel #11
0
        void HandleReadyEvent(DiscordApiData data)
        {
            // Check gateway protocol
            int protocolVersion = data.GetInteger("v").Value;

            if (protocolVersion != GATEWAY_VERSION)
            {
                log.LogError($"[Ready] Gateway protocol mismatch! Expected v{GATEWAY_VERSION}, got {protocolVersion}.");
            }

            // Clear the cache
            cache.Clear();

            // Get the current bot's user object
            DiscordApiData userData = data.Get("user");
            Snowflake      userId   = userData.GetSnowflake("id").Value;

            MutableUser user;

            if (!cache.Users.TryGetValue(userId, out user))
            {
                user = new MutableUser(userId, false, http);
                cache.Users[userId] = user;
            }

            user.Update(userData);

            shard.UserId = userId;

            log.LogInfo($"[Ready] user = {user.Username}#{user.Discriminator}");

            // Get session ID
            sessionId = data.GetString("session_id");

            // Get unavailable guilds
            foreach (DiscordApiData unavailableGuildData in data.GetArray("guilds"))
            {
                Snowflake guildId = unavailableGuildData.GetSnowflake("id").Value;

                cache.AddGuildId(guildId);
                cache.SetGuildAvailability(guildId, false);
            }

            // Get DM channels
            foreach (DiscordApiData dmChannelData in data.GetArray("private_channels"))
            {
                DiscordChannelType type = (DiscordChannelType)dmChannelData.GetInteger("type").Value;
                if (type != DiscordChannelType.DirectMessage)
                {
                    // TODO: Support group DMs
                    continue;
                }

                Snowflake      channelId     = dmChannelData.GetSnowflake("id").Value;
                DiscordApiData recipientData = dmChannelData.GetArray("recipients").First();
                Snowflake      recipientId   = recipientData.GetSnowflake("id").Value;

                MutableUser recipient;
                if (!cache.Users.TryGetValue(recipientId, out recipient))
                {
                    recipient = new MutableUser(recipientId, false, http);
                    cache.Users[recipientId] = recipient;
                }

                recipient.Update(recipientData);

                MutableDMChannel mutableDMChannel;
                if (!cache.DMChannels.TryGetValue(channelId, out mutableDMChannel))
                {
                    mutableDMChannel            = new MutableDMChannel(channelId, recipient, http);
                    cache.DMChannels[channelId] = mutableDMChannel;
                }

                mutableDMChannel.Update(dmChannelData);
            }

            LogServerTrace("Ready", data);

            // Signal that the connection is ready
            handshakeCompleteEvent.Set();
        }
Beispiel #12
0
        void HandleGuildCreateEvent(DiscordApiData data)
        {
            Snowflake guildId = data.GetSnowflake("id").Value;

            bool wasUnavailable = !cache.IsGuildAvailable(guildId);

            // Update guild
            MutableGuild mutableGuild;

            if (!cache.Guilds.TryGetValue(guildId, out mutableGuild))
            {
                mutableGuild          = new MutableGuild(guildId, http);
                cache.Guilds[guildId] = mutableGuild;
            }

            mutableGuild.Update(data);

            // Ensure the cache guildId list contains this guild (it uses a hashset so don't worry about duplicates).
            cache.AddGuildId(guildId);

            // GUILD_CREATE specifics
            // Update metadata
            cache.GuildMetadata[guildId] = new DiscordGuildMetadata(data);

            // Deserialize members
            cache.GuildMembers.Clear(guildId);
            IList <DiscordApiData> membersArray = data.GetArray("members");

            for (int i = 0; i < membersArray.Count; i++)
            {
                DiscordApiData memberData = membersArray[i];

                DiscordApiData userData = memberData.Get("user");
                Snowflake      userId   = userData.GetSnowflake("id").Value;

                MutableUser user;
                if (!cache.Users.TryGetValue(userId, out user))
                {
                    user = new MutableUser(userId, false, http);
                    cache.Users[userId] = user;
                }

                user.Update(userData);

                MutableGuildMember member;
                if (!cache.GuildMembers.TryGetValue(guildId, userId, out member))
                {
                    member = new MutableGuildMember(user, guildId, http);
                    cache.GuildMembers[guildId, userId] = member;
                }

                member.Update(memberData);
            }

            // Deserialize channels
            cache.ClearGuildChannels(guildId);
            IList <DiscordApiData> channelsArray = data.GetArray("channels");

            for (int i = 0; i < channelsArray.Count; i++)
            {
                DiscordApiData     channelData = channelsArray[i];
                DiscordChannelType channelType = (DiscordChannelType)channelData.GetInteger("type");

                DiscordGuildChannel channel = null;
                if (channelType == DiscordChannelType.GuildText)
                {
                    channel = new DiscordGuildTextChannel(http, channelData, guildId);
                }
                else if (channelType == DiscordChannelType.GuildVoice)
                {
                    channel = new DiscordGuildVoiceChannel(http, channelData, guildId);
                }
                else if (channelType == DiscordChannelType.GuildCategory)
                {
                    channel = new DiscordGuildCategoryChannel(http, channelData, guildId);
                }

                if (channel != null)
                {
                    cache.AddGuildChannel(channel);
                }
            }

            // Deserialize voice states
            cache.GuildVoiceStates.Clear(guildId);
            IList <DiscordApiData> voiceStatesArray = data.GetArray("voice_states");

            for (int i = 0; i < voiceStatesArray.Count; i++)
            {
                DiscordVoiceState state = new DiscordVoiceState(guildId, voiceStatesArray[i]);
                UpdateMemberVoiceState(state);
            }

            // Deserialize presences
            cache.GuildPresences.Clear(guildId);
            IList <DiscordApiData> presencesArray = data.GetArray("presences");

            for (int i = 0; i < presencesArray.Count; i++)
            {
                // Presence's in GUILD_CREATE do not contain full user objects,
                // so don't attempt to update them here.

                DiscordApiData presenceData = presencesArray[i];
                Snowflake      userId       = presenceData.LocateSnowflake("user.id").Value;

                cache.GuildPresences[guildId, userId] = new DiscordUserPresence(userId, presenceData);
            }

            // Mark the guild as available
            cache.SetGuildAvailability(guildId, true);

            // Fire event
            if (wasUnavailable)
            {
                OnGuildAvailable?.Invoke(this, new GuildEventArgs(shard, mutableGuild.ImmutableEntity));
            }
            else
            {
                OnGuildCreated?.Invoke(this, new GuildEventArgs(shard, mutableGuild.ImmutableEntity));
            }
        }
        void HandleReadyEvent(DiscordApiData data)
        {
            // Check gateway protocol
            int protocolVersion = data.GetInteger("v").Value;

            if (protocolVersion != GATEWAY_VERSION)
            {
                log.LogError($"[Ready] Gateway protocol mismatch! Expected v{GATEWAY_VERSION}, got {protocolVersion}.");
            }

            // Check shard
            if (shard.Id != 0 || totalShards > 1)
            {
                IList <DiscordApiData> shardData = data.GetArray("shard");
                if (shardData != null)
                {
                    if (shardData.Count > 0 && shardData[0].ToInteger() != shard.Id)
                    {
                        log.LogError($"[Ready] Shard ID mismatch! Expected {shard.Id}, got {shardData[0].ToInteger()}");
                    }
                    if (shardData.Count > 1 && shardData[1].ToInteger() != totalShards)
                    {
                        log.LogError($"[Ready] Total shards mismatch! Expected {totalShards}, got {shardData[1].ToInteger()}");
                    }
                }
            }

            // Clear the cache
            cache.Clear();

            // Get the current bot's user object
            DiscordApiData userData = data.Get("user");
            Snowflake      userId   = userData.GetSnowflake("id").Value;

            MutableUser user;

            if (!cache.Users.TryGetValue(userId, out user))
            {
                user = new MutableUser(userId, false, http);
                cache.Users[userId] = user;
            }

            user.Update(userData);

            shard.UserId = userId;

            log.LogInfo($"[Ready] user = {user.Username}#{user.Discriminator}");

            // Get session ID
            sessionId = data.GetString("session_id");

            // Get unavailable guilds
            foreach (DiscordApiData unavailableGuildData in data.GetArray("guilds"))
            {
                Snowflake guildId = unavailableGuildData.GetSnowflake("id").Value;

                cache.AddGuildId(guildId);
                cache.SetGuildAvailability(guildId, false);
            }

            LogServerTrace("Ready", data);

            // Signal that the connection is ready
            handshakeCompleteEvent.Set();
        }