【问题标题】:Get the last tweet with tweepy使用 tweepy 获取最后一条推文
【发布时间】:2015-11-08 11:08:37
【问题描述】:

我正在尝试使用 Tweepy 获取用户的最后一条推文。这是我的代码:

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' . 

我了解错误,但我怎样才能从状态中获取文本?

【问题讨论】:

    标签: python twitter tweepy


    【解决方案1】:

    API.user_timelines 的返回值,如API reference 所述,是一个状态对象的列表

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

    注意额外的[0] 以获取第一个条目。

    我很确定 Tweepy 的作者很乐意接受带有改进文档的拉取请求;)

    【讨论】:

    • 非常感谢!我想我会为文档提供帮助,同时我会很好地使用 tweepy(也许法国文档对我来说更容易)。还有一个问题,如何从这条推文中获取网址?我可以让它变得简单(https://twitter.com/{}/status/{}.format(tweet.user.screen_name, tweet.id)`),但是否有直接带有 url 的属性?再次感谢!
    • 看代码应该可以使用API.get_oembed。在您的情况下,类似于self.client.get_oembed(id=tweet.id).url。但这只是一个猜测,我没有测试过。
    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 2015-04-27
    • 2015-08-02
    • 2021-02-25
    相关资源
    最近更新 更多