Read all the dweets for a dweeter
962789
def get_dweets_for(thing_name, key=None, session=None):
    
    if key is not None:
        params = {'key': key}
    else:
        params = None
    return _request('get', '/get/dweets/for/{0}'.format(thing_name), params=params, session=None)
1301827
public function read(): array
    {
        while (!$this->streamBody->eof()) {
            $tweet = json_decode(
                $this->readStreamLine($this->streamBody),
                true
            );

            if (null !== $tweet) {
                return $tweet;
            }
        }
    }
614403
@Override
    public void getMentions() {
        getDispatcher().invokeLater(new AsyncTask(MENTIONS_TIMELINE, listeners) {
            @Override
            public void invoke(List<TwitterListener> listeners) throws TwitterException {
                ResponseList<Status> statuses = twitter.getMentionsTimeline();
                for (TwitterListener listener : listeners) {
                    try {
                        listener.gotMentions(statuses);
                    } catch (Exception e) { 
                        logger.warn("Exception at getMentions", e);
                    }
                }
            }
        });
    }
970260
function getFields(tweet) {
  return _.flatten(tweetLikeObjectsToCheck.map(function(tweetLikeName) {
    var tweetLike;
    if (tweetLikeName === null) {
      tweetLike = tweet;
    } else {
      tweetLike = _.get(tweet, tweetLikeName);
    }
    if (!tweetLike) return [];
    return getFieldsFromTweetLike(tweetLike);
  }));
}
1197041
def makeRetweetNetwork(tweets):
    
    G=x.DiGraph()
    G_=x.DiGraph()
    for tweet in tweets:
        text=tweet["text"]
        us=tweet["user"]["screen_name"]
        if text.startswith("RT @"):
            prev_us=text.split(":")[0].split("@")[1]
            #print(us,prev_us,text)
            if G.has_edge(prev_us,us):
                G[prev_us][us]["weight"]+=1
                G_[prev_us][us]["weight"]+=1
            else:
                G.add_edge(prev_us, us, weight=1.)
                G_.add_edge(prev_us, us, weight=1.)
        if us not in G_.nodes():
            G_.add_node(us)
    return G,G_
638877
def pytwis_clt():
    """"""
    epilog = '''After launching `pytwis_clt.py`, you will be able to use the following commands:

    * Register a new user:

        127.0.0.1:6379> register {username} {password}

    * Log into a user:  

        127.0.0.1:6379> login {username} {password} 

    * Log out of a user:

        127.0.0.1:6379> logout

    * Change the password:

        127.0.0.1:6379> changepwd {old_password} {new_password} {confirmed_new_password}

    * Get the profile of the current user:

        127.0.0.1:6379> userprofile

    * Post a tweet:

        127.0.0.1:6379> post {tweet}

    * Follow a user:

        127.0.0.1:6379> follow {followee_username}

    * Unfollow a user:

        127.0.0.1:6379> unfollow {followee_username}

    * Get the follower list:

        127.0.0.1:6379> followers

    * Get the following list:

        127.0.0.1:6379> followings

    * Get the timeline:

        127.0.0.1:6379> timeline
        127.0.0.1:6379> timeline {max_tweet_count}

    Note that if a user is logged in, `timeline` will return the user timeline; 
    otherwise `timeline` will return the general timeline.

    * Get the tweets posted by a user:

        127.0.0.1:6379> tweetsby 
        127.0.0.1:6379> tweetsby {username}
        127.0.0.1:6379> tweetsby {username} {max_tweet_count}

    Note that if no username is given, `tweetsby` will return the tweets posted 
    by the currently logged-in user.

    * Exit the program:

        127.0.0.1:6379> exit
        127.0.0.1:6379> quit
    '''
    twis, prompt = get_pytwis(epilog)
    if twis is None:
        return -1

    auth_secret = ['']
    while True:
        try:
            arg_dict = pytwis_command_parser(
                input('Please enter a command '
                      '(register, login, logout, changepwd, userprofile, post, '
                      'follow, unfollow, followers, followings, timeline, tweetsby):\n{}> '\
                      .format(prompt)))
            if arg_dict[pytwis_clt_constants.ARG_COMMAND] == pytwis_clt_constants.CMD_EXIT \
                or arg_dict[pytwis_clt_constants.ARG_COMMAND] == pytwis_clt_constants.CMD_QUIT:
                # Log out of the current user before exiting.
                if auth_secret[0]:
                    pytwis_command_processor(twis, auth_secret,
                                             {pytwis_clt_constants.ARG_COMMAND:
                                              pytwis_clt_constants.CMD_LOGOUT})
                print('pytwis is exiting.')
                return 0

        except ValueError as excep:
            print('Invalid pytwis command: {}'.format(str(excep)),
                  file=sys.stderr)
            continue

        pytwis_command_processor(twis, auth_secret, arg_dict)
466690
def print_tweets(tweets):
    
    print('=' * 60)
    for index, tweet in enumerate(tweets):
        print('-' * 60)
        print('Tweet {}:'.format(index))
        print('Username:', tweet[pytwis_constants.USERNAME_KEY])
        print('Time:',
              datetime.datetime.fromtimestamp(int(tweet[pytwis_constants.TWEET_UNIXTIME_KEY])).\
              strftime('%Y-%m-%d %H:%M:%S'))
        print('Body:\n\t', tweet[pytwis_constants.TWEET_BODY_KEY])
        print('-' * 60)
    print('=' * 60)
461831
def tweets_for_user(screen_name, limit=1e10):
    
    qu = Queue()
    p = Thread(target=_tweets_for_user, args=(qu, screen_name, limit))
    p.start()
    p.join(910)
    if p.is_alive():
        sys.stderr.write('no results after 15 minutes for %s. Aborting.' % screen_name)
        return []
    else:
        return qu.get()
375164
def auto_retweet(bot):
    """"""
    conn = bot.get_social_connection(id='twitter')
    dirname = os.path.expanduser('~/.irc3/twitter/{nick}'.format(**bot.config))

    if not os.path.isdir(dirname):
        os.makedirs(dirname)

    filename = os.path.join(dirname, 'retweeted')
    if os.path.isfile(filename):
        with open(filename) as fd:
            retweeted = [i.strip() for i in fd.readlines()]
    else:
        retweeted = []

    for user in ('pypi', 'gawel_'):
        results = conn.search.tweets(
            q=user + ' AND irc3',
            result_type='recent')
        for item in results.get('statuses', []):
            if item['user']['screen_name'] == user:
                if item['id_str'] not in retweeted:
                    res = conn(getattr(conn.statuses.retweet, item['id_str']))
                    if 'id' in res:
                        with open(filename, 'a+') as fd:
                            fd.write(item['id_str'] + '\n')
211840
def tweet(args = {})
      options = {
        num_hashtags: [0, rand(1..10) - 6].max,
        num_mentions: [0, rand(1..10) - 8].max,
        reply: (rand(1..10) == 1),
        body_length: rand(20..140)
      }.merge(args)

      my_reply = options[:reply] ? "#{mention} " : ''
      my_mentions = options[:num_mentions] > 0 ? "#{mentions(options[:num_mentions])} " : ''
      my_tags = tags(options[:num_hashtags])

      remaining = [
        options[:body_length],
        140 - (my_reply.size + my_mentions.size + my_tags.size)
      ].min

      "#{my_reply}#{body(remaining)}#{my_mentions}#{my_tags}"
    end
1363620
def main(args):
    """"""
    global logging, log

    args = parse_args(args)
    logging.basicConfig(format=LOG_FORMAT,
                        level=logging.DEBUG if args.verbose else logging.INFO,
                        stream=sys.stdout)
    df = cat_tweets(path=args.path, verbosity=args.verbose + 1, numtweets=args.numtweets, ignore_suspicious=False)
    log.info('Combined {} tweets'.format(len(df)))
    df = drop_nan_columns(df)
    save_tweets(df, path=args.path, filename=args.tweetfile)
    geo = get_geo(df, path=args.path, filename=args.geofile)
    log.info("Combined {} tweets into a single file {} and set asside {} geo tweets in {}".format(
        len(df), args.tweetfile, len(geo), args.geofile))
    return df, geo
68667
def dweet_for(thing_name, payload, key=None, session=None):
    
    if key is not None:
        params = {'key': key}
    else:
        params = None
    return _send_dweet(payload, '/dweet/for/{0}'.format(thing_name), params=params, session=session)
1365149
def read(self):
        """"""

        for line in self.io.read():
            with self.parse_line(line) as j:
                yield j
162849
@Override
    public void getRetweets(final long statusId) {
        getDispatcher().invokeLater(new AsyncTask(RETWEETS, listeners) {
            @Override
            public void invoke(List<TwitterListener> listeners) throws TwitterException {
                ResponseList<Status> statuses = twitter.getRetweets(statusId);
                for (TwitterListener listener : listeners) {
                    try {
                        listener.gotRetweets(statuses);
                    } catch (Exception e) {
                        logger.warn("Exception at getRetweets", e);
                    }
                }
            }
        });
    }
732509
def get_all_docs(self, screen_name):
        
        def _getNewTweets(api, screen_name,count=200, oldest=None, waitTime=60):
            """
                MEthod that recovers the new tweets or waits until the number of remaining calls has been freed.

                :param api:     A valid and connected api.
                :param screen_name: screen_name of the user to monitor.
                :param count:   Number of tweets to grab per iteration.
                :param oldes:  Oldest tweet to grab in this iteration.
                :param waitTime:    Number of seconds to wait between tries.

                :return:  List of new_tweets
            """
            # Verifying the limits of the API
            #self._rate_limit_status(api=api, mode="get_all_docs")

            waiting = True
            while waiting == True:
                try:
                    if oldest != None:
                        # We have to update the oldest id
                        new_tweets = api.user_timeline(screen_name=screen_name, count=count, max_id=oldest)
                    else:
                        new_tweets = api.user_timeline(screen_name=screen_name, count=count)
                    waiting = False
                    #save most recent tweets

                except Exception as e:
                    # Error... We will have to wait
                    #waiting = True
                    print str(e)
                    #print(traceback.format_exc())
                    print "No more queries remaining, sleeping for " + str(waitTime) +" seconds..."
                    time.sleep(waitTime)

            return new_tweets

        # Connecting to the API
        api = self._connectToAPI()

        #initialize a list to hold all the tweepy Tweets
        alltweets = []

        #make initial request for most recent tweets (200 is the maximum allowed count)
        """waiting = True
        while waiting == True:
            try:
                new_tweets = api.user_timeline(screen_name = screen_name,count=200)
                waiting = False
            except:
                # Error... We will have to wait
                waiting = True
                time.sleep(waitTime)  """
        new_tweets = _getNewTweets(api, screen_name)

        alltweets.extend(new_tweets)
        # Storing manually all the json representation for the tweets
        jTweets = []
        for n in new_tweets:
            jTweets.append(n._json)
        if len(alltweets) > 0:
            #save the id of the oldest tweet less one
            oldest = alltweets[-1].id - 1

            #keep grabbing tweets until there are no tweets left to grab
            while len(new_tweets) > 0:
                print "Getting tweets before %s" % (oldest)

                """ #all subsequent requests use the max_id param to prevent duplicates
                waiting = True
                while waiting == True:
                    try:
                        # We have to update the oldest id
                        new_tweets = api.user_timeline(screen_name = screen_name,count=200, max_id=oldest)
                        waiting = False
                        #save most recent tweets

                    except:
                        # Error... We will have to wait
                        waiting = True
                        print "No more queries remaining, sleeping for " + str(waitTime) +" seconds..."
                        time.sleep(waitTime)  """

                new_tweets = _getNewTweets(api, screen_name, oldest=oldest)

                # Extending the list of tweets
                alltweets.extend(new_tweets)

                #update the id of the oldest tweet less one
                oldest = alltweets[-1].id - 1
                print "... %s tweets downloaded so far" % (len(alltweets))
                # Storing manually all the json representation for the tweets
                for n in new_tweets:
                    jTweets.append(n._json)
        else:
            # Verifying the limits of the API
            print json.dumps(self._rate_limit_status(api=api, mode="get_all_docs"), indent =2)

        #transform the tweepy tweets into a 2D array that will populate the csv
        outtweets = []
        # This is how it is represented
        """
          "status": {
            "lang": "es",
            "favorited": false,
            "entities": {
              "symbols": [],
              "user_mentions": [],
              "hashtags": [],
              "urls": []
            },
            "contributors": null,
            "truncated": false,
            "text": "Podemos confirmar que Alpify, aunque acabe en ...fy no es una aplicaci\u00f3n nuestra. ;) \u00a1A aprovechar lo que queda de domingo!",
            "created_at": "Sun Aug 16 17:35:37 +0000 2015",
            "retweeted": true,
            "in_reply_to_status_id_str": null,
            "coordinates": null,
            "in_reply_to_user_id_str": null,
            "source": "<a href=\"http://twitter.com\" rel=\"nofollow\">Twitter Web Client</a>",
            "in_reply_to_status_id": null,
            "in_reply_to_screen_name": null,
            "id_str": "632968969662689280",
            "place": null,
            "retweet_count": 1,
            "geo": null,
            "id": 632968969662689280,
            "favorite_count": 0,
            "in_reply_to_user_id": null
          },
        """
        for tweet in jTweets:
            row =[]
            row.append(tweet["id_str"])
            row.append(tweet["created_at"])
            row.append(tweet["text"].encode("utf-8"))
            row.append(tweet["source"])
            row.append(tweet["coordinates"])
            row.append(tweet["retweet_count"])
            row.append(tweet["favorite_count"])
            row.append(tweet["lang"])
            row.append(tweet["place"])
            row.append(tweet["geo"])
            row.append(tweet["id"])
            row.append(screen_name)

            # URLS
            urls = []
            """
            [
                {
                  "url": "http://t.co/SGty7or6SQ",
                  "indices": [
                    30,
                    52
                  ],
                  "expanded_url": "http://github.com/i3visio/osrframework",
                  "display_url": "github.com/i3visio/osrfra\u2026"
                }
            ]
            """
            for u in tweet["entities"]["urls"]:
                urls.append(u["expanded_url"])
            # Creating the string value for the cell
            str_urls =""
            if len(urls) == 0:
                str_urls = "[N/A]"
            else:
                for i, u in enumerate(urls):
                    str_urls += u
                    # Appending a separator
                    if i+1 <> len(urls):
                        str_urls+= "|"
            row.append(str_urls.encode('utf-8'))

            # TODO: Extract Mentions
            mentions = []
            """ "user_mentions": [
              {
                "id": 66345537,
                "indices": [
                  0,
                  10
                ],
                "id_str": "66345537",
                "screen_name": "muchotomy",
                "name": "Tomy"
              },
            """
            for a in tweet["entities"]["user_mentions"]:
                mentions.append(a["screen_name"])
            # Creating the string value for the cell
            str_mentions =""
            if len(mentions) == 0:
                str_mentions = "[N/A]"
            else:
                for i, m in enumerate(mentions):
                    str_mentions += m
                    # Appending a separator
                    if i+1 <> len(mentions):
                        str_mentions+= "|"
            row.append(str_mentions.encode('utf-8'))

            # Appending the row to the output
            outtweets.append(row)

        # Writing the csv
        with open('%s_tweets.csv' % screen_name, 'wb') as f:
            writer = csv.writer(f)
            # Writing the headers
            writer.writerow([
                "_tweet_id",
                "_tweet_created_at",
                "_tweet_text",
                "_tweet_source",
                "_tweet_coordinates",
                "_tweet_retweet_count",
                "_tweet_favourite_count",
                "_tweet_lang",
                "i3visio_location",
                "_tweet_geo",
                "_twitter_id",
                "i3visio_alias",
                "i3visio_uri",
                "i3visio_alias_mentions",
            ])
            # Writing the rows
            #writer.writerows(outtweets)
            for o in outtweets:
                try:
                    writer.writerow(o)
                except:
                    print o

        return jTweets
403502
def classify(self, tweets):
        
        if type(tweets) == str:
            return self.classifier.classify(tweets)

        return list(map(lambda tweet: self.classifier.classify(tweet), tweets))
213205
public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("java twitter4j.examples.search.SearchTweets [query]");
            System.exit(-1);
        }
        Twitter twitter = new TwitterFactory().getInstance();
        try {
            Query query = new Query(args[0]);
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
        }
    }