Search code examples
pythontwittertweepy

Get the last tweet with tweepy


I'm trying to have the last tweet of the user with Tweepy. This is my code :

class Bot:
    def __init__(self, keys):
        self._consumer_key = keys[0]
        self._consumer_secret = keys[1]
        self._access_token = keys[2]
        self._access_secret = keys[3]

        try:
            auth = tweepy.OAuthHandler(self._consumer_key,
                                       self._consumer_secret)
            auth.set_access_token(self._access_token, self._access_secret)

            self.client = tweepy.API(auth)
            if not self.client.verify_credentials():
                raise tweepy.TweepError
        except tweepy.TweepError as e:
            print('ERROR : connection failed. Check your OAuth keys.')
        else:
            print('Connected as @{}, you can start to tweet !'.format(self.client.me().screen_name))
            self.client_id = self.client.me().id


    def get_last_tweet(self):
        tweet = self.client.user_timeline(id = self.client_id, count = 1)
        print(tweet.text)
        # AttributeError: 'ResultSet' object has no attribute 'text' . 

I understand the error, but how can I have the text from a status?


Solution

  • The return value of API.user_timelines, as stated in the API reference, is a list of Status objects.

    def get_last_tweet(self):
        tweet = self.client.user_timeline(id = self.client_id, count = 1)[0]
        print(tweet.text)
    

    Note the additional [0] to fetch the first entry.

    I'm pretty sure the author of Tweepy happily accepts a pull request with improved documentation ;)