Пример #1
0
        public static IReadOnlyCollection<PoliticalTweet> LoadTweets( IEnumerable<string> handles )
        {
            var service = new TwitterService( ConsumerKey, ConsumerSecret );
            service.AuthenticateWith( AccessToken, AccessTokenSecret );
            var results = new List<PoliticalTweet>();

            foreach ( var handle in handles.Distinct() )
            {
                try
                {
                    var response = service.ListTweetsOnUserTimeline( new ListTweetsOnUserTimelineOptions
                    {
                        ScreenName = handle,
                        Count = 200,
                        IncludeRts = false,
                        ExcludeReplies = true
                    } );
                    results.AddRange( response.Select( t => new PoliticalTweet( handle, t.Text, t.CreatedDate, t.IdStr ) ) );

                    Debug.WriteLine( $"{service.Response.RateLimitStatus.RemainingHits} remaining hits." );
                    if ( service.Response.RateLimitStatus.RemainingHits <= 0 )
                    {
                        var wait = service.Response.RateLimitStatus.ResetTime.ToUniversalTime() - DateTime.UtcNow;
                        Debug.WriteLine( $"Rate limit reached. Sleeping for {wait}." );
                        Thread.Sleep( wait );
                    }
                }
                catch
                {
                    Debug.WriteLine( $"Skipping {handle}" );
                }
            }

            return results;
        }
Пример #2
0
        public IndexModule()
        {
            Get["/locations/{user}", true] = async (paramaters, ct) =>
                {
                    var service = new TwitterService(ConfigurationManager.AppSettings["TWITTER_CONSUMER_KEY"], ConfigurationManager.AppSettings["TWITTER_CONSUMER_SECRET"]);
                    service.AuthenticateWith(ConfigurationManager.AppSettings["TWITTER_ACCESS_TOKEN"], ConfigurationManager.AppSettings["TWITTER_ACCESS_TOKEN_SECRET"]);
                    string user = paramaters.user.ToString();
                    user.Replace("#", "");

                    var tweets = service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions()
                        {
                            ContributorDetails = true,
                            Count = 100,
                            ExcludeReplies = false,
                            IncludeRts = true,
                            ScreenName = user
                        }).ToList();

                    var tweetsWithLocations = tweets.Where(t => t.Location != null).ToList().OrderBy(t => t.CreatedDate);

                    return Response.AsJson(tweetsWithLocations.Select(t => new
                            {
                                LastTweet = t.TextAsHtml,
                                Location = t.Location,
                                Date =
                                      t.CreatedDate.ToShortDateString() + " " +
                                      t.CreatedDate.ToShortTimeString()
                            })).WithHeaders(new []
                            {
                                new { Header = "Access-Control-Allow-Origin", Value="*" }
                            });
                };
        }
Пример #3
0
 // retrieves all post of the user
 public static IEnumerable<TwitterStatus> GetUserTimeline(TwitterService service, long userId, bool includeRts, bool excludeReplies)
 {
     ListTweetsOnUserTimelineOptions options = new ListTweetsOnUserTimelineOptions ();
     options.UserId = userId;
     options.IncludeRts = includeRts;
     options.ExcludeReplies = excludeReplies;
     return service.ListTweetsOnUserTimeline (options);
 }
Пример #4
0
        public override object GetFieldValue(string fieldValue, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            var settings = context.Service.GetItem<TwitterSettings>(TweetCommand.SettingsPath);
            TwitterService twitterService = new TwitterService(settings.ConsumerKey, settings.ConsumerSecret);
            twitterService.AuthenticateWith(settings.AccessToken, settings.AccessTokenSecret);

            return twitterService.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions() { ScreenName = fieldValue });
        }
        public IEnumerable<TwitterStatus> GetTweetsStatus(string screenName)
        {
            if (instance.GetTweets == null || instance.LastRefresh < DateTime.UtcNow.AddHours(-2))
            {
                var service = new TwitterService(ConfigurationManager.AppSettings["TwitterConsumerKey"].ToString(), ConfigurationManager.AppSettings["TwitterConsumerSecret"].ToString());
                service.AuthenticateWith(ConfigurationManager.AppSettings["TwitterToken"].ToString(), ConfigurationManager.AppSettings["TwitterTokenSecret"].ToString());

                instance.GetTweets = service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions { Count = 150 }).ToList();
                instance.LastRefresh = DateTime.UtcNow;
            }
            return instance.GetTweets;
        }
Пример #6
0
        public void TwitterLoad()
        {
            var twitterApp = new TwitterService("", "");
            twitterApp.AuthenticateWith("", "");

            IEnumerable<TwitterStatus> tweets = twitterApp.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions { ScreenName = "ACCOUNTNAME", Count = 1, });
           if (tweets != null){
                foreach (var tweet in tweets)
                {
                    LatestTweet = tweet.Text;
                }
            }
        }
Пример #7
0
        public IEnumerable <TwitterStatus> GetTweets(string channelName, int tweetsNumber)
        {
            var options = new ListTweetsOnUserTimelineOptions()
            {
                ScreenName = channelName,
                Count      = tweetsNumber
            };

            if (options == null)
            {
                throw new TwitterApplicationExceptions(TwitterServiceExceptions.LoadTweets);
            }
            return(_service.ListTweetsOnUserTimeline(options));
        }
Пример #8
0
        public ActionResult Index()
        {
            string consumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"];
            string consumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"];
            //TwitterService("Consumer Key", "Consumer Secret");
            var service = new TwitterService(consumerKey, consumerSecret);

            //AuthenticatedWith("Access Token", "AccessTokenSecret");
            service.AuthenticateWith("486817944-yhSED5Ysl9QIMHcBtytpxzQizupSftTNGbaxZlEV", "XjLnM06gky1r7pZnLhQCB2uu052qkUatkVqgR7yGvQEne");

            //ScreenName="Screen Name", Count=Number of Tweets /www.twitter.com/screenname.
            IEnumerable<TwitterStatus> tweetsByHandle = service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions { ScreenName = "kare11", Count = 5 });
            //IEnumerable<TwitterStatus> tweetsByHandle = service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions { ScreenName = "HFBoysLax", Count = 5 });
            TwitterSearchResult tsr = service.Search(new SearchOptions { Q = "Paris", Count = 5 });
            IEnumerable<TwitterStatus> tweetsByHashTag = tsr.Statuses;
            IEnumerable<TwitterStatus> tweets = tweetsByHandle.Concat(tweetsByHashTag);

            ViewBag.Tweets = tweets.OrderByDescending(CreatedDate => CreatedDate);
            return View();
        }
Пример #9
0
        /// <summary>
        /// Get Latest Twitter For Workflow
        /// </summary>
        /// <param name="tweets">Tweets</param>
        /// <param name="page">Page</param>
        /// <param name="count">Count</param>
        /// <param name="last">Last</param>
        /// <returns>True if all tweets processed</returns>
        private bool GetLatestTwitterForWorkflow(IList <tweet.TwitterStatus> tweets, int page, int count, ref DateTime last)
        {
            // ListTweetsOnSpecifiedUserTimeline is not defined anymore...
            //var ts = _twitterService.ListTweetsOnSpecifiedUserTimeline(ConfigHelper.TwitterUser, page, count);

            var options = new tweet.ListTweetsOnUserTimelineOptions {
                ScreenName = ConfigHelper.TwitterUser
            };
            var ts = _twitterService.ListTweetsOnUserTimeline(options);

            bool isAll = true;

            if (ts == null)
            {
                return(true);
            }

            foreach (var t in ts)
            {
                last = (last < t.CreatedDate) ? t.CreatedDate : last;
                if (t.CreatedDate <= _twitterData.LastTwitter)
                {
                    isAll = true;
                    break;
                }
                else
                {
                    isAll = false;
                }

                if (_twitterData.LastTwitter < t.CreatedDate &&
                    t.Text.Contains(ConfigHelper.TwitterPattern))
                {
                    tweets.Add(t);
                }
            }

            return(isAll);
        }
Пример #10
0
Файл: Utils.cs Проект: baio/dal
        public static IEnumerable<TwitModel> ReadTweets(bool Cached = true)
        {
            var cache = HttpRuntime.Cache;

            if (Cached && cache["ReadTwits"] != null)
            {
                return (TwitModel[])cache["ReadTwits"];
            }
            else
            {
                var service = new TwitterService(ConfigurationManager.AppSettings["TWITTER_CONSUMER_KEY"], ConfigurationManager.AppSettings["TWITTER_CONSUMER_SECRET"]);
                service.AuthenticateWith(ConfigurationManager.AppSettings["TWITTER_ACCESS_TOKEN"], ConfigurationManager.AppSettings["TWITTER_ACCESS_TOKEN_SECRET"]);

                var tweets = service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions { IncludeRts = true, Count = 2 });
                var r = tweets.Select(p => new TwitModel { Text = p.TextAsHtml, Name = p.Author.ScreenName }).ToArray();

                cache.Add("ReadTwits", r, null, DateTime.MaxValue, new TimeSpan(ReadTwitCacheTimeOut, 0, 0), CacheItemPriority.Default, null);

                return r;

            }
        }
Пример #11
0
        protected void load_tw_data()
        {
            //Session["twscreenname"] = "makhdumi";
            //if (Session["twtoken"] != null)
            //{
            //string updateStatusURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screenname=" + Session["twscreenname"].ToString();

            //string outUrl;
            //string OAuthHeaderPOST = OAuthUtility.GetAuthorizationHeaderForPost_OR_QueryParameterForGET(new Uri(updateStatusURL), callbackUrl, httpMethod.POST.ToString(), oauth_consumer_key, oauth_consumer_secret, oauth_access_token, oauth_token_secret, out outUrl);

            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(outUrl);
            ////request.Method = httpMethod.POST.ToString();
            //request.Headers["Authorization"] = OAuthHeaderPOST;
            //request.Method = "GET";
            //request.GetRequestStream();
            ////byte[] array = Encoding.ASCII.GetBytes(postData);
            ////request.GetRequestStream().Write(array, 0, array.Length);

            if (Session["twscreenname"] != null)
            {

                var service = new TwitterService(ConfigurationManager.AppSettings["twitter.appkey"].ToString(), ConfigurationManager.AppSettings["twitter.appsecret"].ToString());
                //service.AuthenticateWith(ConfigurationManager.AppSettings["twitter.accesstoken"].ToString(), ConfigurationManager.AppSettings["twitter.accesstokensecret"].ToString());
                service.AuthenticateWith(Session["twtoken"].ToString(), Session["twsecret"].ToString());
                ListTweetsOnUserTimelineOptions opt = new ListTweetsOnUserTimelineOptions { ScreenName = Session["twscreenname"].ToString(), Count = 5 };
                //IEnumerable<TwitterStatus> tweets = service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions { ScreenName = Session["twscreenname"].ToString(), Count = 5 });
                IEnumerable<TwitterStatus> tweets = service.ListTweetsOnUserTimeline(opt);
                if (tweets != null)
                {
                    foreach (var tweet in tweets)
                    {
                        twitter.InnerHtml = twitter.InnerHtml + "<li><img style=\"clear: both; float: left;\" src=\"" + tweet.Author.ProfileImageUrl + "\"/>";
                        twitter.InnerHtml = twitter.InnerHtml + "<p style=\"float: left;\" class=\"fblike\"><strong>@" + tweet.Author.ScreenName + "</strong><br>" + tweet.CreatedDate.ToString("MM/dd/yyyy") + "</p><br>";
                        twitter.InnerHtml = twitter.InnerHtml + ("<p style=\"clear: both;\"></p>");
                        twitter.InnerHtml = twitter.InnerHtml + "<p>" + tweet.Text + "</p>";
                        twitter.InnerHtml = twitter.InnerHtml + "</li><hr>";
                    }
                }
            }
            //appendlog(tweets.ToString());

            //}
        }
Пример #12
0
        private static void DoMining()
        {
            using (var db = new TwitterDataContext(_connStr))
            {
                var devTwitters = (from d in db.DevTwitterAccounts
                                   select d).ToList();
                foreach (var devAccount in devTwitters)
                {
                    ListTweetsOnListOptions listTweetOptions = new ListTweetsOnListOptions();

                    var service = new TwitterService(CONSUMER_KEY, CONSUMER_SECRET);
                    service.AuthenticateWith(ACCESS_TOKEN, ACCESS_SECRET);
                    var currentTweets = service.ListTweetsOnUserTimeline(
                        new ListTweetsOnUserTimelineOptions()
                        {
                            Count = 20,
                            ExcludeReplies = false,
                            IncludeRts = false,
                            ScreenName = "@" + devAccount.DevTwitterName,
                            SinceId = null,
                            MaxId = null
                        });

                    foreach (var tweet in currentTweets)
                    {
                        List<TwitterStatus> tweetsToInsert = new List<TwitterStatus>();
                        int? convIdToAddTo = null;

                        //We are basically going to keep on getting the reply-to tweets.
                        var currentTweet = tweet;
                        while (true)
                        {
                            if (currentTweet == null)
                                break;

                            List<Tweet> tweetExists;

                            tweetExists = (from t in db.Tweets
                                           where t.TweetTwitterId == currentTweet.Id
                                           select t).ToList();

                            if (tweetExists.Count > 0)
                            {
                                convIdToAddTo = tweetExists[0].TwitterConversationId;
                                break;
                            }
                            else
                            {
                                tweetsToInsert.Add(currentTweet);
                            }

                            if (currentTweet.InReplyToStatusId != null)
                            {
                                currentTweet = service.GetTweet(
                                    new GetTweetOptions()
                                    {
                                        Id = currentTweet.InReplyToStatusId.Value
                                    });
                            }
                            else
                            {
                                break;
                            }
                        }

                        if (tweetsToInsert.Count > 0)
                        {
                            tweetsToInsert = tweetsToInsert.OrderBy(x => x.CreatedDate).ToList();

                            if (convIdToAddTo == null)
                            {
                                string title = String.Empty;

                                if (tweetsToInsert[0].Text.Length > 60)
                                {
                                    for (int i = 0; i < 60; i++)
                                    {
                                        title += tweetsToInsert[0].Text[i];
                                    }
                                    title += " (...)";
                                }
                                else
                                {
                                    title = tweetsToInsert[0].Text;
                                }

                                TwitterConversation conversation = new TwitterConversation();
                                conversation.TwitterConvTitle = title;
                                conversation.LastBlueResponder = tweet.Author.ScreenName;
                                conversation.LastDevResponseDate = tweet.CreatedDate;
                                conversation.TwitterConvAuthor = tweetsToInsert[0].Author.ScreenName;

                                conversation.BlizzAreaId = (from t in tweetsToInsert
                                                            from d in db.DevTwitterAccounts
                                                            where d.DevTwitterName.ToLower() == t.Author.ScreenName.ToLower()
                                                            select d.BlizzAreaId).ToList()[0];

                                foreach (var twitterTweet in tweetsToInsert)
                                {
                                    Tweet bpTweet = new Tweet();

                                    try
                                    {
                                        var devTwitter = (from d in db.DevTwitterAccounts
                                                          where d.DevTwitterName == twitterTweet.Author.ScreenName.Replace("@", "")
                                                          select d).Single();
                                        bpTweet.DevId = devTwitter.DevId;
                                    }
                                    catch (InvalidOperationException) { /*Then we simply leave DevId as null.*/ }

                                    bpTweet.TweetContent = twitterTweet.TextAsHtml;
                                    bpTweet.TweetDate = twitterTweet.CreatedDate;
                                    bpTweet.TweetTwitterId = twitterTweet.Id;
                                    bpTweet.TwitterUserName = twitterTweet.Author.ScreenName;
                                    bpTweet.TweetContentNonHtml = twitterTweet.Text;
                                    bpTweet.UserAvatarUrl = twitterTweet.Author.ProfileImageUrl;
                                    conversation.LastDevResponseDate = twitterTweet.CreatedDate;
                                    bpTweet.TwitterInResponseToId = twitterTweet.InReplyToStatusId;

                                    conversation.Tweets.Add(bpTweet);
                                }

                                db.TwitterConversations.InsertOnSubmit(conversation);
                                db.SubmitChanges();

                            }
                            else
                            {
                                foreach (var twitterTweet in tweetsToInsert)
                                {
                                    Tweet bpTweet = new Tweet();

                                    try
                                    {
                                        var devTwitter = (from d in db.DevTwitterAccounts
                                                          where d.DevTwitterName == twitterTweet.Author.ScreenName.Replace("@", "")
                                                          select d).Single();
                                        bpTweet.DevId = devTwitter.DevId;
                                    }
                                    catch (InvalidOperationException) { /*Then we simply leave DevId as null.*/ }

                                    bpTweet.TweetContent = twitterTweet.TextAsHtml;
                                    bpTweet.TweetDate = twitterTweet.CreatedDate;
                                    bpTweet.TweetTwitterId = twitterTweet.Id;
                                    bpTweet.TwitterUserName = twitterTweet.Author.ScreenName;
                                    bpTweet.TwitterConversationId = convIdToAddTo.Value;
                                    bpTweet.TweetContentNonHtml = twitterTweet.Text;
                                    bpTweet.UserAvatarUrl = twitterTweet.Author.ProfileImageUrl;
                                    bpTweet.TwitterInResponseToId = twitterTweet.InReplyToStatusId;

                                    var conversation = db.TwitterConversations.Where(x => x.Id == convIdToAddTo).Single();
                                    conversation.LastDevResponseDate = twitterTweet.CreatedDate;

                                    db.Tweets.InsertOnSubmit(bpTweet);
                                    db.SubmitChanges();
                                }
                            }
                        }

                    }

                }
            }
        }
Пример #13
0
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (Frame.CanGoBack)
            {
                ((Frame)Window.Current.Content).BackStack.Clear();
            }

            if (NetworkInterface.GetIsNetworkAvailable())
            {
                //Obtain keys by registering your app on https://dev.twitter.com/apps
                var service = new TwitterService("SEuJKVyiLrpntSmX76mLLK5rV", "2oLc3FgsOC1heh6vyiKlBXDWKnLo2dO9UAgHDxgS6WPnwbh2Rq");
                service.AuthenticateWith("197426566-jB7G6TbKGPVHS84rQ2LezVyZp2WJxR5kabaR5sHN", "ntb1049lvRbdX0k5aZkxlWeEvbAZtZm35ekazZnlwBj05");

                //ScreenName is the profile name of the twitter user.
                service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions() { ScreenName = "PerumBULOG" }, (ts, rep) =>
                {
                    if (rep.StatusCode == HttpStatusCode.OK)
                    {
                        //bind
                        //this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { tweetList.ItemsSource = ts; } );
                    }
                });
            }
            else
            {

                var dialog = new MessageDialog("Please check your internet connestion.").ShowAsync();

            }
        }
        public static void GetTwitterTweetsWithDetails(TwitterService service, double feedId, string LastMaxTweetPostedId, ModelFeed modelFeedScrapperPath, List<ModelFeedsDetailScrappingHelper> listScrappingHelper)
        {
            ModelTwitterFeeds modelTwitterFeeds = new ModelTwitterFeeds();
            ModelTwitterFeedsDetails modelTwitterFeedsDetail = new ModelTwitterFeedsDetails();
            ModelFeedMultimedia modelModelFeedMultimedia = new ModelFeedMultimedia();
            List<ModelFeedMultimedia> lstmodelModelFeedImage = new List<ModelFeedMultimedia>();
            List<ModelTwitterFeedsDetails> lstModelTwitterFeedsDetail = new List<ModelTwitterFeedsDetails>();
            BLLFeed objBLLFeed = new BLLFeed();

            string DetailPageURL = String.Empty;
            try
            {
                //TwitterAccount user = new TwitterAccount.
                //TwitterUser twitterUser =
                //>>GET OTHER USER TIMELINE//BeginListTweetsOnHomeTimeline

                var User_OptionInit = new ListTweetsOnUserTimelineOptions { ScreenName = modelFeedScrapperPath.FeedChannelName, Count = 20, ExcludeReplies = true };
                var User_Tweets = service.ListTweetsOnUserTimeline(User_OptionInit);
                /*
                var profilebanner = service.GetUserProfile(new GetUserProfileOptions() { IncludeEntities = true, SkipStatus = true });
                if (profilebanner != null)
                {
                    //profilebanner.ContributorsEnabled
                    //profilebanner.CreatedDate
                    modelTwitterFeeds.UserPageDesc = profilebanner.Description;
                    //profilebanner.FavouritesCount;
                    modelTwitterFeeds.UserPageFollowers = profilebanner.FollowersCount;
                    //profilebanner.FollowRequestSent;
                    //profilebanner.FriendsCount;
                    modelTwitterFeeds.UserPageId = profilebanner.Id;
                    //profilebanner.IsDefaultProfile;
                    //profilebanner.IsGeoEnabled;
                    //profilebanner.IsProfileBackgroundTiled;
                    //profilebanner.IsProtected;
                    //profilebanner.IsTranslator;
                    //profilebanner.IsVerified;
                    modelTwitterFeeds.UserPageLanguage = profilebanner.Language;
                    //profilebanner.ListedCount;
                    //profilebanner.Location;
                    modelTwitterFeeds.UserPageTitle = profilebanner.Name;
                    //profilebanner.ProfileBackgroundColor;
                    //profilebanner.ProfileBackgroundImageUrl;
                    //profilebanner.ProfileBackgroundImageUrlHttps;
                    modelTwitterFeeds.UserPageLogoImage = profilebanner.ProfileImageUrl;
                    //profilebanner.ProfileImageUrlHttps;
                    //profilebanner.ProfileLinkColor;
                    //profilebanner.ProfileSidebarBorderColor;
                    //profilebanner.ProfileSidebarFillColor;
                    //profilebanner.ProfileTextColor;
                    //profilebanner.RawSource;
                    modelTwitterFeeds.UserScreenName = profilebanner.ScreenName;
                    //profilebanner.Status;
                    //profilebanner.StatusesCount;
                    //profilebanner.TimeZone;

                    //JObject o = new JObject(new JProperty("Name", "John Smith"),new JProperty("BirthDate", new DateTime(1983, 3, 20)));
                    JObject obj = (JObject)JsonConvert.DeserializeObject(profilebanner.RawSource);
                    if (obj != null)
                    {
                        if (obj["user"]["profile_banner_url"] != null)
                        {
                            modelTwitterFeeds.UserPageCoverImageURL = (string)obj["user"]["profile_banner_url"];
                        }
                    }
                }
                  */
                string TweetText = String.Empty;
                int tweetCountFirstRun = 0;
                foreach (var tweet in User_Tweets)
                {
                    if (!String.IsNullOrEmpty(LastMaxTweetPostedId))
                    {
                        if (LastMaxTweetPostedId.ToLower().Trim() == tweet.IdStr.ToLower().Trim())
                        {
                            break;
                        }
                    }
                    modelTwitterFeedsDetail = new ModelTwitterFeedsDetails();
                    modelModelFeedMultimedia = new ModelFeedMultimedia();
                    var userDetail = tweet.User;
                    if (tweet != null)
                    {
                        if (tweetCountFirstRun == 0)
                        {
                            if (userDetail != null)
                            {
                                modelTwitterFeeds.FeedId = feedId;
                                modelTwitterFeeds.UserPageId = tweet.User.Id;
                                modelTwitterFeeds.UserPageTitle = tweet.User.Name;
                                modelTwitterFeeds.UserScreenName = tweet.User.ScreenName;
                                modelTwitterFeeds.UserPageDesc = tweet.User.Description;
                                modelTwitterFeeds.UserPageLanguage = tweet.User.Language;
                                modelTwitterFeeds.UserPageFollowers = tweet.User.FollowersCount;
                                //modelTwitterFeeds.UserPageCoverImageURL = tweet.User.ProfileBackgroundImageUrl;
                                modelTwitterFeeds.UserPageLogoImage = tweet.User.ProfileImageUrl;
                                //JObject o = new JObject(new JProperty("Name", "John Smith"),new JProperty("BirthDate", new DateTime(1983, 3, 20)));
                                JObject obj = (JObject)JsonConvert.DeserializeObject(tweet.RawSource);
                                if (obj != null)
                                {
                                    if (obj["user"]["profile_banner_url"] != null)
                                    {
                                        modelTwitterFeeds.UserPageCoverImageURL = (string)obj["user"]["profile_banner_url"];
                                    }
                                }
                            }
                            tweetCountFirstRun++;
                        }
                        var st1 = tweet.Text.ToSafeString(); //string
                        TweetText = tweet.Text;
                        //modelTwitterFeedsDetail.TwitterPageId;
                        modelTwitterFeedsDetail.FeedPostedtId = tweet.Id;
                        modelTwitterFeedsDetail.FeedText = String.Empty;
                        modelTwitterFeedsDetail.FeedLanguage = tweet.Language;
                        modelTwitterFeedsDetail.FeedPostDate = tweet.CreatedDate;

                        modelTwitterFeedsDetail.FeedTextDetail = "";

                        var st2 = tweet.Source; //string
                        var st3 = tweet.TextAsHtml; //string
                        var st4 = tweet.TextDecoded; //string
                        var st5 = tweet.RetweetedStatus; //TwitterStatus
                        var st6 = tweet.RetweetCount; //int
                        var st7 = tweet.RawSource; //string
                        var st8 = tweet.Place; //TwitterPlace
                        var st9 = tweet.Location; //TwitterGeoLocation
                        var st10 = tweet.Language; //string
                        var st11 = tweet.IsTruncated; //bool
                        var st12 = tweet.IsRetweeted; //bool
                        var st13 = tweet.IsPossiblySensitive; //bool is nullable
                        var st14 = tweet.IsFavorited; //bool
                        var st15 = tweet.InReplyToUserId; //long is nullable
                        var st16 = tweet.InReplyToStatusId; //long is nullable
                        var st17 = tweet.InReplyToScreenName; //string
                        var st18 = tweet.IdStr; //string
                        var st19 = tweet.Id; //long
                        var st20 = tweet.FavoriteCount; //int
                        var st21 = tweet.ExtendedEntities; //TwitterExtendedEntities
                        var st22 = tweet.Entities; //TwitterEntities
                        var twitterEntities = new TwitterEntities();
                        twitterEntities = tweet.Entities;
                        IList<TwitterUrl> twitterUrl = twitterEntities.Urls; //List<TwitterUrl>
                        if (twitterUrl != null && twitterUrl.Count > 0)
                        {
                            foreach (var url in twitterUrl)
                            {
                                var url1 = url.DisplayUrl; //string
                                var url2 = url.EndIndex; //int
                                var url3 = url.EntityType; //TwitterEntityType
                                var entityType = url3;
                                //4 Entity Types are Defined
                                //TwitterEntityType.HashTag; //0
                                //TwitterEntityType.Mention; //1
                                //TwitterEntityType.Url; //2
                                //TwitterEntityType.Media; //3

                                var url4 = url.ExpandedValue; //string
                                var url5 = url.Indices; //IList<int>
                                var url6 = url.StartIndex; //int
                                var url7 = url.Value; //string

                                //MODEL DATA //Tweet Detail Page URL
                                if (!String.IsNullOrEmpty(url.ExpandedValue))
                                {
                                    modelTwitterFeedsDetail.FeedDetailPageURL = url.ExpandedValue.Trim();
                                }
                                else if (!String.IsNullOrEmpty(url.Value))
                                {
                                    if (String.IsNullOrEmpty(modelTwitterFeedsDetail.FeedDetailPageURL))
                                    {
                                        modelTwitterFeedsDetail.FeedDetailPageURL = url.Value.Trim();
                                    }
                                }
                                TweetText = TweetText.Trim().Replace(url.Value, String.Empty).Trim();
                            }
                        }
                        IList<TwitterMedia> twitterMedia = twitterEntities.Media; //List<TwitterMedia>
                        foreach (var media in twitterMedia)
                        {
                            var media1 = media.DisplayUrl; //string
                            var media2 = media.EndIndex; //int
                            var media3 = media.EntityType; //TwitterEntity
                            var media4 = media.ExpandedUrl; //string
                            var media5 = media.Id; //long
                            var media6 = media.IdAsString; //string
                            var media7 = media.Indices; //IList<int>
                            var media8 = media.MediaType; //TwitterMediaType
                            var twitterMediaType = media8;

                            /*Three Types of MediaType
                            TwitterMediaType.Photo; //0
                            TwitterMediaType.Video; //1
                            TwitterMediaType.AnimatedGif; //2
                            */

                            var media9 = media.MediaUrl; //string
                            var media10 = media.MediaUrlHttps; //string
                            //var FeedImageURLhttp  = media.MediaUrl; for Http Image
                            //var FeedImageURLhttps  =  media.MediaUrlHttps; for Https Image
                            var media11 = media.Sizes; //TwitterMediaSizes
                            var twitterMediaSizes = media11;
                            //media11.Large
                            //media11.Medium
                            //media11.Small
                            //media11.Thumb
                            var media12 = media.StartIndex; //int
                            var media13 = media.Url; //string
                            //MODEL DATA
                            string tweetMultimediaURL = !String.IsNullOrEmpty(media.Url.Trim()) ? media.Url.Trim() : String.Empty;
                            TweetText = TweetText.Trim().Replace(media.Url, String.Empty).Trim();
                            if (!String.IsNullOrEmpty(tweetMultimediaURL))
                            {
                                modelModelFeedMultimedia.MultiMediaURL = tweetMultimediaURL;
                                modelModelFeedMultimedia.MultiMediaType = Convert.ToInt32(media.MediaType);
                                //Add model object to list
                                //lstmodelModelFeedImage.Add(modelModelFeedMultimedia);
                                modelTwitterFeedsDetail.FeedMultimediaList.Add(modelModelFeedMultimedia);
                            }

                        }
                        IList<TwitterHashTag> twitterHashTag = twitterEntities.HashTags; //List<TwitterHashTag>
                        foreach (var hashTag in twitterHashTag)
                        {
                            var ht1 = hashTag.EndIndex;
                            var ht2 = hashTag.EntityType;
                            var ht3 = hashTag.Indices;
                            var ht4 = hashTag.StartIndex;
                            var ht5 = hashTag.Text;
                            // hashTagText for refine Tweet Text
                            TweetText = TweetText.Trim().Replace("#" + hashTag.Text, string.Empty).Trim();
                        }
                        TweetText = TweetText.Replace("\n", String.Empty).Trim();
                        var st23 = tweet.CreatedDate; //DateTime
                        var st24 = tweet.Author; //ITweeter

                        var ProfileImageURL = st24.ProfileImageUrl;
                        var ss = st24.RawSource;
                        var screenName = st24.ScreenName;
                        modelTwitterFeedsDetail.FeedText = TweetText;

                        //string DetailPageSelector = "div.story-body__inner p:not(:first-of-type)";
                        if (!String.IsNullOrEmpty(modelTwitterFeedsDetail.FeedDetailPageURL))
                        {
                            Uri DetailPageURI = new Uri(modelTwitterFeedsDetail.FeedDetailPageURL);
                            string DetailPageTextSelector = String.Empty;
                            string DetailPageImageSelector = String.Empty;
                            ModelFeedsDetailScrappingHelper rowDetailHelper = listScrappingHelper.Where(m => m.HostName.Contains(DetailPageURI.Host.Trim().ToLower())).FirstOrDefault();
                            if (rowDetailHelper != null)
                            {
                                DetailPageTextSelector = rowDetailHelper.DetailPagePath;
                                DetailPageImageSelector = rowDetailHelper.DetailPageImagePath;
                            }
                            /*
                            if (DetailPageURI.Host.Trim().ToLower().Contains("cnn"))
                            {
                                //bbc.com Text Details= //div[@class='story-body'] //p[position()>=1]
                                //bbc.com img = //div[@class='story-body__inner'] //img[@class='js-image-replace']
                                //cnn = ////p[@dir='RTL']js-image-replace
                                DetailPageTextSelector = "//div[contains(@class, 'article-left')] //p";
                                DetailPageImageSelector = "//div[contains(@class, 'gallery-big-images')] //img";
                            }
                            else if (DetailPageURI.Host.Trim().ToLower().Contains("soundcloud"))
                            {
                                DetailPageTextSelector = "//div[contains(@class, 'sc-type-small')] //p";
                                DetailPageImageSelector = "//div[@class='article-left'] //p";
                            }
                             */
                            HtmlDocument requestedDoc = ScrapeDetailfromPage(DetailPageURI.AbsoluteUri);
                            if (requestedDoc != null)
                            {
                                //if Details Page Selector Text not found then not send request
                                if (!String.IsNullOrEmpty(DetailPageTextSelector))
                                {
                                    string detailTextFromURL = ScrapeTextfromDetailPage(requestedDoc, DetailPageTextSelector);
                                    modelTwitterFeedsDetail.FeedTextDetail = detailTextFromURL;
                                }
                                //if default twitter post not have any multimedia type then
                                if (modelTwitterFeedsDetail.FeedMultimediaList.Count <= 0)
                                {
                                    //if Details Page Selector Image not found then not send request
                                    if (!String.IsNullOrEmpty(DetailPageImageSelector))
                                    {
                                        modelTwitterFeedsDetail.FeedMultimediaList = ScrapeImageDetailfromPage(requestedDoc, DetailPageImageSelector);
                                        //if details page not found on detected tag & Tweet having Image and Embeded Video on Details page
                                        // Then we make a new request to scrape twitter create image from sperate static created request
                                        if (modelTwitterFeedsDetail.FeedMultimediaList.Count <= 0)
                                        {
                                            //Sample URI for Video Image get://https://twitter.com/cnnarabic/status/678548429530906624
                                            //https://twitter.com/i/cards/tfw/v1/678585688783257600?cardname=summary_large_image
                                            //https://twitter.com/i/cards/tfw/v1/678585688783257600
                                            //string StaticImageURI = "https://twitter.com/" + modelTwitterFeeds.UserScreenName.Trim() + "//status/" + modelTwitterFeedsDetail.FeedPostId;
                                            string StaticImageURI = "https://twitter.com/i/cards/tfw/v1/" + tweet.Id;
                                            HtmlDocument VideoImageRequestedDoc = ScrapeDetailfromPage(StaticImageURI);
                                            string staticImageSelector = "//div[contains(@class, 'SummaryCard-image')] //img";
                                            modelTwitterFeedsDetail.FeedMultimediaList = ScrapeImageDetailfromPage(VideoImageRequestedDoc, staticImageSelector);
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            modelTwitterFeedsDetail.FeedTextDetail = String.Empty;
                        }
                    }

                    lstModelTwitterFeedsDetail.Add(modelTwitterFeedsDetail);
                }
                modelTwitterFeeds.TwitterFeedDetails = lstModelTwitterFeedsDetail;
                objBLLFeed.InsertTwitterScrappedData(modelTwitterFeeds);
                //StartSafeScrappedData(modelTwitterFeeds, modelFeed);
            }

            catch (Exception ex)
            {

                throw ex;
            }
        }
Пример #15
0
        private void DeserialiseTweetsOnTimeLine(int? Items )
        {
            var service = new Tweet.TwitterService(this.OAuthRequest.consumerKey, this.OAuthRequest.consumerSecret);
             service.AuthenticateWith(this.OAuthRequest.accessToken, this.OAuthRequest.accessTokenSecret);
             var options = new Tweet.ListTweetsOnUserTimelineOptions();
             options.ScreenName = this.username;
             options.IncludeRts = true;
             if (Items != null) options.Count = Items;
             var t  = service.ListTweetsOnUserTimeline(options);

             foreach (var tweet in t)
             {
                 clsTweet e = new clsTweet(tweet.Id,tweet.Text,tweet.TextAsHtml,"",tweet.CreatedDate,tweet.Author.ScreenName,tweet.Author.ProfileImageUrl);
                 _entries.Add(e);
             }
             service = null;
             options = null;
        }
Пример #16
0
        private void appbar_button1_Click(object sender, EventArgs e)
        {
            listdata.Visibility = Visibility.Collapsed;
            listdata2.Visibility = Visibility.Collapsed;
            listdata3.Visibility = Visibility.Collapsed;
            listdata4.Visibility = Visibility.Collapsed;
            loadtext.Visibility = Visibility.Visible;
            pgbar.Visibility = Visibility.Visible;
            var item = (PivotItem)title.SelectedItem;
            string header = (string)item.Header;
            service = new TwitterService("g8F2KdKH40gGp9BXemw13Q", "OyFRFsI05agcJtURtLv8lpYbYRwZAIL5gr5xQNPW0Q");
            service.AuthenticateWith((string)settings["twitter_token"], (string)settings["twitter_tokensecret"]);
            if (header == "recent")
            {
                service.ListTweetsOnFriendsTimeline(0, 40,
                (tweets, response) =>
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        DateTime ti = DateTime.Now;
                        DateTime now = ti.ToUniversalTime();

                        lists = new List<Tweet>();
                        foreach (var tweet in tweets)
                        {
                            Tweet tv = new Tweet();
                            TimeSpan tsp = now - tweet.CreatedDate;
                            tv.id = tweet.Id;
                            tv.name = tweet.User.ScreenName;
                            tv.thumb_img = tweet.User.ProfileImageUrl;
                            tv.text = tweet.Text + "\n";

                            if (tsp.Days > 0)
                                tv.time = tsp.Days + "일 전";
                            else if (tsp.Hours > 0)
                                tv.time = tsp.Hours + "시간 전";
                            else
                                tv.time = tsp.Minutes + "분 전";

                            lists.Add(tv);
                        }
                        Dispatcher.BeginInvoke(delegate()
                        {
                            if (lists.Count > 0)
                            {
                                loadtext.Visibility = Visibility.Collapsed;
                                pgbar.Visibility = Visibility.Collapsed;
                                listdata.ItemsSource = lists;
                                listdata.Visibility = Visibility.Visible;
                            }
                            else
                            {
                                pgbar.Visibility = Visibility.Collapsed;
                                loadtext.Text = "No items";
                            }

                        });
                    }
                });
            }
            else if (header == "replies")
            {
                service.ListTweetsMentioningMe(0, 40,
                (tweets, response) =>
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        DateTime ti = DateTime.Now;
                        DateTime now = ti.ToUniversalTime();

                        lists = new List<Tweet>();
                        foreach (var tweet in tweets)
                        {
                            Tweet tv = new Tweet();
                            TimeSpan tsp = now - tweet.CreatedDate;
                            tv.id = tweet.Id;
                            tv.name = tweet.User.ScreenName;
                            tv.thumb_img = tweet.User.ProfileImageUrl;
                            tv.text = tweet.Text + "\n";

                            if (tsp.Days > 0)
                                tv.time = tsp.Days + "일 전";
                            else if (tsp.Hours > 0)
                                tv.time = tsp.Hours + "시간 전";
                            else
                                tv.time = tsp.Minutes + "분 전";
                            lists.Add(tv);
                        }
                        Dispatcher.BeginInvoke(delegate()
                        {
                            if (lists.Count > 0)
                            {
                                loadtext.Visibility = Visibility.Collapsed;
                                pgbar.Visibility = Visibility.Collapsed;
                                listdata2.ItemsSource = lists;
                                listdata2.Visibility = Visibility.Visible;
                            }
                            else
                            {
                                pgbar.Visibility = Visibility.Collapsed;
                                loadtext.Text = "No items";
                            }

                        });
                    }
                });
            }
            else if (header == "messages")
            {
                service.ListDirectMessagesReceived(40,
                (tweets, response) =>
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        DateTime ti = DateTime.Now;
                        DateTime now = ti.ToUniversalTime();

                        lists = new List<Tweet>();
                        foreach (var tweet in tweets)
                        {
                            Tweet tv = new Tweet();
                            TimeSpan tsp = now - tweet.CreatedDate;
                            tv.id = tweet.Id;
                            tv.name = tweet.Sender.ScreenName;
                            tv.thumb_img = tweet.Sender.ProfileImageUrl;
                            tv.text = tweet.Text + "\n";
                            if (tsp.Days > 0)
                                tv.time = tsp.Days + "일 전";
                            else if (tsp.Hours > 0)
                                tv.time = tsp.Hours + "시간 전";
                            else
                                tv.time = tsp.Minutes + "분 전";
                            lists.Add(tv);
                        }
                        Dispatcher.BeginInvoke(delegate()
                        {
                            if (lists.Count > 0)
                            {
                                loadtext.Visibility = Visibility.Collapsed;
                                pgbar.Visibility = Visibility.Collapsed;
                                listdata3.ItemsSource = lists;
                                listdata3.Visibility = Visibility.Visible;
                            }
                            else
                            {
                                pgbar.Visibility = Visibility.Collapsed;
                                loadtext.Text = "No items";
                            }

                        });
                    }
                });
            }
            else if (header == "my")
            {
                service.ListTweetsOnUserTimeline(0, 40,
                (tweets, response) =>
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        DateTime ti = DateTime.Now;
                        DateTime now = ti.ToUniversalTime();

                        lists = new List<Tweet>();
                        foreach (var tweet in tweets)
                        {
                            Tweet tv = new Tweet();
                            TimeSpan tsp = now - tweet.CreatedDate;
                            tv.id = tweet.Id;
                            tv.name = tweet.User.ScreenName;
                            tv.thumb_img = tweet.User.ProfileImageUrl;
                            tv.text = tweet.Text + "\n";

                            if (tsp.Days > 0)
                                tv.time = tsp.Days + "일 전";
                            else if (tsp.Hours > 0)
                                tv.time = tsp.Hours + "시간 전";
                            else
                                tv.time = tsp.Minutes + "분 전";
                            lists.Add(tv);
                        }
                        Dispatcher.BeginInvoke(delegate()
                        {
                            if (lists.Count > 0)
                            {
                                loadtext.Visibility = Visibility.Collapsed;
                                pgbar.Visibility = Visibility.Collapsed;
                                listdata4.ItemsSource = lists;
                                listdata4.Visibility = Visibility.Visible;
                            }
                            else
                            {
                                pgbar.Visibility = Visibility.Collapsed;
                                loadtext.Text = "No items";
                            }

                        });
                    }
                });
            }
        }
Пример #17
0
        protected void Load(TwitterResource resource)
        {
            var service = new TwitterService(SensitiveData.ConsumerToken, SensitiveData.ConsumerSecret, resource.User.Key, resource.User.Secret);

            switch (resource.Type)
            {
                case ResourceType.Home:
                    service.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions { Count = 1, IncludeEntities = true }, (status, response) => ReceiveTweetable(status.Cast<ITweetable>(), response, resource));
                    break;
                case ResourceType.Mentions:
                    service.ListTweetsMentioningMe(new ListTweetsMentioningMeOptions { Count = 1, IncludeEntities = true }, (status, response) => ReceiveTweetable(status.Cast<ITweetable>(), response, resource));
                    break;
                case ResourceType.Messages:
                    service.ListDirectMessagesReceived(new ListDirectMessagesReceivedOptions { Count = 1 }, (status, response) => ReceiveTweetable(status.Cast<ITweetable>(), response, resource));
                    break;
                case ResourceType.Favorites:
                    service.ListFavoriteTweets(new ListFavoriteTweetsOptions { Count = 1 }, (status, response) => ReceiveTweetable(status.Cast<ITweetable>(), response, resource));
                    break;
                case ResourceType.List:
                    service.ListTweetsOnList(new ListTweetsOnListOptions
                    {
                        IncludeRts = false,
                        Count = 1,
                        OwnerScreenName = resource.Data.Substring(1, resource.Data.IndexOf('/') - 1),
                        Slug = resource.Data.Substring(resource.Data.IndexOf('/') + 1)
                    }, (status, response) => ReceiveTweetable(status.Cast<ITweetable>(), response, resource));
                    break;
                case ResourceType.Search:
                    service.Search(new SearchOptions { Count = 1, IncludeEntities = true, Q = resource.Data }, (status, response) => ReceiveTweetable(status.Statuses.Cast<ITweetable>(), response, resource));
                    break;
                case ResourceType.Tweets:
                    service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions { Count = 1, ScreenName = resource.Data, IncludeRts = true }, (status, response) => ReceiveTweetable(status.Cast<ITweetable>(), response, resource));
                    break;
            }
        }
Пример #18
0
        public static List<string> PostToReader(string _consumerKey, string _consumerSecret, string _accessToken, string _accessTokenSecret, string gUsername, string gPassword, bool chkTweets, bool chkFavorites, bool chkRetweets,  bool chkLinks, bool chkNoLinks)
        {
            List<string> res = new List<string>();
            GoogleReader gr = new GoogleReader(gUsername, gPassword);
            var serviceReader = new TwitterService(_consumerKey, _consumerSecret);
            serviceReader.AuthenticateWith(_accessToken, _accessTokenSecret);
            Regex urlfind = new Regex("((https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[A-Z0-9+&@#/%=~_|])", RegexOptions.IgnoreCase);

            List<TwitterStatus> mytweets =null;
            List<TwitterStatus> favorites=null;
            List<TwitterStatus> retweets =null;
            if (chkTweets)    mytweets  = serviceReader.ListTweetsOnUserTimeline(5).ToList();
            if (chkFavorites) favorites = serviceReader.ListFavoriteTweets(5).ToList();
            if (chkRetweets)  retweets  = serviceReader.ListRetweetsByMe(5).ToList();

            List<TwitterStatus> alltweets = new List<TwitterStatus>();
            if (mytweets != null) alltweets.AddRange(mytweets);
            if (favorites != null) alltweets.AddRange(favorites);
            if (retweets != null) alltweets.AddRange(retweets);

            foreach (var tweet in alltweets)
            {
                if (hassent(tweet.Id.ToString())) { continue; }
                Match thematch = urlfind.Match(tweet.Text);
                if (thematch.Success)
                {
                    if (chkLinks)
                    {
                        string theshorturl = thematch.Groups[1].Value;
                        string theurl = thematch.Groups[1].Value;
                        try
                        {
                            string longurlxml = c.DownloadString("http://api.unshort.me/?r=" + theurl);
                            Regex resUrl = new Regex("<resolvedURL>(.*?)</resolvedURL>");
                            Match resolved = resUrl.Match(longurlxml);
                            if (resolved.Success)
                            {
                                theurl = resolved.Groups[1].Value;
                            }
                        }
                        catch
                        {

                        }
                        string title;
                        string content = embed(theurl, out title);
                        gr.post(content, theurl, title, tweet.Text.Replace(theshorturl, "").Trim());
                        AddID(tweet.Id.ToString(), tweet.Text);
                    }

                }
                else if (chkNoLinks)
                {
                    gr.post("", "http://twitter.com/" + tweet.User.ScreenName + "/status/" + tweet.Id, "from twitter", tweet.Text.Trim());
                    AddID(tweet.Id.ToString(), tweet.Text);

                }
                res.Add( DateTime.Now.ToShortTimeString() + ": " + tweet.Text);
            }
            return res;
        }
        public static List<ModelTwitterFeedsDetails> GetTwitterTweets(string ScreenName)
        {
            ModelTwitterFeeds modelTwitterFeeds = new ModelTwitterFeeds();
            List<ModelTwitterFeedsDetails> lstModelTwitterFeedsDetail = new List<ModelTwitterFeedsDetails>();
            try
            {
                /*>>> API Creadentials <<<<////
                >> Under Informnation is creating from Personal Account Information API
                >> For any change in this credentials Login Account : [email protected]
                >> API Name : News Get Application
                >> Please don't change any word without permission from following API Admin*/
                string _consumerKey = "cvRCCaqLUlM9SyolFwYEQQ2uZ";
                string _consumerSecret = "sVvOgCPwuzXo37v4qjAriGbftwEefMC9xNadPQLTsoOkeqiJ8C";
                string _accessToken = "65042389-YQ3jLfP1RWu9Q7So9VAj3Rc3J9oMB0Suuv0jlioAN";
                string _accessTokenSecret = "yHMVHihkHAaCIOJi2M9WEOq4fpODY1a0hdS92J9OZEJEL";
                // API access Data End

                var service = new TwitterService(_consumerKey, _consumerSecret);
                //var tweets = new ListTweetsOnHomeTimelineOptions();
                service.AuthenticateWith(_accessToken, _accessTokenSecret);
                IAsyncResult result = service.BeginListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions());
                IEnumerable<TwitterStatus> tweets = service.EndListTweetsOnHomeTimeline(result);

                foreach (var tweet in tweets)
                {
                    if (tweets != null)
                    {
                        modelTwitterFeeds.FeedId = 0;
                        modelTwitterFeeds.UserPageId = 0;
                        modelTwitterFeeds.UserPageTitle = String.Empty;
                        modelTwitterFeeds.UserScreenName = String.Empty;
                        modelTwitterFeeds.UserPageLanguage = String.Empty;
                        modelTwitterFeeds.UserPageFollowers = 0;
                        modelTwitterFeeds.UserPageCoverImageURL = String.Empty;
                        modelTwitterFeeds.UserPageLogoImage = String.Empty;
                    }

                    var st1 = tweet.Text; //string
                    var st2 = tweet.Source; //string
                    var st3 = tweet.TextAsHtml; //string
                    var st4 = tweet.TextDecoded; //string
                    var st5 = tweet.RetweetedStatus; //TwitterStatus
                    var st6 = tweet.RetweetCount; //int
                    var st7 = tweet.RawSource; //string
                    var st8 = tweet.Place; //TwitterPlace
                    var st9 = tweet.Location; //TwitterGeoLocation
                    var st10 = tweet.Language; //string
                    var st11 = tweet.IsTruncated; //bool
                    var st12 = tweet.IsRetweeted; //bool
                    var st13 = tweet.IsPossiblySensitive; //bool is nullable
                    var st14 = tweet.IsFavorited; //bool
                    var st15 = tweet.InReplyToUserId; //long is nullable
                    var st16 = tweet.InReplyToStatusId; //long is nullable
                    var st17 = tweet.InReplyToScreenName; //string
                    var st18 = tweet.IdStr; //string
                    var st19 = tweet.Id; //long
                    var st20 = tweet.FavoriteCount; //int
                    var st21 = tweet.ExtendedEntities; //TwitterExtendedEntities
                    var st22 = tweet.Entities; //TwitterEntities
                    var st23 = tweet.CreatedDate; //DateTime
                    var st24 = tweet.Author; //ITweeter

                }

                //TwitterAccount user = new TwitterAccount.
                //TwitterUser twitterUser =
                //>>GET OTHER USER TIMELINE//BeginListTweetsOnHomeTimeline

                TwitterService t_service = new TwitterService(_consumerKey, _consumerSecret);
                t_service.AuthenticateWith(_accessToken, _accessTokenSecret);
                var t_options = new ListTweetsOnHomeTimelineOptions();
                t_options.ExcludeReplies = true;
                var t_tweets = t_service.ListTweetsOnHomeTimeline(t_options);
                //ListTweetsOnSpecifiedUserTimeline
                string ScreenNameBBCArabic = "BBCArabic";
                string ScreenNameCNNArabic = "cnnarabic";
                string ScreenName1 = "garbo_speaks";
                var User_OptionInit = new ListTweetsOnUserTimelineOptions { ScreenName = ScreenNameCNNArabic, Count = 200, ExcludeReplies = true };
                var User_Tweets = service.ListTweetsOnUserTimeline(User_OptionInit);

                string TweetText = String.Empty;

                foreach (var tweet in User_Tweets)
                {
                    var userDetail = tweet.User;
                    if (false)
                    {
                        var us1 = tweet.User.ContributorsEnabled; //bool?
                        var us2 = tweet.User.CreatedDate;
                        var us3 = tweet.User.Description;
                        var us4 = tweet.User.FavouritesCount;
                        var us5 = tweet.User.FollowersCount;
                        var us6 = tweet.User.FollowRequestSent;
                        var us7 = tweet.User.FriendsCount;
                        var us8 = tweet.User.Id;
                        var us9 = tweet.User.IsDefaultProfile;
                        var us10 = tweet.User.IsGeoEnabled;
                        var us11 = tweet.User.IsProfileBackgroundTiled;
                        var us12 = tweet.User.IsProtected;
                        var us13 = tweet.User.IsTranslator;
                        var us14 = tweet.User.IsVerified;
                        var us15 = tweet.User.Language;
                        var us16 = tweet.User.ListedCount;
                        var us17 = tweet.User.Location;
                        var us18 = tweet.User.Name;
                        var us19 = tweet.User.ProfileBackgroundColor;
                        var us20 = tweet.User.ProfileBackgroundImageUrl;
                        var us21 = tweet.User.ProfileBackgroundImageUrlHttps;
                        var us22 = tweet.User.ProfileImageUrl;
                        var us23 = tweet.User.ProfileImageUrlHttps;
                        var us24 = tweet.User.ProfileLinkColor;
                        var us25 = tweet.User.ProfileSidebarBorderColor;
                        var us26 = tweet.User.ProfileSidebarFillColor;
                        var us27 = tweet.User.ProfileTextColor;
                        var us28 = tweet.User.RawSource;
                        var us29 = tweet.User.ScreenName;
                        var us30 = tweet.User.Status;
                        var us31 = tweet.User.StatusesCount;
                        var us32 = tweet.User.TimeZone;
                        var us33 = tweet.User.Url;
                        var us34 = tweet.User.UtcOffset;
                    }

                    var st1 = tweet.Text.ToSafeString(); //string
                    TweetText = tweet.Text;
                    var st2 = tweet.Source; //string
                    var st3 = tweet.TextAsHtml; //string
                    var st4 = tweet.TextDecoded; //string
                    var st5 = tweet.RetweetedStatus; //TwitterStatus
                    var st6 = tweet.RetweetCount; //int
                    var st7 = tweet.RawSource; //string
                    var st8 = tweet.Place; //TwitterPlace
                    var st9 = tweet.Location; //TwitterGeoLocation
                    var st10 = tweet.Language; //string
                    var st11 = tweet.IsTruncated; //bool
                    var st12 = tweet.IsRetweeted; //bool
                    var st13 = tweet.IsPossiblySensitive; //bool is nullable
                    var st14 = tweet.IsFavorited; //bool
                    var st15 = tweet.InReplyToUserId; //long is nullable
                    var st16 = tweet.InReplyToStatusId; //long is nullable
                    var st17 = tweet.InReplyToScreenName; //string
                    var st18 = tweet.IdStr; //string
                    var st19 = tweet.Id; //long
                    var st20 = tweet.FavoriteCount; //int
                    var st21 = tweet.ExtendedEntities; //TwitterExtendedEntities
                    var st22 = tweet.Entities; //TwitterEntities
                    var twitterEntities = new TwitterEntities();
                    twitterEntities = st22;
                    IList<TwitterUrl> twitterUrl = twitterEntities.Urls; //List<TwitterUrl>
                    foreach (var url in twitterUrl)
                    {
                        var url1 = url.DisplayUrl; //string
                        var url2 = url.EndIndex; //int
                        var url3 = url.EntityType; //TwitterEntityType
                        var entityType = url3;
                        //4 Entity Types are Defined
                        //TwitterEntityType.HashTag; //0
                        //TwitterEntityType.Mention; //1
                        //TwitterEntityType.Url; //2
                        //TwitterEntityType.Media; //3

                        var url4 = url.ExpandedValue; //string
                        var url5 = url.Indices; //IList<int>
                        var url6 = url.StartIndex; //int
                        var url7 = url.Value; //string
                        TweetText = TweetText.Trim().Replace(url.Value, String.Empty).Trim();
                    }

                    IList<TwitterMention> twitterMention = twitterEntities.Mentions; //List<TwitterMention>
                    foreach (var mention in twitterMention)
                    {
                        var url1 = mention.EndIndex; //int
                        var url2 = mention.EntityType; //int
                        var entityType = url2;

                        //4 Entity Types are Defined
                        //TwitterEntityType.HashTag; //0
                        //TwitterEntityType.Mention; //1
                        //TwitterEntityType.Url; //2
                        //TwitterEntityType.Media; //3

                        var url3 = mention.Id; //long
                        var url4 = mention.Indices; //IList<int>
                        var url5 = mention.Name; //string
                        var url6 = mention.ScreenName; //string
                        var url7 = mention.StartIndex; //int
                    }
                    IList<TwitterMedia> twitterMedia = twitterEntities.Media; //List<TwitterMedia>
                    foreach (var media in twitterMedia)
                    {
                        var media1 = media.DisplayUrl; //string
                        var media2 = media.EndIndex; //int
                        var media3 = media.EntityType; //TwitterEntity
                        var media4 = media.ExpandedUrl; //string
                        var media5 = media.Id; //long
                        var media6 = media.IdAsString; //string
                        var media7 = media.Indices; //IList<int>
                        var media8 = media.MediaType; //TwitterMediaType
                        var twitterMediaType = media8;

                        /*Three Types of MediaType
                        TwitterMediaType.Photo; //0
                        TwitterMediaType.Video; //1
                        TwitterMediaType.AnimatedGif; //2
                        */

                        var media9 = media.MediaUrl; //string
                        var media10 = media.MediaUrlHttps; //string
                        //var FeedImageURLhttp  = media.MediaUrl; for Http Image
                        //var FeedImageURLhttps  =  media.MediaUrlHttps; for Https Image
                        var media11 = media.Sizes; //TwitterMediaSizes
                        var twitterMediaSizes = media11;
                        //media11.Large
                        //media11.Medium
                        //media11.Small
                        //media11.Thumb
                        var media12 = media.StartIndex; //int
                        var media13 = media.Url; //string

                        TweetText = TweetText.Trim().Replace(media.Url, String.Empty).Trim();
                    }
                    IList<TwitterHashTag> twitterHashTag = twitterEntities.HashTags; //List<TwitterHashTag>
                    foreach (var hashTag in twitterHashTag)
                    {
                        var ht1 = hashTag.EndIndex;
                        var ht2 = hashTag.EntityType;
                        var ht3 = hashTag.Indices;
                        var ht4 = hashTag.StartIndex;
                        var ht5 = hashTag.Text;
                        // hashTagText for refine Tweet Text
                        TweetText = TweetText.Trim().Replace("#" + hashTag.Text, string.Empty).Trim();
                    }
                    TweetText = TweetText.Replace("\n", String.Empty).Trim();
                    var st23 = tweet.CreatedDate; //DateTime
                    var st24 = tweet.Author; //ITweeter

                    var ProfileImageURL = st24.ProfileImageUrl;
                    var ss = st24.RawSource;
                    var screenName = st24.ScreenName;

                }
                return lstModelTwitterFeedsDetail;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
Пример #20
0
        public string getTwitter(string user)
        {
            try
            {
                SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
                SqlDataReader dr;
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "select * from tbl_ext_creds_twitter (nolock) where userid='" + user + "'";
                cmd.Connection = conn;
                conn.Open();

                if (conn.State == ConnectionState.Open)
                {
                    dr = cmd.ExecuteReader();
                    dr.Read();
                    if (dr.HasRows)
                    {
                        //Session["twtoken"] = dr[1].ToString();
                        //Session["twsecret"] = dr[2].ToString();
                        //Session["twscreenname"] = dr[4].ToString();
                        //Session["twuserid"] = dr[3].ToString();

                        var service = new TwitterService(ConfigurationManager.AppSettings["twitter.appkey"].ToString(), ConfigurationManager.AppSettings["twitter.appsecret"].ToString());
                        //service.AuthenticateWith(ConfigurationManager.AppSettings["twitter.accesstoken"].ToString(), ConfigurationManager.AppSettings["twitter.accesstokensecret"].ToString());
                        service.AuthenticateWith(dr[1].ToString(), dr[2].ToString());
                        ListTweetsOnUserTimelineOptions opt = new ListTweetsOnUserTimelineOptions { ScreenName = dr[4].ToString(), Count = 5 };
                        //IEnumerable<TwitterStatus> tweets = service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions { ScreenName = Session["twscreenname"].ToString(), Count = 5 });
                        IEnumerable<TwitterStatus> tweets = service.ListTweetsOnUserTimeline(opt);
                        if (tweets != null)
                        {
                            //var t = (TwitterStatus)JsonConvert.DeserializeObject(tweets, typeof(TwitterStatus));

                            foreach (var tweet in tweets)
                            {
                                MPtweets aTweet = new MPtweets();
                                aTweet.profileImageUrl = tweet.Author.ProfileImageUrl;
                                aTweet.ScreenName = tweet.Author.ScreenName;
                                aTweet.CreatedDate = tweet.CreatedDate.ToString();
                                aTweet.Text = tweet.Text;
                                mpt.Add(aTweet);
                                //twitter.InnerHtml = twitter.InnerHtml + "<li> <p> <table><tr><td><img alt=\"\" src=\"" + tweet.Author.ProfileImageUrl + "\" /></td><td> <table> <tr> <td> " + tweet.Author.ScreenName + " </td> </tr> <tr><td>" + tweet.CreatedDate.ToString("MM/dd/yyyy") + " </td> </tr></table> </td></tr></table> </p></li></br>";
                                //twitter.InnerHtml = twitter.InnerHtml + "<li> <p>" + tweet.Text + "</p></li></br>";
                            }

                            twdata = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(mpt);

                        }

                    }
                    dr.Close();
                }
                conn.Close();
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            return twdata;
        }
Пример #21
0
        public static void DoRetweets()
        {
            string CONSUMER_KEY = "R";
            string CONSUMER_SECRET = "R";
            string ACCESS_TOKEN = "R";
            string ACCESS_SECRET = "R";

            var service = new TwitterService(CONSUMER_KEY, CONSUMER_SECRET);
            service.AuthenticateWith(ACCESS_TOKEN, ACCESS_SECRET);

            //WoW
            var currentTweets = service.ListTweetsOnUserTimeline(
                new ListTweetsOnUserTimelineOptions()
                {
                    Count = 5,
                    ExcludeReplies = false,
                    IncludeRts = false,
                    ScreenName = "@" + "blizzpostswow",
                    SinceId = null,
                    MaxId = null
                }).Where(x => (DateTime.UtcNow - x.CreatedDate).TotalHours <= 6 && x.RetweetCount == 0);

            foreach (var tweet in currentTweets)
            {
                if (tweet.InReplyToStatusId == null && !tweet.Text.EndsWith("~!"))
                    service.Retweet(new RetweetOptions { Id = tweet.Id });
                Console.WriteLine("Retweet result: " + service.Response.StatusCode.ToString());
            }

            //D3
            currentTweets = service.ListTweetsOnUserTimeline(
                new ListTweetsOnUserTimelineOptions()
                {
                    Count = 5,
                    ExcludeReplies = false,
                    IncludeRts = false,
                    ScreenName = "@" + "blizzpostsd3",
                    SinceId = null,
                    MaxId = null
                }).Where(x => (DateTime.UtcNow - x.CreatedDate).TotalHours <= 6 && x.RetweetCount == 0);

            foreach (var tweet in currentTweets)
            {
                if (tweet.InReplyToStatusId == null && !tweet.Text.EndsWith("~!"))
                    service.Retweet(new RetweetOptions { Id = tweet.Id });
                Console.WriteLine("Retweet result: " + service.Response.StatusCode.ToString());
            }

            //Hearthstone
            currentTweets = service.ListTweetsOnUserTimeline(
                new ListTweetsOnUserTimelineOptions()
                {
                    Count = 5,
                    ExcludeReplies = false,
                    IncludeRts = false,
                    ScreenName = "@" + "blizzpostshs",
                    SinceId = null,
                    MaxId = null
                }).Where(x => (DateTime.UtcNow - x.CreatedDate).TotalHours <= 6 && x.RetweetCount == 0);

            foreach (var tweet in currentTweets)
            {
                if (tweet.InReplyToStatusId == null && !tweet.Text.EndsWith("~!"))
                    service.Retweet(new RetweetOptions { Id = tweet.Id });
                Console.WriteLine("Retweet result: " + service.Response.StatusCode.ToString());
            }

            //Heroes
            currentTweets = service.ListTweetsOnUserTimeline(
                new ListTweetsOnUserTimelineOptions()
                {
                    Count = 5,
                    ExcludeReplies = false,
                    IncludeRts = false,
                    ScreenName = "@" + "blizzpostshots",
                    SinceId = null,
                    MaxId = null
                }).Where(x => (DateTime.UtcNow - x.CreatedDate).TotalHours <= 6 && x.RetweetCount == 0);

            foreach (var tweet in currentTweets)
            {
                if (tweet.InReplyToStatusId == null && !tweet.Text.EndsWith("~!"))
                    service.Retweet(new RetweetOptions { Id = tweet.Id });
                Console.WriteLine("Retweet result: " + service.Response.StatusCode.ToString());
            }

            //SC2
            currentTweets = service.ListTweetsOnUserTimeline(
                new ListTweetsOnUserTimelineOptions()
                {
                    Count = 5,
                    ExcludeReplies = false,
                    IncludeRts = false,
                    ScreenName = "@" + "blizzpostssc2",
                    SinceId = null,
                    MaxId = null
                }).Where(x => (DateTime.UtcNow - x.CreatedDate).TotalHours <= 6 && x.RetweetCount == 0);

            foreach (var tweet in currentTweets)
            {
                if (tweet.InReplyToStatusId == null && !tweet.Text.EndsWith("~!"))
                    service.Retweet(new RetweetOptions { Id = tweet.Id });
                Console.WriteLine("Retweet result: " + service.Response.StatusCode.ToString());
            }
        }
Пример #22
0
        /// <summary>
        ///     Returns the tweets for ChildCancerNZ
        /// </summary>
        /// <returns></returns>
        public IEnumerable<TwitterStatus> getTweets()
        {
            List<String> urlOfImages = new List<String>();
            var service = new TwitterService(OAuthConsumerKey, OAuthConsumerSecret);
            service.AuthenticateWith(OAuthToken, OAuthTokenSecret);
            ListTweetsOnHomeTimelineOptions options = new ListTweetsOnHomeTimelineOptions();

            IEnumerable<TwitterStatus> tweets =
                service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions {ScreenName = "ChildCancerNZ"});

            return tweets;
        }
Пример #23
0
        protected Boolean GrabTimeLine()
        {
            var config = Serializer.Load<AuthConfig>(@"configs\twitter.config");

            var service = new TwitterService(config.ConsumerKey, config.ConsumerSecret);
            service.AuthenticateWith(config.AccessToken, config.AccessTokenSecret);

            var tweets = service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions() { Count = EntriesCount }).ToList();

            tweets.ForEach((tweet) =>
            {
                var item = tweet.RetweetedStatus ?? tweet;

                var date = item.CreatedDate.ToShortDateString() + " " + tweet.CreatedDate.ToShortTimeString();
                var text = item.Text;
                var idTweet = item.Id.ToString();
                var nameUser = item.User.Name;
                var imageUser = item.User.ProfileImageUrl;
                var screenName = item.User.ScreenName;

                _entries.Add(new TwitterEntry()
                {
                    IdTweet = idTweet,
                    Text = text,
                    Date = date,
                    NameUser = nameUser,
                    ImageUser = imageUser,
                    ScreenName = screenName
                });
            });

            return EntriesCount > 0 && tweets.Count() > 0 ? true : false;
        }
Пример #24
0
        private List<TweetSharp.TwitterStatus> UpdateTweetTimeline()
        {
            var result = new List<TweetSharp.TwitterStatus>();

            recentTweetTimelineUpdateTime = DateTime.UtcNow;

            // Some of oAuth parameters is not set up
            if (String.IsNullOrEmpty(TwitterConsumerKey) || String.IsNullOrEmpty(TwitterConsumerSecret) ||
                String.IsNullOrEmpty(TwitterAccessToken) || String.IsNullOrEmpty(TwitterAccessTokenSecret))
            {
                return result;
            }

            var service = new TwitterService(TwitterConsumerKey, TwitterConsumerSecret);
            service.AuthenticateWith(TwitterAccessToken, TwitterAccessTokenSecret);

            var options = new ListTweetsOnUserTimelineOptions
            {
                Count = 10
            };

            var recentTweets = service.ListTweetsOnUserTimeline(options);
            if (recentTweets != null)
            {
                foreach (TwitterStatus s in recentTweets)
                {
                    result.Add(s);
                }
            }

            return result;
        }