Exemplo n.º 1
0
        async Task HandleVoiceServerUpdateEvent(DiscordApiData data)
        {
            Snowflake?guildId = data.GetSnowflake("guild_id");

            if (guildId.HasValue) // Only guild voice channels are supported so far.
            {
                string token    = data.GetString("token");
                string endpoint = data.GetString("endpoint");

                DiscordVoiceConnection connection;
                if (shard.Voice.TryGetVoiceConnection(guildId.Value, out connection))
                {
                    // Notify the connection of the server update
                    await connection.OnVoiceServerUpdated(token, endpoint).ConfigureAwait(false);
                }
                else
                {
                    throw new ShardCacheException($"Voice connection for guild {guildId.Value} was not in the cache!");
                }
            }
            else
            {
                throw new NotImplementedException("Non-guild voice channels are not supported yet.");
            }
        }
Exemplo n.º 2
0
 internal DiscordEmbedThumbnail(DiscordApiData data)
 {
     Url      = data.GetString("url");
     ProxyUrl = data.GetString("proxy_url");
     Width    = data.GetInteger("width").Value;
     Height   = data.GetInteger("height").Value;
 }
Exemplo n.º 3
0
 internal DiscordEmbedAuthor(DiscordApiData data)
 {
     Name         = data.GetString("name");
     Url          = data.GetString("url");
     IconUrl      = data.GetString("icon_url");
     ProxyIconUrl = data.GetString("proxy_icon_url");
 }
 internal DiscordActivityAssets(DiscordApiData data)
 {
     LargeImage = data.GetString("large_image");
     LargeText  = data.GetString("large_text");
     SmallImage = data.GetString("small_image");
     SmallText  = data.GetString("small_text");
 }
Exemplo n.º 5
0
 internal DiscordMessageApplication(DiscordApiData data)
     : base(data)
 {
     CoverImage  = data.GetString("cover_image");
     Description = data.GetString("description");
     Icon        = data.GetString("icon");
     Name        = data.GetString("name");
 }
Exemplo n.º 6
0
 internal DiscordAttachment(DiscordApiData data)
     : base(data)
 {
     FileName = data.GetString("filename");
     Size     = data.GetInteger("size").Value;
     Url      = data.GetString("url");
     ProxyUrl = data.GetString("proxy_url");
     Width    = data.GetInteger("width");
     Height   = data.GetInteger("height");
 }
Exemplo n.º 7
0
 internal DiscordVoiceRegion(DiscordApiData data)
 {
     Id             = data.GetString("id");
     Name           = data.GetString("name");
     SampleHostname = data.GetString("sample_hostname");
     SamplePort     = data.GetInteger("sample_port").Value;
     IsVIPOnly      = data.GetBoolean("vip").Value;
     IsOptimal      = data.GetBoolean("optimal").Value;
     IsDeprecated   = data.GetBoolean("deprecated").Value;
     IsCustom       = data.GetBoolean("custom").Value;
 }
Exemplo n.º 8
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();
        }
Exemplo n.º 9
0
        public void PartialUpdate(DiscordApiData data)
        {
            Username         = data.GetString("username") ?? Username;
            Avatar           = data.GetString("avatar") ?? Avatar;
            HasTwoFactorAuth = data.GetBoolean("mfa_enabled") ?? HasTwoFactorAuth;
            IsVerified       = data.GetBoolean("verified") ?? IsVerified;
            Email            = data.GetString("email") ?? Email;

            // To avoid causing every entity that references this user to be unncessarily
            // dirtied, check to see if any properties actually changed with this update.
            if (Changed())
            {
                Dirty();
            }
        }
Exemplo n.º 10
0
 internal DiscordChannelMention(DiscordApiData data)
     : base(data)
 {
     GuildId = data.GetSnowflake("guild_id").GetValueOrDefault();
     Type    = (DiscordChannelType)(data.GetInteger("type") ?? 0);
     Name    = data.GetString("name");
 }
Exemplo n.º 11
0
        /// <exception cref="DiscordHttpApiException"></exception>
        internal async Task <string> Get()
        {
            DiscordApiData data = await rest.Get("gateway",
                                                 "gateway").ConfigureAwait(false);

            return(data.GetString("url"));
        }
Exemplo n.º 12
0
        void HandleDispatchPayload(DiscordApiData payload, DiscordApiData data)
        {
            sequence = payload.GetInteger("s").Value;
            string eventName = payload.GetString("t");

            OnDispatch?.Invoke(this, new DispatchEventArgs(eventName, data));
        }
Exemplo n.º 13
0
        internal DiscordUserGuild(DiscordApiData data)
            : base(data)
        {
            Name    = data.GetString("name");
            IsOwner = data.GetBoolean("owner").Value;

            string iconHash = data.GetString("icon");

            if (iconHash != null)
            {
                Icon = DiscordCdnUrl.ForGuildIcon(Id, iconHash);
            }

            long permissions = data.GetInt64("permissions").Value;

            Permissions = (DiscordPermission)permissions;
        }
Exemplo n.º 14
0
        public void Update(DiscordApiData data)
        {
            Username         = data.GetString("username");
            Discriminator    = data.GetString("discriminator");
            Avatar           = data.GetString("avatar");
            IsBot            = data.GetBoolean("bot") ?? false;
            HasTwoFactorAuth = data.GetBoolean("mfa_enabled") ?? false;
            IsVerified       = data.GetBoolean("verified") ?? false;
            Email            = data.GetString("email");

            // To avoid causing every entity that references this user to be unncessarily
            // dirtied, check to see if any properties actually changed with this update.
            if (!initialized || Changed())
            {
                Dirty();
            }

            initialized = true;
        }
Exemplo n.º 15
0
        public void Update(DiscordApiData data)
        {
            Nickname = data.GetString("nick");
            JoinedAt = data.GetDateTime("joined_at").Value;
            IsDeaf   = data.GetBoolean("deaf") ?? false;
            IsMute   = data.GetBoolean("mute") ?? false;

            UpdateRoles(data);

            Dirty();
        }
Exemplo n.º 16
0
        /// <summary>
        /// Modifies the current bot's nickname in the specified guild.
        /// <para>Requires <see cref="DiscordPermission.ChangeNickname"/>.</para>
        /// </summary>
        /// <param name="nickname">The new nickname (or null or an empty string to remove nickname).</param>
        /// <returns>Returns the new nickname (or null if the nickname was removed).</returns>
        /// <exception cref="DiscordHttpApiException"></exception>
        public async Task <string> ModifyCurrentUsersNickname(Snowflake guildId, string nickname)
        {
            DiscordApiData requestData = new DiscordApiData();

            requestData.Set("nick", nickname);

            DiscordApiData returnData = await rest.Patch($"guilds/{guildId}/members/@me/nick", requestData,
                                                         $"guilds/{guildId}/members/@me/nick").ConfigureAwait(false);

            return(returnData.GetString("nick"));
        }
Exemplo n.º 17
0
        public void PartialUpdate(DiscordApiData data)
        {
            Nickname = data.GetString("nick") ?? Nickname;

            if (data.ContainsKey("roles"))
            {
                UpdateRoles(data);
            }

            Dirty();
        }
Exemplo n.º 18
0
        internal DiscordVoiceState(Snowflake guildId, DiscordApiData data)
        {
            GuildId = guildId;

            ChannelId = data.GetSnowflake("channel_id");
            UserId    = data.GetSnowflake("user_id").Value;

            SessionId    = data.GetString("session_id");
            IsServerDeaf = data.GetBoolean("deaf").Value;
            IsServerMute = data.GetBoolean("mute").Value;
            IsSelfDeaf   = data.GetBoolean("self_deaf").Value;
            IsSelfMute   = data.GetBoolean("self_mute").Value;
            IsSuppressed = data.GetBoolean("suppress").Value;
        }
Exemplo n.º 19
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));
        }
Exemplo n.º 20
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));
        }
Exemplo n.º 21
0
        void HandleReadyPayload(DiscordApiData payload, DiscordApiData data)
        {
            IPAddress ip   = IPAddress.Parse(data.GetString("ip"));
            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(ip, port, ssrc, modes));
        }
Exemplo n.º 22
0
        internal DiscordUserPresence(Snowflake userId, DiscordApiData data)
        {
            UserId = userId;

            DiscordApiData gameData = data.Get("game");

            if (gameData != null)
            {
                if (gameData.IsNull)
                {
                    Game = null;
                }
                else
                {
                    Game = new DiscordGame(gameData);
                }
            }

            string statusStr = data.GetString("status");

            if (statusStr != null)
            {
                DiscordUserStatus?status = Utils.ParseUserStatus(statusStr);

                if (!status.HasValue)
                {
                    // If we don't have a value for the status yet,
                    // we at least know that they aren't offline.
                    Status = DiscordUserStatus.Online;

                    // However, this should issue a warning.
                    DiscoreLogger.Global.LogWarning($"[DiscordUserPresence] Failed to deserialize status for user {UserId}. " +
                                                    $"status = {statusStr}");
                }
                else
                {
                    Status = status.Value;
                }
            }
        }
Exemplo n.º 23
0
 internal DiscordGame(DiscordApiData data)
 {
     Name = data.GetString("name");
     Type = (DiscordGameType)(data.GetInteger("type") ?? 0);
     Url  = data.GetString("url");
 }
Exemplo n.º 24
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();
        }
Exemplo n.º 25
0
 internal DiscordEmbedFooter(DiscordApiData data)
 {
     Text         = data.GetString("text");
     IconUrl      = data.GetString("icon_url");
     ProxyIconUrl = data.GetString("proxy_icon_url");
 }
Exemplo n.º 26
0
 internal DiscordEmbedField(DiscordApiData data)
 {
     Name     = data.GetString("name");
     Value    = data.GetString("value");
     IsInline = data.GetBoolean("inline").Value;
 }
Exemplo n.º 27
0
 internal DiscordActivitySecrets(DiscordApiData data)
 {
     Join     = data.GetString("join");
     Spectate = data.GetString("spectate");
     Match    = data.GetString("match");
 }
Exemplo n.º 28
0
 internal DiscordActivityEmoji(DiscordApiData data)
 {
     Name     = data.GetString("name");
     Id       = data.GetSnowflake("id");
     Animated = data.GetBoolean("animated") ?? false;
 }
Exemplo n.º 29
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}.");
            }

            // 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();
        }
Exemplo n.º 30
0
 internal DiscordEmbedVideo(DiscordApiData data)
 {
     Url    = data.GetString("url");
     Width  = data.GetInteger("width").Value;
     Height = data.GetInteger("height").Value;
 }