Exemplo n.º 1
0
    def __init__(self, storage_dir=False, db=False):
        """Initialise the API."""
        if not db and not storage_dir:
            raise TypeError(
                "Twitter() needs either a storage_dir or a db argument."
            )

        if not db:
            db = DB(storage_dir)
        self.db = db
        ck = self.db.get_config('consumer_key')
        cs = self.db.get_config('consumer_secret')
        at = self.db.get_config('access_token')
        ats = self.db.get_config('access_token_secret')
        mf = wtModelFactory()
        pr = ModelParser(model_factory=mf)
        self.auth = OAuthHandler(ck, cs)
        self.auth.set_access_token(at, ats)
        self.api = API(self.auth, parser=pr)
        try:
            self.api.me().name
        except TweepError as error:
            raise TwitterError("Could not connect to Twitter: %s" % error)
        except TypeError as error:
            raise TwitterError("Your keys haven't been set correctly!")
Exemplo n.º 2
0
 def update_status(self, message, reply_id=False):
     """Posts text to twitter."""
     if self.__is_sane(message):
         try:
             self.api.update_status(message, in_reply_to_status_id=reply_id)
         except TweepError as error:
             raise TwitterError("Failed to post status: %s" % error)
         return "Status updated."
     else:
         raise TwitterError("Status too long!")
Exemplo n.º 3
0
 def get_tweet(self, identification):
     """Return a tweet from either an integer or cached screen name."""
     tid = False
     try:
         int(identification)
         tid = identification
     except ValueError:
         identification = identification.lstrip("@")
         tid = self.db.get_last_tid(identification)
         if not tid:
             raise TwitterError("ID %s not cached." % identification)
     try:
         return self.api.get_status(tid, include_entities=True)
     except TweepError as error:
         raise TwitterError("Failed to get tweet: %s" % error)
Exemplo n.º 4
0
 def get_followed(self):
     """Returns an array of screen_names that you follow."""
     try:
         followed = [u.screen_name for u in self.api.friends()]
     except TweepError as error:
         raise TwitterError("Faled to get followed: %s" % error)
     return followed
Exemplo n.º 5
0
 def get_user(self, user):
     """Returns the requested user."""
     try:
         user = self.api.get_user(user, include_entities=True)
     except TweepError as error:
         raise TwitterError("Failed to get user: %s" % error)
     return user
Exemplo n.º 6
0
 def get_favorites(self):
     """Get your favourite tweets."""
     try:
         favorites = self.api.favorites(include_entities=True)
     except TweepError as error:
         raise TwitterError("Failed to get favourites: %s" % error)
     return favorites
Exemplo n.º 7
0
    def on_timeout(self):
        """We want to keep retrying for self.retry_count amount of times."""
        self.error_count += 1
        if self.error_count > self.timeout_count:
            raise TwitterError("Connection timed out for %s times." %
                               self.error_count)

        return True
Exemplo n.º 8
0
 def get_followed(self):
     """Returns an array of screen_names that you follow."""
     try:
         followed = []
         for user in Cursor(self.api.friends).items(200):
             followed.append(user.screen_name)
     except TweepError as error:
         raise TwitterError("Faled to get followed: %s" % error)
     return followed
Exemplo n.º 9
0
 def next(self):
     "Returns the next status."
     try:
         status_file = self.status_files.pop()
         with file(status_file) as f:
             status = Tweet.parse(self.api, json.loads(f.read()))
         os.unlink(status_file)
         return status
     except IndexError:
         raise StopIteration()
     except TwitterError as error:
         os.unlink(status_file)
         raise TwitterError(str(error))
Exemplo n.º 10
0
    def get_trends(self, woeid):
        """
        Gets the current trends for the location represented by woeid.
        Returns a list of trends with element 0 representing the location name.
        """
        try:
            trend_response = self.api.trends_place(woeid)
        except TweepError as error:
            raise TwitterError("Failed to get trends: %s" % error)

        trends = []
        trends.append(trend_response[0]['locations'][0]['name'])
        for trend in trend_response[0]['trends']:
            trends.append(trend['name'])

        return trends
Exemplo n.º 11
0
 def parse(cls, api, json):
     """Add some stuff to the parse routine."""
     status = super(Tweet, cls).parse(api, json)
     try:
         tid = status.retweeted_status.id
         txt = status.retweeted_status.text
         name = status.retweeted_status.user.name
         screen_name = status.retweeted_status.user.screen_name
         is_retweet = True
     except AttributeError:
         try:
             tid = status.id
             txt = status.text
             name = status.user.name
             screen_name = status.user.screen_name
             is_retweet = False
         except AttributeError:
             raise TwitterError(
                 "Found a non status update. (Probably a favourite notification)"
             )
     rtname = status.user.name
     rtscreen_name = status.user.screen_name
     url = 'https://twitter.com/{user}/status/{id}'.format(user=screen_name,
                                                           id=tid)
     setattr(status, 'tid', tid)
     setattr(status, 'txt_unescaped', unescape(txt))
     setattr(status, 'name', unescape(name))
     setattr(status, 'screen_name', screen_name)
     setattr(status, 'rtname', unescape(rtname))
     setattr(status, 'rtscreen_name', rtscreen_name)
     setattr(status, 'is_retweet', is_retweet)
     setattr(status, 'txt_unescaped', status.txt_unescaped)
     setattr(status, 'txt', status.expand_urls(status.txt_unescaped))
     setattr(status, 'source', unescape(status.source))
     setattr(status, 'url', url)
     return status
Exemplo n.º 12
0
    def get_trend_places(self):
        """
        Returns a dict of dicts, first by country then by place.
        Every country has a special 'woeid' key that holds the woeid of the
        country itself and all the places of the country pointing to their
        respective woeids.
        A special exception is the 'Worldwide' "country" which only has a
        woeid entry.
        """
        try:
            trend_places = self.api.trends_available()
        except TweepError as error:
            raise TwitterError("Falied to get available places: %s." % error)

        places = defaultdict(dict)
        for place in trend_places:
            if not place['country']:
                places['Worldwide'] = {'woeid': place['woeid']}
            else:
                if place['country'] == place['name']:
                    places[place['country']]['woeid'] = place['woeid']
                else:
                    places[place['country']][place['name']] = place['woeid']
        return places
Exemplo n.º 13
0
 def on_error(self, status_code):
     """Handle errors."""
     if status_code == 420:
         raise TwitterError(
             "Too many searches open, please close one and try again.")
     return True