【问题标题】:Tweepy does not return includes object using StreamingClientTweepy 不使用 StreamingClient 返回包含对象
【发布时间】:2022-10-01 07:58:15
【问题描述】:

我正在使用tweepy4.10.1 来获取使用StreamingClient 的推文,但我无法加载任何media 信息甚至includes 对象本身。我已经使用get_tweet() 方法尝试了类似的代码,mediaincludes 收到了很好的结果。

编码:

class TweetPrinter(tweepy.StreamingClient):
    def on_tweet(self, tweet):
        print(tweet.includes)


streaming_client = TweetPrinter(\'bearer-token\')

streaming_client.add_rules(tweepy.StreamRule(\"from:xxxyyy\"))

streaming_client.filter(tweet_fields=[\'author_id\', \'created_at\'],
                        media_fields=[\'preview_image_url\', \'url\'],
                        expansions=[\'attachments.media_keys\'])

print(tweet.includes)

我收到以下错误:

raise AttributeError from None

当我通过get_tweet() 方法使用相同的推文ID 时,我可以从includes 很好地检索media

client = tweepy.Client(config.BEARER)

ID = \'xxxxyyyy\'

tweet = client.get_tweet(ID,
                         tweet_fields=[\'author_id\', \'created_at\'],
                         media_fields=[\'preview_image_url\', \'url\'],
                         expansions=[\'attachments.media_keys\'])

print(tweet.includes)

根据谷歌,官方文档和常见问题解答,我已经尝试了我发现的所有推荐步骤

我在这里想念什么?

    标签: python python-3.x twitter tweepy


    【解决方案1】:

    编辑

    我发现使用on_data() 是正确的检索方式全部来自推文的数据。它涵盖了所有tweetincludes 和其他对象。

    所以正确的代码应该是这样的:

    import orjson
    
    class TweetPrinter(tweepy.StreamingClient):
        def on_data(self, raw_data):
            # Received as bytes, needs to be loaded by json (I use orjson)
            raw_data = orjson.loads(raw_data)
            print("data")
            print(raw_data.get('data', None))
            print("media")
            print(raw_data.get('includes', None))
    
    

    已弃用的解决方案

    TweetPrinter 类应该包含当includes 像这样收到时要处理的函数:

    class TweetPrinter(tweepy.StreamingClient):
        def on_tweet(self, tweet):
            print(tweet.data)
    
        def on_includes(self, includes):
            print(includes)
    

    感谢this 文章,它帮助我找到了正确的解决方案:)

    【讨论】:

      猜你喜欢
      • 2022-07-04
      • 1970-01-01
      • 2012-01-14
      • 2013-11-28
      • 1970-01-01
      • 2011-03-28
      • 2017-08-27
      • 1970-01-01
      • 2019-04-29
      相关资源
      最近更新 更多