Пример #1
0
            public Task <List <Message> > GetNewMessages()
            {
                // Do not want the after query before we have populated lastRecieved as it will start fetching messages from the beginning of time
                string query = _lastRecievedMessageId != "0" ? $"?after={_lastRecievedMessageId}" : "";
                Task <HttpResponseMessage> httpResponseTask = DiscordHttpClient.GetAsync($"channels/{Id}/messages{query}");

                Task <List <Message> > messagesDataTask = new Task <List <Message> >(() =>
                {
                    HttpResponseMessage httpResponse = httpResponseTask.Result;
                    if (httpResponse.IsSuccessStatusCode == false)
                    {
                        return(new List <Message>());
                    }

                    string response         = httpResponse.Content.ReadAsStringAsync().Result;
                    List <Message> messages = JsonConvert.DeserializeObject <List <Message> >(response);
                    messages.ForEach((message) => message.Channel = this);

                    //Response always ordered with recent at top. So can take ID from first item
                    if (messages.Count > 0)
                    {
                        _lastRecievedMessageId = messages[0].Id;
                    }
                    return(messages);
                });

                messagesDataTask.Start();
                return(messagesDataTask);
            }
Пример #2
0
 public void SendMessage(Message message)
 {
     string        serializeObject = JsonConvert.SerializeObject(message);
     StringContent content         = new StringContent(serializeObject, Encoding.UTF8, "application/json");
     var           result          = DiscordHttpClient.PostAsync("channels/542319190825238528/messages", content).Result;
     var           resolved        = result.Content.ReadAsStringAsync().Result;
 }
Пример #3
0
        internal DiscordInvite(DiscordHttpClient http, DiscordApiData data)
        {
            this.http = http;

            Code                     = data.GetString("code");
            TargetUserType           = (DiscordInviteTargetUserType?)data.GetInteger("target_user_type");
            ApproximatePresenceCount = data.GetInteger("approximate_presence_count");
            ApproximateMemberCount   = data.GetInteger("approximate_member_count");

            DiscordApiData guildData = data.Get("guild");

            if (guildData != null)
            {
                Guild = new DiscordInviteGuild(guildData);
            }

            DiscordApiData channelData = data.Get("channel");

            if (channelData != null)
            {
                Channel = new DiscordInviteChannel(channelData);
            }

            DiscordApiData userData = data.Get("target_user");

            if (userData != null)
            {
                TargetUser = new DiscordUser(isWebhookUser: false, userData);
            }
        }
Пример #4
0
        internal DiscordWebhook(DiscordHttpClient http, DiscordApiData data)
            : base(data)
        {
            this.http = http;

            GuildId   = data.GetSnowflake("guild_id").Value;
            ChannelId = data.GetSnowflake("channel_id").Value;

            DiscordApiData userData = data.Get("user");

            if (!userData.IsNull)
            {
                User = new DiscordUser(false, userData);
            }

            Name  = data.GetString("name");
            Token = data.GetString("token");

            string avatarHash = data.GetString("avatar");

            if (avatarHash != null)
            {
                Avatar = DiscordCdnUrl.ForUserAvatar(Id, avatarHash);
            }
        }
Пример #5
0
            public Task <List <Channel> > GetChannels()
            {
                // TODO: Handle additional channels being added after bots first pass through
                if (Channels.Count > 0)
                {
                    return(Task.Run(() => Channels));
                }

                Task <HttpResponseMessage> httpResponseTask = DiscordHttpClient.GetAsync($"guilds/{Id}/channels");

                Task <List <Channel> > channelDataTask = new Task <List <Channel> >(() =>
                {
                    HttpResponseMessage httpResponse = httpResponseTask.Result;
                    if (httpResponse.IsSuccessStatusCode == false)
                    {
                        return(new List <Channel>());
                    }

                    string response         = httpResponse.Content.ReadAsStringAsync().Result;
                    List <Channel> channels = JsonConvert.DeserializeObject <List <Channel> >(response);
                    Channels = channels;
                    return(channels);
                });

                channelDataTask.Start();
                return(channelDataTask);
            }
Пример #6
0
        internal DiscordGuildMember(DiscordHttpClient http, DiscordApiData data, Snowflake guildId)
        // We do not specify the base constructor here because the member ID must be
        // manually retrieved, as it is actually the user ID rather than a unique one.
        {
            this.http = http;

            GuildId = guildId;

            Nickname = data.GetString("nick");
            JoinedAt = data.GetDateTime("joined_at").Value;
            IsDeaf   = data.GetBoolean("deaf") ?? false;
            IsMute   = data.GetBoolean("mute") ?? false;

            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;

            DiscordApiData userData = data.Get("user");

            User = new DiscordUser(false, userData);

            Id = User.Id;
        }
Пример #7
0
        public void Run(out string currentWork)
        {
            // Create authenticator using a bot user token.
            currentWork = "initializing (grabbing token)";
            string token = File.ReadAllText(AssemblyPath + "discord_token.txt");

            httpClient = new DiscordHttpClient(token);

            // Create and start a single shard.
            currentWork = "initializing (starting shard)";
            Shard shard = new Shard(token, 0, 1);

            currentWork = "initializing (subscribing methods)";
            // Subscribe to the message creation event.
            shard.Gateway.OnMessageCreated += Gateway_OnMessageCreated;
            // Subscribe to the guild creatino event.
            shard.Gateway.OnGuildCreated += Gateway_OnGuildCreated;


            currentWork = "initializing (Trying to connect)";
            shard.StartAsync().Wait();
            log.Enter("Bot connected!");

            // Wait for the shard to end before closing the program.
            currentWork = "running";
            shard.WaitUntilStoppedAsync().Wait();
        }
Пример #8
0
        internal DiscordIntegration(DiscordHttpClient http, DiscordApiData data)
            : base(data)
        {
            this.http = http;

            Name              = data.GetString("name");
            Type              = data.GetString("type");
            IsEnabled         = data.GetBoolean("enabled");
            IsSyncing         = data.GetBoolean("syncing");
            ExpireBehavior    = data.GetInteger("expire_behavior");
            ExpireGracePeriod = data.GetInteger("expire_grace_period");
            SyncedAt          = data.GetDateTime("synced_at");
            RoleId            = data.GetSnowflake("role_id");

            DiscordApiData userData = data.Get("user");

            if (userData != null)
            {
                User = new DiscordUser(false, userData);
            }

            DiscordApiData accountData = data.Get("account");

            if (accountData != null)
            {
                Account = new DiscordIntegrationAccount(accountData);
            }
        }
Пример #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DiscordRestStageInstanceAPI"/> class.
 /// </summary>
 /// <param name="discordHttpClient">The Discord HTTP client.</param>
 /// <param name="jsonOptions">The JSON options.</param>
 public DiscordRestStageInstanceAPI
 (
     DiscordHttpClient discordHttpClient,
     IOptions <JsonSerializerOptions> jsonOptions
 )
     : base(discordHttpClient, jsonOptions)
 {
 }
        internal DiscordGuildStoreChannel(DiscordHttpClient http, DiscordApiData data, Snowflake?guildId = null)
            : base(http, data, DiscordChannelType.GuildStore, guildId)
        {
            this.http = http;

            Nsfw     = data.GetBoolean("nsfw") ?? false;
            ParentId = data.GetSnowflake("parent_id");
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DiscordRestInteractionAPI"/> class.
 /// </summary>
 /// <param name="discordHttpClient">The Discord HTTP client.</param>
 /// <param name="jsonOptions">The json options.</param>
 public DiscordRestInteractionAPI
 (
     DiscordHttpClient discordHttpClient,
     IOptions <JsonSerializerOptions> jsonOptions
 )
     : base(discordHttpClient, jsonOptions)
 {
 }
Пример #12
0
        public MutableGuildMember(MutableUser user, Snowflake guildId, DiscordHttpClient http)
            : base(http)
        {
            User = user;
            Reference(user);

            GuildId = guildId;
        }
Пример #13
0
        public MutableDMChannel(Snowflake id, MutableUser recipient, DiscordHttpClient http)
            : base(http)
        {
            Id = id;

            Recipient = recipient;
            Reference(recipient);
        }
Пример #14
0
        internal DiscordGuildEmbed(DiscordHttpClient http, Snowflake guildId, DiscordApiData data)
        {
            this.http = http;

            GuildId = guildId;

            Enabled   = data.GetBoolean("enabled").Value;
            ChannelId = data.GetSnowflake("channel_id").Value;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DiscordRestInteractionAPI"/> class.
 /// </summary>
 /// <param name="discordHttpClient">The Discord HTTP client.</param>
 /// <param name="jsonOptions">The json options.</param>
 public DiscordRestInteractionAPI
 (
     DiscordHttpClient discordHttpClient,
     IOptions <JsonSerializerOptions> jsonOptions
 )
 {
     _discordHttpClient = discordHttpClient;
     _jsonOptions       = jsonOptions.Value;
 }
Пример #16
0
 /// <inheritdoc cref="DiscordRestVoiceAPI(DiscordHttpClient)" />
 public CachingDiscordRestVoiceAPI
 (
     DiscordHttpClient discordHttpClient,
     CacheService cacheService
 )
     : base(discordHttpClient)
 {
     _cacheService = cacheService;
 }
Пример #17
0
        public DiscordClient()
        {
            HttpClient = new DiscordHttpClient(this);
            HttpClient.Headers.Add("X-Fingerprint", this.GetFingerprint());

            SuperPropertiesInfo = new SuperPropertiesInformation();
            SuperPropertiesInfo.OnPropertiesUpdated += OnPropertiesUpdated;
            SuperPropertiesInfo.Base64 = "eyJvcyI6IldpbmRvd3MiLCJicm93c2VyIjoiQ2hyb21lIiwiZGV2aWNlIjoiIiwiYnJvd3Nlcl91c2VyX2FnZW50IjoiTW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzc0LjAuMzcyOS4xNjkgU2FmYXJpLzUzNy4zNiIsImJyb3dzZXJfdmVyc2lvbiI6Ijc0LjAiLCJvc192ZXJzaW9uIjoiMTAiLCJyZWZlcnJlciI6IiIsInJlZmVycmluZ19kb21haW4iOiIiLCJyZWZlcnJlcl9jdXJyZW50IjoiIiwicmVmZXJyaW5nX2RvbWFpbl9jdXJyZW50IjoiIiwicmVsZWFzZV9jaGFubmVsIjoic3RhYmxlIiwiY2xpZW50X2J1aWxkX251bWJlciI6Mzk4MjcsImNsaWVudF9ldmVudF9zb3VyY2UiOm51bGx9";
        }
Пример #18
0
        internal DiscordDMChannel(DiscordHttpClient http, MutableDMChannel channel)
            : base(http, DiscordChannelType.DirectMessage)
        {
            this.http = http;

            Id            = channel.Id;
            Recipient     = channel.Recipient.ImmutableEntity;
            lastMessageId = channel.LastMessageId;
        }
Пример #19
0
        internal DiscordGuildVoiceChannel(DiscordHttpClient http, DiscordApiData data, Snowflake?guildId = null)
            : base(http, data, DiscordChannelType.GuildVoice, guildId)
        {
            this.http = http;

            Bitrate   = data.GetInteger("bitrate").Value;
            UserLimit = data.GetInteger("user_limit").Value;
            ParentId  = data.GetSnowflake("parent_id");
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="AbstractDiscordRestAPI"/> class.
 /// </summary>
 /// <param name="discordHttpClient">The Discord-specialized Http client.</param>
 /// <param name="jsonOptions">The Remora-specialized JSON options.</param>
 protected AbstractDiscordRestAPI
 (
     DiscordHttpClient discordHttpClient,
     IOptions <JsonSerializerOptions> jsonOptions
 )
 {
     this.DiscordHttpClient = discordHttpClient;
     this.JsonOptions       = jsonOptions.Value;
 }
 /// <inheritdoc cref="DiscordRestUserAPI(DiscordHttpClient, IOptions{JsonSerializerOptions})" />
 public CachingDiscordRestUserAPI
 (
     DiscordHttpClient discordHttpClient,
     IOptions <JsonSerializerOptions> jsonOptions,
     CacheService cacheService
 )
     : base(discordHttpClient, jsonOptions)
 {
     _cacheService = cacheService;
 }
Пример #22
0
 private void InitHandler(DiscordHttpClient client, Shard shard)
 {
     try {
         handlers.Add(new CoreHandler(client, shard, Commands));
         log.Debug(string.Format(Resources.Culture, Resources.ResourceManager.GetString("CreatedHandler", Resources.Culture), shard.Id, handlers.Count));
     } catch (Exception ex) {
         log.Fatal(ex.ToString());
         Environment.Exit(-1);
     }
 }
Пример #23
0
        public MutableGuild(Snowflake id, DiscordHttpClient http)
            : base(http)
        {
            Id = id;

            Features = new List <string>();

            Emojis = new ShardCacheDictionary <DiscordEmoji>();
            Roles  = new ShardCacheDictionary <DiscordRole>();
        }
Пример #24
0
 public CoreHandler(DiscordHttpClient client, Shard shard, Dictionary <string, Tuple <BaseModule, ILog, MethodInfo> > commands)
 {
     log           = LogManager.GetLogger("Azuki", "Core.Handler");
     this.client   = client;
     this.shard    = shard;
     this.commands = commands;
     shard.Gateway.OnGuildCreated   += DiscoveredGuild;
     shard.Gateway.OnGuildAvailable += DiscoveredGuild;
     shard.Gateway.OnMessageCreated += Gateway_OnMessageCreated;
 }
Пример #25
0
        internal DiscordGuildNewsChannel(DiscordHttpClient http, DiscordApiData data, Snowflake?guildId = null)
            : base(http, data, DiscordChannelType.GuildNews, guildId)
        {
            this.http = http;

            Topic    = data.GetString("topic");
            Nsfw     = data.GetBoolean("nsfw") ?? false;
            ParentId = data.GetSnowflake("parent_id");

            lastMessageId = data.GetSnowflake("last_message_id") ?? default(Snowflake);
        }
Пример #26
0
        internal DiscordDMChannel(DiscordHttpClient http, DiscordApiData data)
            : base(http, data, DiscordChannelType.DirectMessage)
        {
            this.http = http;

            lastMessageId = data.GetSnowflake("last_message_id") ?? default(Snowflake);

            // Normal DM should only ever have exactly one recipient
            DiscordApiData recipientData = data.GetArray("recipients").First();

            Recipient = new DiscordUser(false, recipientData);
        }
Пример #27
0
        internal DiscordGuild(DiscordHttpClient http, MutableGuild guild)
        {
            this.http = http;

            Id = guild.Id;

            Name                        = guild.Name;
            RegionId                    = guild.RegionId;
            AfkTimeout                  = guild.AfkTimeout;
            IsEmbedEnabled              = guild.IsEmbedEnabled;
            VerificationLevel           = guild.VerificationLevel;
            MfaLevel                    = guild.MfaLevel;
            ApplicationId               = guild.ApplicationId;
            IsWidgetEnabled             = guild.IsWidgetEnabled;
            WidgetChannelId             = guild.WidgetChannelId;
            SystemChannelId             = guild.SystemChannelId;
            DefaultMessageNotifications = guild.DefaultMessageNotifications;
            ExplicitContentFilter       = guild.ExplicitContentFilter;
            OwnerId                     = guild.OwnerId;
            AfkChannelId                = guild.AfkChannelId;
            EmbedChannelId              = guild.EmbedChannelId;
            MaxPresences                = guild.MaxPresences;
            MaxMembers                  = guild.MaxMembers;
            VanityUrlCode               = guild.VanityUrlCode;
            Description                 = guild.Description;
            PremiumTier                 = guild.PremiumTier;
            PremiumSubscriptionCount    = guild.PremiumSubscriptionCount;
            PreferredLocale             = guild.PreferredLocale;

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

            if (guild.Splash != null)
            {
                Splash = DiscordCdnUrl.ForGuildSplash(guild.Id, guild.Splash);
            }

            if (guild.Banner != null)
            {
                Splash = DiscordCdnUrl.ForGuildBanner(guild.Id, guild.Banner);
            }

            Features = new List <string>(guild.Features);

            Roles  = guild.Roles.CreateReadonlyCopy();
            Emojis = guild.Emojis.CreateReadonlyCopy();
        }
Пример #28
0
        internal DiscordGuildMember(DiscordHttpClient http, MutableGuildMember member)
        {
            this.http = http;

            GuildId = member.GuildId;

            User = member.User.ImmutableEntity;

            Nickname = member.Nickname;
            JoinedAt = member.JoinedAt;
            IsDeaf   = member.IsDeaf;
            IsMute   = member.IsMute;

            RoleIds = new List <Snowflake>(member.RoleIds);

            Id = member.User.Id;
        }
Пример #29
0
        internal DiscordInviteMetadata(DiscordHttpClient http, DiscordApiData data)
            : base(http, data)
        {
            DiscordApiData inviterData = data.Get("inviter");

            if (inviterData != null)
            {
                Inviter = new DiscordUser(false, inviterData);
            }

            Uses        = data.GetInteger("uses").Value;
            MaxUses     = data.GetInteger("max_uses").Value;
            MaxAge      = data.GetInteger("max_age").Value;
            IsTemporary = data.GetBoolean("temporary").Value;
            CreatedAt   = data.GetDateTime("created_at").Value;
            IsRevoked   = data.GetBoolean("revoked") ?? false;
        }
Пример #30
0
            public Task <List <Guild> > GetCurrentUserGuilds()
            {
                Task <HttpResponseMessage> httpResponseTask = DiscordHttpClient.GetAsync("users/@me/guilds");

                Task <List <Guild> > guildDataTask = new Task <List <Guild> >(() =>
                {
                    HttpResponseMessage httpResponse = httpResponseTask.Result;
                    if (httpResponse.IsSuccessStatusCode == false)
                    {
                        return(new List <Guild>());
                    }

                    string response = httpResponse.Content.ReadAsStringAsync().Result;
                    return(JsonConvert.DeserializeObject <List <Guild> >(response));
                });

                guildDataTask.Start();
                return(guildDataTask);
            }