public void ProcessResults_WithErrors_PopulatesErrorList() { var searchProc = new TwitterSearchRequestProcessor <TwitterSearch> { BaseUrl = "https://api.twitter.com/1.1/search/" }; List <TwitterSearch> searches = searchProc.ProcessResults(SearchErrorJson); Assert.IsNotNull(searches); TwitterSearch search = searches.SingleOrDefault(); Assert.IsNotNull(search); List <TwitterError> errors = search.Errors; Assert.IsNotNull(errors); Assert.AreEqual(2, errors.Count); TwitterError error = errors.FirstOrDefault(); Assert.IsNotNull(error); Assert.AreEqual("tweet", error.ResourceType); Assert.AreEqual("non_public_metrics.impression_count", error.Field); Assert.AreEqual("Field Authorization Error", error.Title); Assert.AreEqual("data", error.Section); Assert.AreEqual("Sorry, you are not authorized to access non_public_metrics.impression_count on a Tweet.", error.Detail); Assert.AreEqual("https://api.twitter.com/2/problems/not-authorized-for-field", error.Type); }
/// <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>()); } }
public void ProcessResults_WithErrors_PopulatesErrorList() { var tweetProc = new TweetRequestProcessor <TweetQuery> { BaseUrl = "https://api.twitter.com/1.1/search/" }; List <TweetQuery> results = tweetProc.ProcessResults(ErrorTweet); Assert.IsNotNull(results); TweetQuery tweetQuery = results.SingleOrDefault(); Assert.IsNotNull(tweetQuery); List <TwitterError> errors = tweetQuery.Errors; Assert.IsNotNull(errors); Assert.AreEqual(1, errors.Count); TwitterError error = errors.FirstOrDefault(); Assert.IsNotNull(error); Assert.AreEqual("Could not find tweet with ids: [1].", error.Detail); Assert.AreEqual("Not Found Error", error.Title); Assert.AreEqual("tweet", error.ResourceType); Assert.AreEqual("ids", error.Parameter); Assert.AreEqual("1", error.Value); Assert.AreEqual("https://api.twitter.com/2/problems/resource-not-found", error.Type); }
/// <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> >()); } }
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>()); } }
/// <summary> /// Checks if the current user (from the auth context) is subscribed to a webhook by Id. /// </summary> /// <param name="webhookId">Webhook Id to check against.</param> /// <returns>true indicates existed subscribtion.</returns> public async Task <Result <bool> > CheckSubscription(string webhookId) { if (string.IsNullOrEmpty(webhookId)) { throw new ArgumentException(nameof(webhookId)); } //TODO: Provide a generic class to make Twitter API Requests. string resourceUrl = $"https://api.twitter.com/1.1/account_activity/webhooks/{webhookId}/subscriptions.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.NoContent) { return(new Result <bool>(true)); } if (!string.IsNullOrEmpty(jsonResponse)) { TwitterError 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>(false)); } return(new Result <bool>(err)); } else { //TODO: Provide a way to return httpstatus code return(new Result <bool>()); } }
/// <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>()); } }
/// <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>()); } }
public Result(TwitterError err) { Error = err; Success = false; }
public static List <TwitterItem> getListItems( TwitterService service, AccountTwitter account, string username, string listNameOrId, decimal listId, string slug, decimal sinceId, DoWorkEventArgs e) { IEnumerable <TwitterStatus> tweets; List <TwitterItem> allTweets = new List <TwitterItem>(); try { if (service == null) { return(new List <TwitterItem>()); } ListTweetsOnListOptions options = new TweetSharp.ListTweetsOnListOptions(); options.Slug = slug; options.ListId = Convert.ToInt64(listId); options.OwnerScreenName = username; service.TraceEnabled = true; options.Count = Properties.Settings.Default.TwitterItemsFetchInPast; if (sinceId > 0) { options.SinceId = Convert.ToInt64(sinceId); } IAsyncResult result = service.BeginListTweetsOnList(options); tweets = service.EndListTweetsOnList(result); if (tweets != null) { foreach (TwitterStatus status in tweets) { if (e != null) { if (e.Cancel) { AppController.Current.Logger.writeToLogfile("Cancel received for timeline"); break; } } if (status.Id < Convert.ToInt64(sinceId)) { continue; } else { TwitterItem item = API.TweetSharpConverter.getItemFromStatus(status, account); if (item != null) { item.SourceListId = listId; allTweets.Add(item); } } } } else { TwitterError error = service.Response.Error; Console.WriteLine(); } } catch (Exception exp) { TwitterError error = service.Response.Error; AppController.Current.sendNotification("ERROR", exp.Message, exp.StackTrace, "", null); } return(allTweets); }
public static void SendTweet(string tweet, string appendUrl, SessionProperties sessionProperties) { if (TwitterService == null) { InitiateTwitterAuthentication(sessionProperties); } if (TwitterService == null) { WebControlManager.SendAndLogErrorMessage(new Exception("TwitterService not initialized"), Parameters.Instance.MailSender, Parameters.Instance.SupportMail); //clear authentication, guess we need to authenticate again? Parameters.Instance.TwitterAccessToken = null; Parameters.Instance.TwitterAccessTokenSecret = null; return; } try { //format the string, replace if (tweet.Contains("&")) { tweet = HttpUtility.HtmlDecode(tweet); } string shortUrl = String.Empty; //parse url to shorturl if (!String.IsNullOrEmpty(appendUrl)) { IBitlyService s = new BitlyService("o_3cpfcndji4", "R_8e203358cb5ca0f68d809419b056b192"); string shortened = s.Shorten(appendUrl); if (shortened != null) { shortUrl = " " + shortened; } } var maxLength = 140 - shortUrl.Length; if (tweet.Length > maxLength) { tweet = tweet.Substring(0, maxLength); } tweet += shortUrl; TwitterService.SendTweet(new SendTweetOptions() { Status = tweet }); // Likely this is an error; we don't have to go fishing for it TwitterError error = TwitterService.Response.Error; TwitterResponse response = TwitterService.Response; if (error != null || response.StatusCode != HttpStatusCode.OK) { // You now know you have a real error from Twitter, and can handle it string message; if (error != null) { message = String.Format("Twitter error: {0} ({1})", error.Message, error.Code); } else { message = String.Format("Twitter response status not ok: {0} ({1})\n{2}", response.StatusDescription, response.StatusCode, response.Response); } WebControlManager.SendAndLogErrorMessage(new Exception(message), Parameters.Instance.MailSender, Parameters.Instance.SupportMail); } } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
private static string FormatTwitterError(TwitterError error) => string.Join(",", error.Errors.Select(x => x.ToString()));
protected TwitterApiException(SerializationInfo info, StreamingContext context) : base(info, context) { this.ErrorResponse = (TwitterError)info.GetValue("ErrorResponse", typeof(TwitterError)); }
public TwitterApiException(TwitterError error, string responseText) : base(FormatTwitterError(error), responseText) { this.ErrorResponse = error; }