コード例 #1
0
        /// <summary>
        /// Send a direct message to a user by userId, from the current user (using Options).
        /// </summary>
        /// <returns></returns>
        public async Task <Result <DirectMessageResult> > SendAsync(NewDirectMessageObject message)
        {
            var resourceUrl = $"https://api.twitter.com/1.1/direct_messages/events/new.json";

            var jsonObj = JsonConvert.SerializeObject(message);

            HttpResponseMessage response;

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization",
                                                 AuthHeaderBuilder.Build(Options, HttpMethod.Post, resourceUrl));

                response = await client.PostAsync(resourceUrl,
                                                  new StringContent(jsonObj, Encoding.UTF8, "application/json"));
            }

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var msgCreateJson = await response.Content.ReadAsStringAsync();

                var mCreateObj = JsonConvert.DeserializeObject <NewDmResult>(msgCreateJson);
                return(new Result <DirectMessageResult>(mCreateObj.@event));
            }

            var jsonResponse = await response.Content.ReadAsStringAsync();

            if (!string.IsNullOrEmpty(jsonResponse))
            {
                var err = JsonConvert.DeserializeObject <TwitterError>(jsonResponse);
                return(new Result <DirectMessageResult>(err));
            }
            return(new Result <DirectMessageResult>());
        }
コード例 #2
0
ファイル: WebhooksManager.cs プロジェクト: tvcsantos/Tweety
        /// <summary>
        /// Retrieve a list of <see cref="WebhookRegistration"/> associated with the user (from the auth context).
        /// </summary>
        /// <returns></returns>
        public async Task <Result <List <WebhookRegistration> > > GetRegisteredWebhooks()
        {
            string resourceUrl = $"https://api.twitter.com/1.1/account_activity/webhooks.json";

            HttpResponseMessage response;

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", AuthHeaderBuilder.Build(AuthContext, HttpMethod.Get, resourceUrl));

                response = await client.GetAsync(resourceUrl);
            }
            string jsonResponse = await response.Content.ReadAsStringAsync();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                List <WebhookRegistration> subs = JsonConvert.DeserializeObject <List <WebhookRegistration> >(jsonResponse);
                return(new Result <List <WebhookRegistration> >(subs));
            }


            if (!string.IsNullOrEmpty(jsonResponse))
            {
                TwitterError err = JsonConvert.DeserializeObject <TwitterError>(jsonResponse);
                return(new Result <List <WebhookRegistration> >(err));
            }
            else
            {
                return(new Result <List <WebhookRegistration> >());
            }
        }
コード例 #3
0
ファイル: WebhooksManager.cs プロジェクト: tvcsantos/Tweety
        /// <summary>
        /// Unregister a webhook from current user (from the auth context) by Id.
        /// </summary>
        /// <param name="webhookId">The Webhook Id to unregister.</param>
        /// <returns></returns>
        public async Task <Result <bool> > UnregisterWebhook(string webhookId)
        {
            //TODO: Provide a generic class to make Twitter API Requests.

            string resourceUrl = $"https://api.twitter.com/1.1/account_activity/webhooks/{webhookId}.json";

            HttpResponseMessage response;

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", AuthHeaderBuilder.Build(AuthContext, HttpMethod.Delete, resourceUrl));

                response = await client.DeleteAsync(resourceUrl);
            }

            if (response.StatusCode == HttpStatusCode.NoContent)
            {
                return(new Result <bool>(true));
            }

            string jsonResponse = await response.Content.ReadAsStringAsync();

            if (!string.IsNullOrEmpty(jsonResponse))
            {
                TwitterError err = JsonConvert.DeserializeObject <TwitterError>(jsonResponse);
                return(new Result <bool>(err));
            }
            else
            {
                //TODO: Provide a way to return httpstatus code

                return(new Result <bool>());
            }
        }
コード例 #4
0
        /// <summary>
        /// Subscribe current user (from the auth context) to a webhook by Id.
        /// </summary>
        /// <param name="environmentName">The name of the environment to subscribe to.</param>
        /// <returns>true indicates successful subscription.</returns>
        public async Task <Result <bool> > Subscribe(string environmentName)
        {
            if (string.IsNullOrEmpty(environmentName))
            {
                throw new ArgumentException(nameof(environmentName));
            }
            var resourceUrl = $"https://api.twitter.com/1.1/account_activity/all/{environmentName}/subscriptions.json";
            HttpResponseMessage response;

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", AuthHeaderBuilder.Build(Options, HttpMethod.Post, resourceUrl));

                response = await client.PostAsync(resourceUrl, new StringContent("")).ConfigureAwait(false);
            }


            if (response.StatusCode == HttpStatusCode.NoContent)
            {
                return(new Result <bool>(true));
            }

            var jsonResponse = await response.Content.ReadAsStringAsync();

            if (!string.IsNullOrEmpty(jsonResponse))
            {
                var err = JsonConvert.DeserializeObject <TwitterError>(jsonResponse);
                return(new Result <bool>(err));
            }
            return(new Result <bool>());
        }
コード例 #5
0
        /// <summary>
        /// Unregister a webhook from current user (from the auth context) by Id.
        /// </summary>
        /// <param name="webhookId">The Webhook Id to unregister.</param>
        /// <returns></returns>
        public async Task <Result <bool> > UnregisterWebhook(string webhookId, string environmentName)
        {
            //TODO: Provide a generic class to make Twitter API Requests.

            var resourceUrl = $"https://api.twitter.com/1.1/account_activity/all/{environmentName}/webhooks/{webhookId}.json";

            HttpResponseMessage response;

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", AuthHeaderBuilder.Build(Options, HttpMethod.Delete, resourceUrl));
                response = await client.DeleteAsync(resourceUrl).ConfigureAwait(false);
            }

            if (response.StatusCode == HttpStatusCode.NoContent)
            {
                return(new Result <bool>(true));
            }

            var jsonResponse = await response.Content.ReadAsStringAsync();

            if (string.IsNullOrEmpty(jsonResponse))
            {
                return(new Result <bool>());
            }

            var err = JsonConvert.DeserializeObject <TwitterError>(jsonResponse);

            return(new Result <bool>(err));
        }
コード例 #6
0
 public void BuildWithInvalidOptionsShouldFail()
 {
     Assert.ThrowsException <TwitterException>(
         () =>
     {
         AuthHeaderBuilder.Build(_testOptions.Object.Value, HttpMethod.Post, "test_url");
     }, "Invalid Twitter options.");
 }
コード例 #7
0
 public void BuildWithNullUrlShouldFail()
 {
     Assert.ThrowsException <TwitterException>(
         () =>
     {
         AuthHeaderBuilder.Build(_testOptions.Object.Value, HttpMethod.Post, null);
     }, "Invalid Resource Url format.");
 }
コード例 #8
0
        public async Task <Result <MessageCreate> > Send(string toScreenName, string messageText)
        {
            //TODO: Provide a generic class to make Twitter API Requests.

            if (string.IsNullOrEmpty(messageText))
            {
                throw new TweetyException("You can't send an empty message.");
            }
            if (messageText.Length > 140)
            {
                throw new TweetyException("You can't send more than 140 char using this end point, use SendAsync instead.");
            }

            messageText = Uri.EscapeDataString(messageText);
            string resourceUrl = $"https://api.twitter.com/1.1/direct_messages/new.json?text={messageText}&screen_name={toScreenName}";

            HttpResponseMessage response;

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", AuthHeaderBuilder.Build(AuthContext, HttpMethod.Post, resourceUrl));

                response = await client.PostAsync(resourceUrl, new StringContent(""));
            }

            if (response.StatusCode == HttpStatusCode.OK)
            {
                string msgCreateJson = await response.Content.ReadAsStringAsync();

                MessageCreate mCreateObj = JsonConvert.DeserializeObject <MessageCreate>(msgCreateJson);
                return(new Result <MessageCreate>(mCreateObj));
            }

            string jsonResponse = await response.Content.ReadAsStringAsync();

            if (!string.IsNullOrEmpty(jsonResponse))
            {
                TwitterError err = JsonConvert.DeserializeObject <TwitterError>(jsonResponse);
                return(new Result <MessageCreate>(err));
            }
            else
            {
                //TODO: Provide a way to return httpstatus code

                return(new Result <MessageCreate>());
            }
        }
コード例 #9
0
        public void BuildWithValidOptionsAndEmptyParametersShouldReturnHeader()
        {
            var testOptions = new Mock <TwitterOptions>()
            {
                Object =
                {
                    ConsumerKey    = "ConsumerKey",
                    ConsumerSecret = "ConsumerSecret",
                    AccessToken    = "AccessToken",
                    AccessSecret   = "AccessSecret",
                    WebhookUri     = "WebhookUri",
                    Environment    = "Environment"
                }
            };
            var header = AuthHeaderBuilder.Build(testOptions.Object, HttpMethod.Get, "test_url");

            Assert.IsFalse(header.IsNullOrEmpty());
        }
コード例 #10
0
        /// <summary>
        /// Unsubscribe current user (from the auth context) from a webhook by Id.
        /// </summary>
        /// <param name="webhookId">Webhook Id to unsubscribe from.</param>
        /// <returns>true indicates successful deletion.</returns>
        public async Task <Result <bool> > Unsubscribe(string webhookId)
        {
            if (string.IsNullOrEmpty(webhookId))
            {
                throw new ArgumentException(nameof(webhookId));
            }

            //TODO: Provide a generic class to make Twitter API Requests.
            var resourceUrl = $"https://api.twitter.com/1.1/account_activity/webhooks/{webhookId}/subscriptions.json";

            HttpResponseMessage response;

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", AuthHeaderBuilder.Build(Options, HttpMethod.Delete, resourceUrl));

                response = await client.DeleteAsync(resourceUrl).ConfigureAwait(false);
            }

            var jsonResponse = await response.Content.ReadAsStringAsync();

            if (response.StatusCode == HttpStatusCode.NoContent)
            {
                return(new Result <bool>(true));
            }

            if (!string.IsNullOrEmpty(jsonResponse))
            {
                var err = JsonConvert.DeserializeObject <TwitterError>(jsonResponse);
                if (err.Errors.Count == 1 && err.Errors[0].Code == 34)
                {
                    // Twitter API will return : {"code":34,"message":"Sorry, that page does not exist."} if you try to check a webhook with 0 subscribers,
                    // Which means, you're not subscribed.
                    return(new Result <bool>(true));
                }

                return(new Result <bool>(err));
            }
            else
            {
                //TODO: Provide a way to return httpstatus code
                return(new Result <bool>());
            }
        }
コード例 #11
0
ファイル: WebhooksManager.cs プロジェクト: tvcsantos/Tweety
        /// <summary>
        /// Register a new webhook url using the current user (from the auth context).
        /// </summary>
        /// <param name="url">The webhook url to register.</param>
        /// <returns></returns>
        public async Task <Result <WebhookRegistration> > RegisterWebhook(string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentException(nameof(url));
            }

            //TODO: Provide a generic class to make Twitter API Requests.
            string urlParam    = Uri.EscapeUriString(url);
            string resourceUrl = $"https://api.twitter.com/1.1/account_activity/webhooks.json?url={urlParam}";

            HttpResponseMessage response;

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", AuthHeaderBuilder.Build(AuthContext, HttpMethod.Post, resourceUrl));

                response = await client.PostAsync(resourceUrl, new StringContent(""));
            }

            string jsonResponse = await response.Content.ReadAsStringAsync();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                WebhookRegistration sub = JsonConvert.DeserializeObject <WebhookRegistration>(jsonResponse);
                return(new Result <WebhookRegistration>(sub));
            }

            if (!string.IsNullOrEmpty(jsonResponse))
            {
                TwitterError err = JsonConvert.DeserializeObject <TwitterError>(jsonResponse);
                return(new Result <WebhookRegistration>(err));
            }
            else
            {
                //TODO: Provide a way to return httpstatus code

                return(new Result <WebhookRegistration>());
            }
        }
コード例 #12
0
        /// <summary>
        /// Send a direct message to a user by userId, from the current user (using AuthContext).
        /// </summary>
        /// <param name="userId">The Twitter User Id to send the message to.</param>
        /// <param name="messageText">The text of the message, should be less than 10,000 chars.</param>
        /// <returns></returns>
        public async Task <Result <DirectMessageResult> > SendAsync(long userId, string messageText)
        {
            //TODO: Provide a generic class to make Twitter API Requests.

            if (string.IsNullOrEmpty(messageText))
            {
                throw new TweetyException("You can't send an empty message.");
            }

            if (messageText.Length > 10000)
            {
                throw new TweetyException("Invalid message, the length of the message should be less than 10000 chars.");
            }

            if (userId == default(long))
            {
                throw new TweetyException("Invalid userId.");
            }

            string resourceUrl = $"https://api.twitter.com/1.1/direct_messages/events/new.json";

            NewDirectMessageObject newDmEvent = new NewDirectMessageObject();

            newDmEvent.@event = new Event()
            {
                type = "message_create"
            };
            [email protected]_create = new NewEvent_MessageCreate()
            {
                message_data = new NewEvent_MessageData {
                    text = messageText
                }, target = new Target {
                    recipient_id = userId.ToString()
                }
            };
            string jsonObj = JsonConvert.SerializeObject(newDmEvent);


            HttpResponseMessage response;

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", AuthHeaderBuilder.Build(AuthContext, HttpMethod.Post, resourceUrl));


                response = await client.PostAsync(resourceUrl, new StringContent(jsonObj, Encoding.UTF8, "application/json"));
            }

            if (response.StatusCode == HttpStatusCode.OK)
            {
                string msgCreateJson = await response.Content.ReadAsStringAsync();

                NewDmResult mCreateObj = JsonConvert.DeserializeObject <NewDmResult>(msgCreateJson);
                return(new Result <DirectMessageResult>(mCreateObj.@event));
            }

            string jsonResponse = await response.Content.ReadAsStringAsync();

            if (!string.IsNullOrEmpty(jsonResponse))
            {
                TwitterError err = JsonConvert.DeserializeObject <TwitterError>(jsonResponse);
                return(new Result <DirectMessageResult>(err));
            }
            else
            {
                //TODO: Provide a way to return httpstatus code

                return(new Result <DirectMessageResult>());
            }
        }
コード例 #13
0
        /// <summary>
        /// Send a direct message to a user by userId, from the current user (using Options).
        /// </summary>
        /// <param name="userId">The Twitter User Id to send the message to.</param>
        /// <param name="messageText">The Text of the message, should be less than 10,000 chars.</param>
        /// <param name="quickReplies"></param>
        /// <returns></returns>
        public async Task <Result <DirectMessageResult> > SendAsync(long userId, string messageText, IList <string> quickReplies = null)
        {
            if (string.IsNullOrEmpty(messageText))
            {
                throw new TwitterException("You can't send an empty message.");
            }

            if (messageText.Length > 10000)
            {
                throw new TwitterException(
                          "Invalid message, the length of the message should be less than 10000 chars.");
            }

            if (userId == default(long))
            {
                throw new TwitterException("Invalid userId.");
            }

            var resourceUrl = $"https://api.twitter.com/1.1/direct_messages/events/new.json";

            var newDmEvent = new NewDirectMessageObject
            {
                Event = new Event
                {
                    EventType     = "message_create",
                    MessageCreate = new NewEvent_MessageCreate
                    {
                        MessageData = new NewEvent_MessageData {
                            Text = messageText
                        },
                        target = new Target {
                            recipient_id = userId.ToString()
                        }
                    }
                }
            };

            if (quickReplies != null && quickReplies.Any())
            {
                newDmEvent.Event.MessageCreate.MessageData.QuickReply = new NewEvent_QuickReply
                {
                    Options = quickReplies.Select(x => new NewEvent_QuickReplyOption {
                        Label = x
                    }).ToList()
                };
            }
            var jsonObj = JsonConvert.SerializeObject(newDmEvent);

            HttpResponseMessage response;

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization",
                                                 AuthHeaderBuilder.Build(Options, HttpMethod.Post, resourceUrl));

                response = await client.PostAsync(resourceUrl,
                                                  new StringContent(jsonObj, Encoding.UTF8, "application/json"));
            }

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var msgCreateJson = await response.Content.ReadAsStringAsync();

                var mCreateObj = JsonConvert.DeserializeObject <NewDmResult>(msgCreateJson);
                return(new Result <DirectMessageResult>(mCreateObj.@event));
            }

            var jsonResponse = await response.Content.ReadAsStringAsync();

            if (!string.IsNullOrEmpty(jsonResponse))
            {
                var err = JsonConvert.DeserializeObject <TwitterError>(jsonResponse);
                return(new Result <DirectMessageResult>(err));
            }
            return(new Result <DirectMessageResult>());
        }