示例#1
0
        public List<Status> UserTweets(string inUserName_)
        {
            List<Status> statusList = new List<Status>(from tweet in _twitterCtx.Status
                                                       where tweet.Type == StatusType.User &&
                                                               tweet.ScreenName == inUserName_ &&
                                                               tweet.Count == Cfg_Twitter.AMT_TWEET_QUERY &&
                                                               tweet.RetweetedStatus.StatusID == 0
                                                       select tweet);

            ulong maxID = statusList[statusList.Count - 1].StatusID;
            int prevCount = statusList.Count;

            while (prevCount > 1)
            {
                if (statusList.Count > Cfg_Twitter.AMT_MAX_TWEETS)
                    break;

                List<Status> tmp = (from tweet in _twitterCtx.Status
                                    where tweet.Type == StatusType.User &&
                                            tweet.ScreenName == inUserName_ &&
                                            tweet.Count == Cfg_Twitter.AMT_TWEET_QUERY &&
                                            tweet.RetweetedStatus.StatusID == 0 &&
                                            tweet.MaxID == maxID
                                    select tweet).ToList();
                if (tmp.Count == 1)
                    break;

                statusList.AddRange(tmp);
                maxID = tmp[tmp.Count - 1].StatusID;
            }

            return statusList;
        }
示例#2
0
        private static IList<Status> Load(IQueryBuilder queryBuilder, ulong maxId, int count = 2000)
        {
            var statuses = new List<Status>();
            //todo limit exception System.AggregateException, message: Rate limit exceeded - Please visit the LINQ to Twitter FAQ (at the HelpLink) for help on resolving this error.
            var tweetQuery = queryBuilder.BuildTaskByMinId(maxId + 1).ToList();

            statuses.AddRange(tweetQuery);

            if (statuses.Count < 150)
            {
                return statuses;
            }

            while (statuses.Count < count)
            {
                tweetQuery = queryBuilder.BuildTaskByMinIdAndMaxId(maxId + 1, statuses[statuses.Count - 1].StatusID - 1).ToList();

                statuses.AddRange(tweetQuery);
                if (tweetQuery.Count < 150)
                {
                    break;
                }
            }
            return statuses;
        }
 private void CacheAccountList(List<Domain.Model.Account> accounts)
 {
     foreach(var item in accounts)
     {
         this.accountCache.Add(item.AccountId.ToString(), item, DateTimeOffset.Now.AddMinutes(20));
     }
 }
示例#4
0
 public FenetrePrincipale()
 {
     InitializeComponent();
     listeTweets = new List<TweetControl>();
     vScrollBar1.Maximum = nbTweetsToShow * ConfigurationManager.HEIGHT_TWEET_CONTROL - this.Height + ConfigurationManager.HEIGHT_TOOLBAR;
     recupererTweets();
 }
示例#5
0
        private void GetRecent200()
        {
            var twitterContext = new TwitterContext(authorizedUser);
            var tweets = from tweet in twitterContext.Status where tweet.Type == StatusType.Home && tweet.Count select tweet;

            currentTweets = tweets.ToList();
        }
        /// <summary>
        /// Removes one or more users from a Site Stream
        /// </summary>
        /// <param name="ctx">Twitter Context</param>
        /// <param name="userIDs">List of user IDs to remove from Site Stream</param>
        /// <param name="streamID">ID of Site Stream to remove users from</param>
        /// <param name="callback">Async Callback</param>
        /// <returns>Control Stream with CommandResponse property for Twitter's response message</returns>
        public static ControlStream RemoveSiteStreamUser(this TwitterContext ctx, List<ulong> userIDs, string streamID, Action<TwitterAsyncResponse<ControlStream>> callback)
        {
            if (string.IsNullOrEmpty(streamID)) throw new ArgumentNullException("streamID", "streamID is required.");

            var newUrl = ctx.SiteStreamUrl + "site/c/" + streamID + "/remove_user.json";

            string userIDString = string.Join(",", userIDs.Select(user => user.ToString()).ToArray());

            var reqProc = new ControlStreamRequestProcessor<ControlStream>();

            var twitExe = ctx.TwitterExecutor;

            twitExe.AsyncCallback = callback;
            var resultsJson =
                twitExe.PostToTwitter(
                    newUrl,
                    new Dictionary<string, string>
                    {
                        {"user_id", userIDString}
                    },
                    response => reqProc.ProcessActionResult(response, ControlStreamType.Info));

            ControlStream cs = reqProc.ProcessActionResult(resultsJson, ControlStreamType.Info);
            return cs;
        }
        public async Task<IEnumerable<TweetDto>> GetTweetsFor(IEnumerable<string> tweetsIds)
        {
            var tweetsIdsList = tweetsIds.Select(s => Convert.ToUInt64(s)).Materialize();

            if (tweetsIdsList.IsEmpty())
            {
                return Enumerable.Empty<TweetDto>();
            }

            using (var twitterContext = CreateContext())
            {
                var results = new List<TweetDto>();
                foreach (var tweetsId in tweetsIdsList)
                {
                    var id = tweetsId;
                    var tweet = await
                    twitterContext.Status
                        .Where(status => status.Type == StatusType.Show && status.ID == id).FirstOrDefaultAsync();
                    if (tweet != null)
                    {
                        results.Add(BuildTweetDto(tweet));
                    }
                }

                return results;
            }
        }
        public JsonResult Status(string id)
        {
            Authorize();
            string screenName = ViewBag.User;
            IEnumerable<TweetViewModel> friendTweets = new List<TweetViewModel>();

            if (string.IsNullOrEmpty(screenName))
            {
                return Json(friendTweets, JsonRequestBehavior.AllowGet);
            }

            twitterCtx = new TwitterContext(auth);

            friendTweets =
                (
                from tweet in twitterCtx.Status
                 where tweet.Type == StatusType.Show &&
                       tweet.ID == id
                 select GetTweetViewModel(tweet))
                .ToList();

            if (friendTweets.Count() > 0)
                return Json(friendTweets.ElementAt(0), JsonRequestBehavior.AllowGet);
            else
                return Json(new TweetViewModel { Tweet = "Requested Status Not Found" }, JsonRequestBehavior.AllowGet);
        }
示例#9
0
        private List<string> GetFollowers()
        {
            List<string> results = new List<string>();

            var twitterContext = new TwitterContext(authorizedUser);

            var temp = Enumerable.FirstOrDefault(from friend in twitterContext.Friendship
                                                 where friend.Type == FriendshipType.FollowersList &&
                                                 friend.ScreenName == "Bostato90" &&
                                                 friend.Count == 200
                                                 select friend);
            if (temp != null)
            {
                temp.Users.ToList().ForEach(user => results.Add(user.Name));

                while (temp != null && temp.CursorMovement.Next != 0)
                {
                    temp = Enumerable.FirstOrDefault(from friend in twitterContext.Friendship
                                                      where friend.Type == FriendshipType.FollowersList &&
                                                      friend.ScreenName == "Bostato90" &&
                                                      friend.Count == 200 &&
                                                      friend.Cursor == temp.CursorMovement.Next
                                                      select friend);
                    if (temp != null) temp.Users.ToList().ForEach(user => results.Add(user.Name));
                }
            }
            return results;
        }
示例#10
0
 public TweetGrid()
 {
     InitializeComponent();
     panelDisabled.Dock = DockStyle.Fill;
     splitContainer1.Dock = DockStyle.Fill;
     Panes = new List<TweetPane>();
 }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			var auth = new OAuth1Authenticator ("Ywun66NxYNMXgjzNRdIG12q4k",
				"XQAQ5djSlMOiXfMhn5rl4fdPahqw0wNPW6nBS5I9aRCajbxMvJ",
				new Uri("https://api.twitter.com/oauth/request_token"),
				new Uri("https://api.twitter.com/oauth/authorize"),
				new Uri("https://api.twitter.com/oauth/access_token"),
				new Uri("http://mobile.twitter.com"));

			auth.Completed += (sender, e) => {
				DismissViewController (true, null);
				if (e.IsAuthenticated) {

					loggedInAccount = e.Account;
					GetUserData ();
					var mList =   GetTwitterData();
					mList.ContinueWith(async (Task<List<Status>> arg) =>{
						myList = arg.Result;
						//twitterHomeTableView.Source = new TwitterHomeSource(arg.Result.ToArray());
					});


				}

			};

			var ui = auth.GetUI();
			PresentViewController(ui, true, null);
		}
示例#12
0
        protected IList<string> Followers(TwitterContext twitterCtx, string user)
        {
            var result = new List<string>();
            long cursor = -1;
            do
            {
                var friendship = (from friend in twitterCtx.Friendship
                    where friend.Type == FriendshipType.FriendsList &&
                          friend.ScreenName == user &&
                          friend.Cursor == cursor
                    select friend)
                    .SingleOrDefaultAsync().Result;

                if (friendship != null &&
                    friendship.Users != null &&
                    friendship.CursorMovement != null)
                {
                    cursor = friendship.CursorMovement.Next;

                }

                if (friendship != null && friendship.Users != null)
                    result.AddRange(friendship.Users.Select(x => x.UserIDResponse));
            } while (cursor != 0);
            return result;
        }
示例#13
0
        static void Main(string[] args)
        {
            if (!EnsureSingleLoad())
            {
                Console.WriteLine("{0}: Another Instance Currently Runing", DateTime.Now);
                return;
            }

            var streamMonitors = new List<DualStreamMonitor>();

            UsersCollection.PrimaryUsers().AsParallel()
                .ForAll(u =>
            {
                var streamMonitor = new DualStreamMonitor(u, Console.Out);
                streamMonitor.Start();

                lock (streamMonitors)
                {
                    streamMonitors.Add(streamMonitor);
                }
            });

            while (Console.ReadLine() != "exit") ;

            streamMonitors.ForEach(s => s.Stop());
        }
示例#14
0
        public Relationship(JsonData relJson)
        {
            if (relJson == null) return;

            ScreenName = relJson.GetValue<string>("screen_name");
            Name = relJson.GetValue<string>("name");
            RetweetsWanted = relJson.GetValue<bool>("want_retweets");
            AllReplies = relJson.GetValue<bool>("all_replies");
            MarkedSpam = relJson.GetValue<bool>("marked_spam");
            ID = relJson.GetValue<ulong>("id");
            Blocking = relJson.GetValue<bool>("blocking");
            NotificationsEnabled = relJson.GetValue<bool>("notifications_enabled");
            CanDm = relJson.GetValue<bool>("can_dm");
            Muting = relJson.GetValue<bool>("muting", false);

            var connections = relJson.GetValue<JsonData>("connections");
            if (connections != null)
                Connections =
                    (from JsonData connection in connections
                     select connection.ToString())
                    .ToList();
            else
                Connections = new List<string>();

            FollowedBy = 
                relJson.GetValue<bool>("followed_by") ||
                Connections.Contains("followed_by");
            Following = 
                relJson.GetValue<bool>("following") ||
                Connections.Contains("following");
        }
示例#15
0
        static async Task ShowFavoritesAsync(TwitterContext twitterCtx)
        {
            const int PerQueryFavCount = 200;

            // set from a value that you previously saved
            ulong sinceID = 1; 

            var favsResponse =
                await
                    (from fav in twitterCtx.Favorites
                     where fav.Type == FavoritesType.Favorites &&
                           fav.Count == PerQueryFavCount
                     select fav)
                    .ToListAsync();

            if (favsResponse == null)
            {
                Console.WriteLine("No favorites returned from Twitter.");
                return;
            }

            var favList = new List<Favorites>(favsResponse);

            // first tweet processed on current query
            ulong maxID = favList.Min(fav => fav.StatusID) - 1;

            do
            {
                favsResponse =
                    await
                        (from fav in twitterCtx.Favorites
                         where fav.Type == FavoritesType.Favorites &&
                               fav.Count == PerQueryFavCount &&
                               fav.SinceID == sinceID &&
                               fav.MaxID == maxID
                         select fav)
                        .ToListAsync();

                if (favsResponse == null || favsResponse.Count == 0) break;

                // reset first tweet to avoid re-querying the
                // same list you just received
                maxID = favsResponse.Min(fav => fav.StatusID) - 1;
                favList.AddRange(favsResponse);

            } while (favsResponse.Count > 0);

            favList.ForEach(fav => 
            {
                if (fav != null && fav.User != null)
                    Console.WriteLine(
                        "Name: {0}, Tweet: {1}",
                        fav.User.ScreenNameResponse, fav.Text);
            });

            // save this in your db for this user so you can set
            // sinceID accurately the next time you do a query
            // and avoid querying the same tweets again.
            ulong newSinceID = favList.Max(fav => fav.SinceID);
        }
示例#16
0
        public async Task InitTweetViewModel()
        {
            var auth = new ApplicationOnlyAuthorizer()
            {
                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey = "dYNbMI3KFn4zFrHIaAKIWCFYQ",
                    ConsumerSecret = "mQhDSmPov7bbJXb8jPwaVghBbUbgELpQqyHG2QRyf89CsQWKyb",
                },
            };
            await auth.AuthorizeAsync();

            var ctx = new TwitterContext(auth);

            var searchResponse = await
                (from search in ctx.Search
                 where search.Type == SearchType.Search &&
                       search.Query == "\"LINQ to Twitter\""
                 select search)
                .SingleAsync();

            Tweets =
                (from tweet in searchResponse.Statuses
                 select new Tweet
                 {
                     StatusID = tweet.StatusID,
                     ScreenName = tweet.User.ScreenNameResponse,
                     Text = tweet.Text,
                     ImageUrl = tweet.User.ProfileImageUrl
                 })
                .ToList();
        }
示例#17
0
 public JsonResult GetTweets()
 {
     Authorize();
     string screenName = ViewBag.User;
     IEnumerable<TweetViewModel> friendTweets = new List<TweetViewModel>();
     if (string.IsNullOrEmpty(screenName))
     {
         return Json(friendTweets, JsonRequestBehavior.AllowGet);
     }
     twitterCtx = new TwitterContext(auth);
     friendTweets =
     (from tweet in twitterCtx.Status
      where tweet.Type == StatusType.Home &&
            tweet.ScreenName == screenName &&
            tweet.IncludeEntities == true
      select new TweetViewModel
      {
          ImageUrl = tweet.User.ProfileImageUrl,
          ScreenName = tweet.User.Identifier.ScreenName,
          MediaUrl = GetTweetMediaUrl(tweet),
          Tweet = tweet.Text
      })
     .ToList();
     return Json(friendTweets, JsonRequestBehavior.AllowGet);
 }
示例#18
0
        public static async Task<List<User>> ShowFriends(IAuthorizer auth, string login)
        {
            var users = new List<User>();
            var twitterCtx = new TwitterContext(auth);

            Friendship friendship;
            long cursor = -1;
            do
            {
                friendship = await twitterCtx.Friendship.Where(x =>
                   x.Type == FriendshipType.FriendsList
                   && x.ScreenName == login
                   && x.Cursor == cursor
                   && x.Count == 200
                   && x.IncludeUserEntities == false)
                    .SingleOrDefaultAsync();

                if (friendship != null
                    && friendship.Users != null
                    && friendship.CursorMovement != null)
                {
                    cursor = friendship.CursorMovement.Next;
                    users.AddRange(friendship.Users);
                }
            } while (cursor != 0);
            return users;
        }
示例#19
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="tweetList"></param>
 /// <param name="actionState"></param>
 public void AddTweets(List<TwitterEntity> tweetList, ActionState actionState)
 {
     TwitterRepository twitterRepository = new TwitterRepository();
     for (int i = 0; i < tweetList.Count; i++)
     {
         twitterRepository.Insert(tweetList[i], actionState);
     }
 }
 public Domain.Model.Account GetAccount(ulong accountId)
 {
     using (var twitterCtx = new TwitterContext(this.GetAuthKey()))
     {
         var accountIdList = new List<string>() { accountId.ToString() };
         return GetUsers(twitterCtx, accountIdList).FirstOrDefault();
     }
 }
示例#21
0
        public IActionResult Index(string screenname, string order)
        {
            // TODO handle hashtags separately
            int markovOrder;
            // default order is 2, if the parse failed
            if (!int.TryParse(order, out markovOrder))
                markovOrder = 2;

            // hack to avoid null pointer exception
            if (markovOrder > 5)
                markovOrder = 5;
            int tweetCount = 200;
            var generator = new MarkovGenerator(markovOrder, false);
            
            // how to handle hashtags? just keep a list of them along with a probability for each,
            // i.e. a single-prefix markov chain?
            // would also need a no-hashtag probability
            // no, that won't work, since there wouldn't be an end point, really. at least not one that makes sense.
            
            // what might work is keeping track of individual hashtag probabilities,
            // as well as a probability distribution of number of hashtags. (fun to get some stats on that, see if it's poisson-distributed)

            ViewData["Screenname"] = screenname;

            var auth = new SingleUserAuthorizer
            {
                CredentialStore = new SingleUserInMemoryCredentialStore
                {
                    ConsumerKey = _consumerKey,
                    ConsumerSecret = _consumerSecret,
                    AccessToken = _accessToken,
                    AccessTokenSecret = _accessTokenSecret
                }
            };

            var twitterCtx = new TwitterContext(auth);
            var timeline =
                (twitterCtx.Status.Where(tweet => tweet.Type == StatusType.User &&
                                                  tweet.ScreenName == screenname &&
                                                  tweet.Count == tweetCount))
                    .ToList();

            foreach (var tweet in timeline)
            {
                generator.ReadInput(tweet.Text);
            }

            int outputCount = 20;
            var outputList = new List<string>();
            for (int i = 0; i < outputCount; i++)
            {
                outputList.Add(generator.GenerateOutput());
            }

            //TODO add form
            //TODO use form data
            return View(outputList);
        }
示例#22
0
        List<Tweet> BasicSearch(string str)
        {
            Search srch;
            SearchQuery qu;
            Model1Container container = new Model1Container();
            container.Configuration.AutoDetectChangesEnabled = false;

            List<Tweet> returnList = new List<Tweet>();
            if(_context.RateLimitRemaining < 50)
            {
                Thread.Sleep(_context.RateLimitReset*1000 + 20000);
            }
            if (container.SearchQuerySet.Any(query => query.request == str))
            {
                qu = container.SearchQuerySet.FirstOrDefault(query => query.request == str);
                srch =
                    (from search in _context.Search
                        where search.Type == SearchType.Search &&
                              search.Query == str &&  search.SearchLanguage == "en" &&
                              search.Count == 100 && search.MaxID == (ulong) qu.lowestId select search)
                .SingleOrDefault();
                qu.lowestId = Int64.Parse(srch.Statuses.Min(status => status.StatusID));
            }
            else
            {
                qu = new SearchQuery();
                srch =
                (from search in _context.Search
                 where search.Type == SearchType.Search &&
                       search.Query == str &&
                       search.Count == 100
                 select search)
                .SingleOrDefault();
                qu.request = str;
                qu.lowestId = Int64.Parse(srch.Statuses.Min(status => status.StatusID));
                container.SearchQuerySet.Add(qu);
            }

            foreach (var entry in srch.Statuses)
            {
                Tweet tweet = new Tweet();
                tweet.lang = entry.Lang;
                tweet.text = entry.Text;
                tweet.user = entry.User.Name;

                tweet.SearchQuery = qu;
                tweet.statusID = entry.StatusID;
                tweet.date = entry.CreatedAt;
                tweet.retweet = entry.Retweeted;
                container.TweetSet.Add(tweet);
                returnList.Add(tweet);
            }
            container.SaveChanges();

            return returnList;
        }
 private IEnumerable<TweetFromUser> BuildLast20TweetsOfUser(IEnumerable<Status> tweets)
 {
     var last20TweetsFromUser = new List<TweetFromUser>();
      tweets.ToList().ForEach(tweet => last20TweetsFromUser
     .Add(new TweetFromUser
             {
                TweetText = tweet.Text
             }));
      return last20TweetsFromUser;
 }
        /// <summary>
        /// Get profile image of user
        /// </summary>
        /// <param name="screenName">string screen name</param>
        /// <returns>string url of profile image</returns>
        private string GetCoverImage(List<User> returnedUser)
        {
            var coverImage = "";

            foreach (var item in returnedUser)
            {
                coverImage = item.ProfileBannerUrl;
            }
            return coverImage;
        }
示例#25
0
        public override List<Result> Search(string pKeyWords)
        {
            string twitterConsumerKey = ConfigurationManager.AppSettings["twitter-consumer-key"];
            string twitterConsumerSecret = ConfigurationManager.AppSettings["twitter-consumer-secret"];

            if (string.IsNullOrWhiteSpace(twitterConsumerKey) || string.IsNullOrWhiteSpace(twitterConsumerSecret))
                throw new Exception("App was unable to find Twitter credentials on the current settings file. Please add twitter-consumer-key and twitter-consumer-secret to the appSettings section.");

            ApplicationOnlyAuthorizer authorization = new ApplicationOnlyAuthorizer()
            {
                Credentials = new InMemoryCredentials()
                {
                    ConsumerKey = twitterConsumerKey,
                    ConsumerSecret = twitterConsumerSecret
                }
            };

            authorization.Authorize();

            if(!authorization.IsAuthorized)
                throw new Exception("Twitter authorizaton was unsuccessful. Please review your Twitter key and secret.");

            TwitterContext twitterContext = new TwitterContext(authorization);

            LinqToTwitter.Search twitterSearch =
                (from search in twitterContext.Search
                 where search.Type == SearchType.Search &&
                       search.Query == pKeyWords &&
                       search.Count == this.MaxResultSearch
                 select search)
                .SingleOrDefault();

            IEnumerable<Status> tweets =
                from status in twitterSearch.Statuses
                orderby status.CreatedAt descending
                select status;

            List<Result> domainResults = new List<Result>();

            foreach (Status status in tweets)
            {
                domainResults.Add(
                    new Result()
                    {
                        CreatedDate = status.CreatedAt,
                        Type = SourceType.Twitter,
                        Text = status.Text,
                        Title = status.Text.Length > 50? string.Format("{0}...",status.Text.Substring(0, 47)) : status.Text,
                        URL = string.Format("http://twitter.com/{0}", status.User.Identifier.ScreenName)
                    }
                );
            }

            return domainResults;
        }
        public static void GetMostRecent10HomeTimeLine()
        {
            var twitterContext = new TwitterContext(authorizer);

            var tweets = from tweet in twitterContext.Status
                         where tweet.Type == StatusType.Home &&
                         tweet.Count == 10
                         select tweet;

            CurrentTweets = tweets.ToList();
        }
示例#27
0
文件: IrcalBot.cs 项目: foxjazz/IRCAL
        public void pushmessage(List<Message> lstmsg)
        {
           
            foreach (Message mm in lstmsg)
            {
                if(setChannel(mm) < 0)
                    return ;
               
                process(mm);
            }

        }
        /// <summary>
        /// Realiza a inicialização.
        /// </summary>
        public static void Initialize()
        {
            s_userNamesToLoginQueue = new Queue<string>(ConfigurationManager.AppSettings["twitterUserName"].Split(';'));
            s_accessTokenQueue = new Queue<string>(ConfigurationManager.AppSettings["twitterAccessToken"].Split(';'));
            s_oauthTokenQueue = new Queue<string>(ConfigurationManager.AppSettings["twitterOAuthToken"].Split(';'));
            s_auths = new List<PinAuthorizer>(s_userNamesToLoginQueue.Count);
            Contexts = new List<TwitterContext>();
            Accounts = new List<DGAccount>();
            s_millsecondsIntervalToUpdate = Convert.ToInt32(ConfigurationManager.AppSettings["secondsIntervalToUpdate"]) * 1000;

            Initialized = true;
        }
        private IEnumerable<TweetFromUser> BuildTweetsFromStatuses(IEnumerable<Status> myWall)
        {
            var tweetFromUserList = new List<TweetFromUser>();
             myWall.ToList().ForEach(tweet => tweetFromUserList
                                             .Add(new TweetFromUser
                                                     {
                                                        TweetText = tweet.Text,
                                                        User = BuildUserOffUserId(tweet.User.Identifier.UserID)
                                                     }));

             return tweetFromUserList;
        }
示例#30
0
 public static List<string> getstopwords(string lang)
 {
     //lang can be implemented later. XML doc has lang attribute in wordlist element.
     List<string> sw = new List<string>();
     XmlDocument xd = new XmlDocument();
     xd.Load(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content/StopWords.xml"));
     XmlNodeList nl = xd.SelectNodes("/wordlist/word");
     foreach (XmlNode n in nl)
     {
         sw.Add(n.InnerText);
     }
     return sw;
 }