def __init__(self, instance_name, consumer_key, consumer_secret, access_token, access_token_secret, testing=False):
     logging.debug("Authenticating with Twitter")
     auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
     auth.set_access_token(access_token, access_token_secret)
     self.api = tweepy.API(auth)
     self.settings = WMTSettings(instance_name)
     self.testing = testing
     self.report_twitter_limit_status()
Exemplo n.º 2
0
    def __init__(self, instance_name, consumer_key, consumer_secret, access_token, access_token_secret, testing=False):
        logging.debug("Authenticating with Twitter")
        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        self.api = tweepy.API(auth)
        self.settings = WMTSettings(instance_name)
        self.testing = testing

        # By default, we check all streams, checking limit status may change this however
        self.do_check_followers = True
        self.do_fetch_replies = True
        self.do_fetch_direct_messages = True

        if not self.testing:
            self.report_twitter_limit_status()
class WMTTwitterClient():
    """
    A Twitter Client that fetches Tweets and manages follows for When's My Transport
    """
    def __init__(self, instance_name, consumer_key, consumer_secret, access_token, access_token_secret, testing=False):
        logging.debug("Authenticating with Twitter")
        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        self.api = tweepy.API(auth)
        self.settings = WMTSettings(instance_name)
        self.testing = testing
        self.report_twitter_limit_status()

    def check_followers(self):
        """
        Check my followers. If any of them are not following me, try to follow them back
        """
        # Don't bother if we have checked in the last ten minutes
        last_follower_check = self.settings.get_setting("last_follower_check") or 0
        if time.time() - last_follower_check < 600:
            return
        logging.info("Checking to see if I have any new followers...")
        self.settings.update_setting("last_follower_check", time.time())

        # Get IDs of our friends (people we already follow), and our followers
        followers_ids = self.api.followers_ids()
        friends_ids = self.api.friends_ids()

        # Annoyingly, different versions of Tweepy implement the above; older versions return followers_ids() as a tuple and the list of
        # followers IDs is the first element of that tuple. Newer versions return just the followers' IDs (which is much more sensible)
        if isinstance(followers_ids, tuple):
            followers_ids = followers_ids[0]
            friends_ids = friends_ids[0]

        # Some users are protected and have been requested but not accepted - we need not continually ping them
        protected_users_to_ignore = self.settings.get_setting("protected_users_to_ignore") or []

        # Work out the difference between the two, and also ignore protected users we have already requested
        # Twitter gives us these in reverse order, so we pick the final twenty (i.e the earliest to follow)
        # reverse these to give them in normal order, and follow each one back!
        twitter_ids_to_follow = [f for f in followers_ids if f not in friends_ids and f not in protected_users_to_ignore][-20:]
        for twitter_id in twitter_ids_to_follow[::-1]:
            try:
                person = self.api.create_friendship(twitter_id)
                logging.info("Following user %s", person.screen_name)
            except tweepy.error.TweepError:
                protected_users_to_ignore.append(twitter_id)
                logging.info("Error following user %s, most likely the account is protected", twitter_id)
                continue

        self.settings.update_setting("protected_users_to_ignore", protected_users_to_ignore)
        self.report_twitter_limit_status()

    def fetch_tweets(self):
        """
        Fetch Tweets that are replies & direct messages to us and return as a list
        """
        # Get the IDs of the Tweets and Direct Message we last answered
        last_answered_tweet = self.settings.get_setting('last_answered_tweet') or 1
        last_answered_direct_message = self.settings.get_setting('last_answered_direct_message') or 1

        # Fetch those Tweets and DMs. This is most likely to fail if OAuth is not correctly set up
        try:
            tweets = self.api.mentions(since_id=last_answered_tweet)
            direct_messages = self.api.direct_messages(since_id=last_answered_direct_message)
            #tweets = tweepy.Cursor(self.api.mentions, since_id=last_answered_tweet).items(10)
            #direct_messages = tweepy.Cursor(self.api.direct_messages, since_id=last_answered_direct_message).items(10)
        except tweepy.error.TweepError, e:
            logging.error("Error: OAuth connection to Twitter failed, probably due to an invalid token")
            raise RuntimeError("Error: OAuth connection to Twitter failed, probably due to an invalid token")

        # Convert iterators to lists & reverse
        tweets = list(tweets)[::-1]
        direct_messages = list(direct_messages)[::-1]

        # No need to bother if no replies
        if not tweets and not direct_messages:
            logging.info("No new Tweets, exiting...")
        else:
            logging.info("%s replies and %s direct messages received!", len(tweets), len(direct_messages))

        # Keep an eye on our rate limit, for science
        self.report_twitter_limit_status()
        return direct_messages + tweets