public void DisplayTweets(string value) { if (value != "") { UserTimelineOptions userOptions = new UserTimelineOptions(); userOptions.APIBaseAddress = "https://api.twitter.com/1.1/"; // <-- needed for API 1.1 userOptions.Count = 20; userOptions.UseSSL = true; // <-- needed for API 1.1 userOptions.ScreenName = value; //<-- replace with yours TwitterResponse <TwitterStatusCollection> timeline = TwitterTimeline.UserTimeline(tokens, userOptions); // collects first 20 tweets from our account int i = 1; foreach (TwitterStatus status in timeline.ResponseObject) { TextBox2.Text += i + ")" + status.Text + Environment.NewLine; i++; } TextBox2.Text += "-----------------------------------------------------------------------" + Environment.NewLine; } else { TextBox2.Text += "Invalid Screen Name"; } }
public void Button1_Click(object sender, EventArgs e) { string Input = TextBox1.Text; string method = Input.Split('(')[0]; int x = Input.Length - 1 - (Input.IndexOf('(') + 1); string value = Input.Substring(Input.IndexOf('(') + 1, x); UserTimelineOptions userOptions = new UserTimelineOptions(); userOptions.APIBaseAddress = "https://api.twitter.com/1.1/"; // <-- needed for API 1.1 userOptions.Count = 5; userOptions.UseSSL = true; // <-- needed for API 1.1 userOptions.ScreenName = value; //<-- replace with yours TwitterResponse <TwitterStatusCollection> timeline = TwitterTimeline.UserTimeline(tokens, userOptions); // collects first 20 tweets from our account int i = 1; //TwitterResponse<TwitterTrendCollection> timelineres = TwitterTrend.Trends(tokens,1); TwitterResponse <TwitterUser> followers = TwitterUser.Show(tokens, value); if (followers.Result == RequestResult.Success) { TextBox2.Text = "Number of followers for " + followers.ResponseObject.ScreenName + " is " + followers.ResponseObject.NumberOfFollowers + Environment.NewLine; } //if (showUserResponse.Result == RequestResult.Success) // { // string screenName = showUserResponse.ResponseObject.ScreenName; // Response.Write(screenName); // Response.Write("<br>"); // Response.Write(showUserResponse.ResponseObject.NumberOfFollowers); // } //FollowersOptions options = new FollowersOptions(); //options.ScreenName = value; //options.UserId = 212250358; //options.UseSSL = true; //TwitterResponse<TwitterUserCollection> Followernames = TwitterFriendship.Followers(tokens, options); //TwitterResponse<TwitterUserCollection> followers = TwitterFriendship.Followers(options); //foreach (var follower in followers.ResponseObject.) //{ // TextBox2.Text += i + ")" + follower + Environment.NewLine; // i++; //} foreach (TwitterStatus status in timeline.ResponseObject) { TextBox2.Text += i + ")" + status.Text + Environment.NewLine; i++; } //Getting trends from a location LocalTrendsOptions trendoptions = new LocalTrendsOptions(); trendoptions.UseSSL = true; // TwitterResponse<TwitterTrendCollection> tr = TwitterTrend.Trends(1); //foreach (TwitterTrend tnds in tr.ResponseObject) //{ // TextBox2.Text += tnds.ToString() + Environment.NewLine; //} }
private TwitterResponse <TwitterStatusCollection> GetTwitterStatus() { TwitterResponse <TwitterStatusCollection> userInfo = new TwitterResponse <TwitterStatusCollection>(); //use cache here if (Page.Cache[string.Format("TweetWrite-{0}", this.ScreenName)] == null) { //create a authorization token of the user OAuthTokens tokens = new OAuthTokens(); tokens.ConsumerKey = this.ConsumerKey; tokens.ConsumerSecret = this.ConsumerSecret; tokens.AccessToken = this.AccessToken; tokens.AccessTokenSecret = this.AccessTokenSecret; //Set the query options UserTimelineOptions Useroptions = new UserTimelineOptions(); Useroptions.ScreenName = this.ScreenName; //Get the account info userInfo = TwitterTimeline.UserTimeline(tokens, Useroptions); HttpContext.Current.Cache.Insert(string.Format("TweetWrite-{0}", this.ScreenName), userInfo, null, DateTime.Now.AddMinutes(Common.CACHEDURATION), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null); } else { userInfo = Page.Cache[string.Format("TweetWrite-{0}", this.ScreenName)] as TwitterResponse <TwitterStatusCollection>; } return(userInfo); }
public static async Task <List <Status> > GetUserTimeline(UserTimelineOptions options) { CheckData(options); HttpRequestMessage reqMsg = OAuthHelper.GetRequest(HttpMethod.Get, USER_TIMELINE, options); return(await GetData <Statuses>(reqMsg)); }
void CheckAlert() { UserTimelineOptions userOptions = new UserTimelineOptions(); userOptions.APIBaseAddress = "https://api.twitter.com/1.1/"; userOptions.Count = 10; userOptions.UseSSL = true; userOptions.ScreenName = "WarframeAlerts"; TwitterResponse <TwitterStatusCollection> timeline = null; try { timeline = TwitterTimeline.UserTimeline(tokens, userOptions); } catch (Exception) { } if (timeline == null || timeline.Content == null) { if (status != ConnectionStatus.Issue) { configWindow.Log("Having trouble reaching Twitter. Will retry every 60 seconds."); } status = ConnectionStatus.Issue; return; } if (status == ConnectionStatus.Connecting) { configWindow.Log("Connected. Scanning for alerts matching your filter..."); } if (status == ConnectionStatus.Issue) { configWindow.Log("Reconnected."); } status = ConnectionStatus.Connected; for (int i = 9; i >= 0; i--) { dynamic tweet = JArray.Parse(timeline.Content)[i]; string createdAt = tweet.created_at; DateTime dt = DateTime.ParseExact(createdAt, "ddd MMM dd HH:mm:ss \"+0000\" yyyy", CultureInfo.InvariantCulture).ToLocalTime(); if (dt <= lastTweetTime) { continue; } lastTweetTime = dt; string text = tweet.text; try { NewAlert(text, dt); } catch (Exception e) { configWindow.Log("Trouble parsing: " + text); configWindow.Log(e.ToString()); } } }
public void parameters_has_username() { string username = Guid.NewGuid().ToString(); UserTimelineOptions options = new UserTimelineOptions(username); options.Parameters.ContainsKey("user_id").ShouldBeFalse(); options.Parameters.ContainsKey("screen_name").ShouldBeTrue(); options.Parameters["screen_name"].ShouldEqual(username); }
public void parameters_has_userId() { const int userId = 999; UserTimelineOptions options = new UserTimelineOptions(userId); options.Parameters.ContainsKey("user_id").ShouldBeTrue(); options.Parameters.ContainsKey("screen_name").ShouldBeFalse(); options.Parameters["user_id"].ShouldEqual(userId.ToString()); }
public static async Task <List <Status> > GetUserTimeline(UserTimelineOptions options) { if (options.User == null) { options.User = AuthenticatedUser.LoadCredentials(); } HttpRequestMessage reqMsg = OAuthHelper.GetRequest(HttpMethod.Get, USER_TIMELINE, options); return(await GetData <Statuses>(reqMsg)); }
public void TweetTimechart(string value) { if (value != "") { Chart1.Visible = true; UserTimelineOptions userOptions = new UserTimelineOptions(); userOptions.APIBaseAddress = "https://api.twitter.com/1.1/"; // <-- needed for API 1.1 userOptions.Count = 20; userOptions.UseSSL = true; // <-- needed for API 1.1 userOptions.ScreenName = value; //<-- replace with yours TwitterResponse <TwitterStatusCollection> timeline = TwitterTimeline.UserTimeline(tokens, userOptions); // collects first 20 tweets from our account int i = 1, Mrng = 0, Afternoon = 0, evening = 0, night = 0; int timeinhrs; foreach (TwitterStatus status in timeline.ResponseObject) { //TextBox2.Text += i + ")" + status.CreatedDate + Environment.NewLine; timeinhrs = status.CreatedDate.Hour; if (timeinhrs > 0 && timeinhrs <= 5) { night++; } else if (timeinhrs > 5 && timeinhrs <= 12) { Mrng++; } else if (timeinhrs > 12 && timeinhrs <= 18) { Afternoon++; } else if (timeinhrs > 18 && timeinhrs <= 22) { evening++; } else if (timeinhrs > 22 && timeinhrs <= 24) { night++; } //i++; } Chart1.Series["Time"].Points.AddXY("Morning", Mrng); Chart1.Series["Time"].Points.AddXY("Afternoon", Afternoon); Chart1.Series["Time"].Points.AddXY("Evening", evening); Chart1.Series["Time"].Points.AddXY("Night", night); } else { TextBox2.Text += "Invalid Screen Name"; } }
/// <summary> /// Initializes a new instance of the <see cref="UserTimelineCommand"/> class. /// </summary> /// <param name="tokens">The request tokens.</param> /// <param name="options">The options.</param> public UserTimelineCommand(OAuthTokens tokens, UserTimelineOptions options) : base(HTTPVerb.GET, "statuses/user_timeline.json", tokens, options) { if (tokens == null && options == null) { throw new ArgumentException("You must supply either OAuth tokens or identify a user in the TimelineOptions class."); } if (options != null && tokens == null && string.IsNullOrEmpty(options.ScreenName) && options.UserId <= 0) { throw new ArgumentException("You must specify a user's screen name or id for unauthorized requests."); } }
/// <summary> /// Initializes a new instance of the <see cref="UserTimelineCommand"/> class. /// </summary> /// <param name="tokens">The request tokens.</param> /// <param name="options">The options.</param> public UserTimelineCommand(OAuthTokens tokens, UserTimelineOptions options) : base(HttpMethod.Get, "statuses/user_timeline.json", tokens, options) { if (tokens == null && options == null) { throw new ArgumentException("You must supply either OAuth tokens or identify a user in the TimelineOptions class."); } if (options != null && tokens == null && string.IsNullOrEmpty(options.ScreenName) && options.UserId <= 0) { throw new ArgumentException("You must specify a user's screen name or id for unauthorized requests."); } }
public void parameters_has_count() { const int count = 99; UserTimelineOptions options; options = new UserTimelineOptions("username", count); options.Parameters.ContainsKey("count").ShouldBeTrue(); options.Parameters["count"].ShouldEqual(count.ToString()); options = new UserTimelineOptions(123, count); options.Parameters.ContainsKey("count").ShouldBeTrue(); options.Parameters["count"].ShouldEqual(count.ToString()); }
/// <summary> /// Initializes the command. /// </summary> public override void Init() { UserTimelineOptions options = this.OptionalProperties as UserTimelineOptions; if (options == null) options = new UserTimelineOptions(); TimelineOptions.Init(this, options); if (options.UserId > 0) this.RequestParameters.Add("user_id", options.UserId.ToString(CultureInfo.InvariantCulture.NumberFormat)); if (!string.IsNullOrEmpty(options.ScreenName)) this.RequestParameters.Add("screen_name", options.ScreenName); }
private void listboxTimeline_SelectionChanged(object sender, SelectionChangedEventArgs e) { ListBox list = sender as ListBox; ListBoxItem twitt = list.SelectedItem as ListBoxItem; if (twitt != null) { UserTimelineOptions options = new UserTimelineOptions(); //options.ScreenName = twitt.Name; options.UserId = decimal.Parse(twitt.Uid); TwitterResponse <TwitterStatusCollection> userTimeline = TwitterTimeline.UserTimeline(_authToken, options); showUserTimeline(userTimeline); } list.SelectedItem = null; }
public async Task GetUserTimeline() { try { UserTimelineOptions options = new UserTimelineOptions { ScreenName = "sebagomez", ExcludeReplies = true, IncludeRTs = false, User = m_user }; List <Sebagomez.TwitterLib.Entities.Status> ss = await UserTimeline.GetUserTimeline(options); Assert.True(ss.Count > 0, "Ningún tweet!"); } catch (Exception ex) { Assert.True(false, Util.ExceptionMessage(ex)); } }
public IEnumerable <Tweet> Tweets(UserTimelineOptions options) { if (options == null) { throw new ArgumentNullException("options"); } const string uri = "https://api.twitter.com/1.1/statuses/user_timeline.json"; IEnumerable <UserTimelineResponse> response = _client.Query <UserTimelineResponse>(uri, options, HttpMethod.Get); if (response == null) { return(Enumerable.Empty <Tweet>()); } return(response.Select(x => x.ToTweet())); }
public async Task GetMaxUserTimeline() { try { int count = 200; UserTimelineOptions options = new UserTimelineOptions { ScreenName = "sebagomez", Count = count, User = m_user }; List <Sebagomez.TwitterLib.Entities.Status> ss = await UserTimeline.GetUserTimeline(options); Assert.True(ss.Count > 0, "Ningún tweet!"); Assert.True(ss.Count <= count, $"No trajo {count}?"); } catch (Exception ex) { Assert.True(false, Util.ExceptionMessage(ex)); } }
public List <Tweet> GetTweetsForUser(string user, decimal?sinceId) { try { UserTimelineOptions uto = new UserTimelineOptions(); uto.Count = 1000; uto.IncludeRetweets = true; uto.ScreenName = user; if (sinceId == null) { uto.SinceStatusId = 0; } else { uto.SinceStatusId = sinceId.Value; } TwitterResponse <TwitterStatusCollection> twitterResponse = TwitterTimeline.UserTimeline(tokens, uto); // TwitterAccount.VerifyCredentials(tokens); List <Tweet> tweets = new List <Tweet>(); if (twitterResponse.Result == RequestResult.Success) { log.Info("Successfully retrieved results for user \"" + user + "\"."); foreach (TwitterStatus status in twitterResponse.ResponseObject) { Tweet t = GetTweetFromStatus(status); if (t != null && t.language != null) { tweets.Add(t); } } } else { log.Warn("Cannot retrieve results for user \"" + user + "\"."); } return(tweets); } catch (Exception ex) { log.Warn("Communication error! Cannot retrieve results for user \"" + user + "\".", ex); return(new List <Tweet>()); } }
/// <summary> /// Initializes the command. /// </summary> public override void Init() { UserTimelineOptions options = this.OptionalProperties as UserTimelineOptions; if (options == null) { options = new UserTimelineOptions(); } TimelineOptions.Init(this, options); if (options.UserId > 0) { this.RequestParameters.Add("user_id", options.UserId.ToString(CultureInfo.InvariantCulture.NumberFormat)); } if (!string.IsNullOrEmpty(options.ScreenName)) { this.RequestParameters.Add("screen_name", options.ScreenName); } }
private StringBuilder showUserTimelineLastX(TwitterUser user, int twittNumber) { getWaitCursor(); UserTimelineOptions options = new UserTimelineOptions(); options.ScreenName = user.ScreenName; options.Count = twittNumber; TwitterResponse <TwitterStatusCollection> userTimeline = TwitterTimeline.UserTimeline(_authToken, options); StringBuilder timelineString = new StringBuilder(); for (int j = 0; j < userTimeline.ResponseObject.Count; j++) { var userStatus = userTimeline.ResponseObject[j]; timelineString.Append(userStatus.CreatedDate).AppendLine(); timelineString.Append(userStatus.Text).AppendLine(); timelineString.AppendLine(); } getDefaultCursor(); return(timelineString); }
/// <summary> /// Get the tweets from the Twitter object /// </summary> /// <param name="PageNumber"></param> /// <returns></returns> private TwitterStatusCollection FetchTweets(int PageNumber) { TwitterStatusCollection tweets = new TwitterStatusCollection(); //cache the tweets here if (Page.Cache[string.Format("Tweet-{0}-{1}", PageNumber, this.ScreenName)] == null) { //set the tokens here OAuthTokens tokens = new OAuthTokens(); tokens.ConsumerKey = this.ConsumerKey; tokens.ConsumerSecret = this.ConsumerSecret; tokens.AccessToken = this.AccessToken; tokens.AccessTokenSecret = this.AccessTokenSecret; UserTimelineOptions options = new UserTimelineOptions(); options.Count = this.TweetCount * PageNumber; options.Page = 1; options.ScreenName = this.ScreenName; //now hit the twitter and get the response tweets = TwitterTimeline.UserTimeline(tokens, options).ResponseObject; if (PageNumber == 1) { HttpContext.Current.Cache.Add(string.Format("Tweet-{0}-{1}", PageNumber, this.ScreenName), tweets, null, DateTime.Now.AddMinutes(Common.CACHEDURATION), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, CacheRemovedCallBack); } else { HttpContext.Current.Cache.Insert(string.Format("Tweet-{0}-{1}", PageNumber, this.ScreenName), tweets, null, DateTime.Now.AddMinutes(Common.CACHEDURATION), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null); } } else { tweets = HttpContext.Current.Cache[string.Format("Tweet-{0}-{1}", PageNumber, this.ScreenName)] as TwitterStatusCollection; } return(tweets); }
public static void UserTimeline() { IAsyncResult asyncResult = TwitterTimelineAsync.UserTimeline( Configuration.GetTokens(), new UserTimelineOptions(), new TimeSpan(0, 2, 0), PerformCommonTimelineTests); asyncResult.AsyncWaitHandle.WaitOne(); UserTimelineOptions User_Options = new UserTimelineOptions(); User_Options.ScreenName = "twitterapi"; User_Options.Count = 8; TwitterResponse <TwitterStatusCollection> timelineResponse = TwitterTimeline.UserTimeline(Configuration.GetTokens(), User_Options); PerformCommonTimelineTests(timelineResponse); timelineResponse = TwitterTimeline.UserTimeline(User_Options); PerformCommonTimelineTests(timelineResponse); }
static void Main(string[] args) { try { //Debug.Assert(false, "Attach VS here!"); Console.OutputEncoding = new UTF8Encoding(); PrintHeader(); BaseAPI.SetMessageAction(message => Console.WriteLine(message)); if (args.Length == 0) { PrintTwits(Timeline.GetTimeline().Result); return; } if (args[0].StartsWith("/")) { string flag = args[0].ToLower().Trim(); switch (flag) { case CLEAR: AuthenticatedUser.ClearCredentials(); Console.WriteLine("User credentials cleared!"); return; case HELP: ShowUsage(); return; case TIME_LINE: PrintTwits(Timeline.GetTimeline().Result); return; case MENTIONS: PrintTwits(Mentions.GetMentions().Result); return; case SEARCH: SearchOptions options = new SearchOptions { Query = string.Join(" ", args).Substring(2), User = AuthenticatedUser.LoadCredentials() }; PrintTwits(Search.SearchTweets(options).Result); return; case LIKES: PrintTwits(Likes.GetUserLikes(new LikesOptions()).Result); return; case USER: if (args.Length != 2) { throw new ArgumentNullException("screenname", "The user' screen name must be provided"); } UserTimelineOptions usrOptions = new UserTimelineOptions { ScreenName = args[1] }; PrintTwits(UserTimeline.GetUserTimeline(usrOptions).Result); return; case STREAMING: if (args.Length != 2) { throw new ArgumentNullException("streaming", "The track must be provided"); } StreammingFilterOptions streamingOptions = new StreammingFilterOptions { Track = args[1] }; Console.WriteLine("Starting live streaming, press ctrl+c to quit"); foreach (Status s in StreamingFilter.GetStreamingTimeline(streamingOptions)) { PrintTwit(s); } return; default: Console.WriteLine($"Invalid flag: {flag}"); ShowUsage(); return; } } if (args[0].StartsWith("\\") || args[0].Length == 1) { Console.WriteLine("Really? do you really wanna twit that?. [T]wit, or [N]o sorry, I messed up..."); ConsoleKeyInfo input = Console.ReadKey(); while (input.Key != ConsoleKey.T && input.Key != ConsoleKey.N) { Console.WriteLine(); Console.WriteLine("[T]wit, or [N]o sorry, I messed up..."); input = Console.ReadKey(); } Console.WriteLine(); if (input.Key == ConsoleKey.N) { Console.WriteLine("That's what I thought! ;)"); return; } } string response = Update.UpdateStatus(string.Join(" ", args)).Result; if (response != "OK") { Console.WriteLine($"Response was not OK: {response}"); } } catch (WebException wex) { Console.WriteLine(wex.Message); HttpWebResponse res = (HttpWebResponse)wex.Response; if (res != null) { UpdateError errors = ShelltwitLib.Helpers.Util.Deserialize <UpdateError>(res.GetResponseStream()); errors.errors.ForEach(e => Console.WriteLine(e.ToString())); } } catch (Exception ex) { PrintException(ex); } finally { #if DEBUG if (Debugger.IsAttached) { Console.WriteLine("Press <enter> to exit..."); Console.ReadLine(); } #endif } Environment.Exit(0); }
public ActionResult Profile(String screenname) { if (Session["LoggedASP"] != null) { ViewData["username"] = ((User)Session["LoggedUser"]).Username; } try { TwitterResponse <TwitterUser> user; if (Session["LoggedTwitter"] != null) { OAuthTokens token = new OAuthTokens(); token.ConsumerKey = ConfigurationManager.AppSettings["consumerKey"]; token.ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]; token.AccessToken = ((User)Session["LoggedUser"]).TwitterToken; token.AccessTokenSecret = ((User)Session["LoggedUser"]).TwitterTokenSecret; user = TwitterUser.Show(token, screenname); } else { user = TwitterUser.Show(screenname); } if (String.IsNullOrEmpty(user.ErrorMessage)) { ViewData["content"] = "<img class='userImg' src='" + user.ResponseObject.ProfileImageLocation.ToString() + "' />Profil de <em>@" + user.ResponseObject.ScreenName + "</em> qui possède l'ID N°" + user.ResponseObject.Id + "<br />Il s'est enregistré sur Twitter le : " + user.ResponseObject.CreatedDate + " et il possède " + user.ResponseObject.NumberOfFollowers + " followers."; UserTimelineOptions options = new UserTimelineOptions(); options.ScreenName = screenname; options.Count = 100; options.IncludeRetweets = true; if (Session["LoggedTwitter"] != null) { OAuthTokens token = new OAuthTokens(); token.ConsumerKey = ConfigurationManager.AppSettings["consumerKey"]; token.ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]; token.AccessToken = ((User)Session["LoggedUser"]).TwitterToken; token.AccessTokenSecret = ((User)Session["LoggedUser"]).TwitterTokenSecret; bool taRaceVanStaen = false; if (screenname.ToLower() == TwitterUser.Show(token, Decimal.Parse(((User)Session["LoggedUser"]).TwitterID)).ResponseObject.ScreenName.ToLower()) { taRaceVanStaen = false; } TwitterResponse <TwitterStatusCollection> truc = TwitterTimeline.UserTimeline(token, options); if (String.IsNullOrEmpty(truc.ErrorMessage)) { foreach (var item in truc.ResponseObject) { if (taRaceVanStaen) { ViewData["tweets"] += "<div class='editTweet'><a href=''>Edit</a> <a href=''>Delete</a></div><div><a href=\"/User/" + item.User.ScreenName + "\">" + item.User.ScreenName + "</a> ---- " + item.Text.Replace("\n", "<br />").ToString() + "</div>"; } else { ViewData["tweets"] += "<div><a href=\"/User/" + item.User.ScreenName + "\">" + item.User.ScreenName + "</a> ---- " + item.Text.Replace("\n", "<br />").ToString() + "</div>"; } } } else { ViewData["tweets"] = "Les tweets de cet utilisateur sont protégés."; } } else { TwitterResponse <TwitterStatusCollection> truc = TwitterTimeline.UserTimeline(options); if (String.IsNullOrEmpty(truc.ErrorMessage)) { foreach (var item in truc.ResponseObject) { ViewData["tweets"] += "<div><a href=\"/User/" + item.User.ScreenName + "\">" + item.User.ScreenName + "</a> ---- " + item.Text.Replace("\n", "<br />").ToString() + "</div>"; } } else { ViewData["tweets"] = "Les tweets de cet utilisateur sont protégés."; } } return(View("Index")); } else { ViewData["errorMessage"] = user.ErrorMessage; return(View("Error")); } } catch (Exception exception) { ViewData["errorMessage"] = exception.Message; return(View("Error")); } }