【问题标题】:How to use tweepy api v2 to get status?如何使用 tweepy api v2 获取状态?
【发布时间】:2022-12-11 06:23:39
【问题描述】:

我用 tweepy 和 python 创建了这个机器人,基本上我可以转发包含特定关键字的最新推文。我想获取具有该关键字的推文的状态,以便我知道我是否已经转发了它。

import time

import tweepy
import config

# Search/ Like/ Retweet


def get_client():
    client = tweepy.Client(bearer_token=config.BEARER_TOKEN,
                           consumer_key=config.CONSUMER_KEY,
                           consumer_secret=config.CONSUMER_SECRET,
                           access_token=config.ACCESS_TOKEN,
                           access_token_secret=config.ACCESS_TOKEN_SECRET, )
    return client


def search_tweets(query):
    client = get_client()

    tweets = client.search_recent_tweets(query=query, max_results=20)

    tweet_data = tweets.data

    results = []

    if tweet_data is not None and len(tweet_data) > 0:
        for tweet in tweet_data:
            obj = {'id': tweet.id, 'text': tweet.text}
            results.append(obj)
    else:
        return 'There are no tweets with that keyword!'

    return results


client = get_client()

tweets = search_tweets('#vinu')

for tweet in tweets:
    client.retweet(tweet["id"])
    client.like(tweet['id'])
    time.sleep(2)

这是代码。我想创建一个 if 语句来检查我是否已经转发了它,如果是,则继续循环中的下一个项目。我知道我可以将 api.get_status 与 api v1 一起使用,但我不知道如何使用 v2 来做到这一点。请帮帮我。

 if tweet_data is not None and len(tweet_data) > 0:
        for tweet in tweet_data:
            status = tweepy.api(client.access_token).get_status(tweet.id)
            if status.retweeted:
                continue
            else:
                obj = {'id': tweet.id, 'text': tweet.text}
                results.append(obj)
    else:
        return ''

    return results

这应该在 v1 中工作,请帮助我在 v2 中做同样的事情。谢谢!

【问题讨论】:

    标签: python tweepy


    【解决方案1】:

    对于 Tweepy API v2,您可以对每条推文使用 get_retweeters() 方法,然后将您的用户 ID 与检索到的转发者 ID 进行比较。

    if tweet_data is not None and len(tweet_data) > 0:
            for tweet in tweet_data:
                status = client.get_retweeters(tweet.id, max_results=3)
                for stat in status.data:
                    if stat.id == YOUR_ID_HERE:
                        continue
                    else:
                        obj = {'id': tweet.id, 'text': tweet.text}
                        results.append(obj)
        else:
            return 'There are no tweets with that keyword!'
    
        return results
    

    只要您正确管理费率,就可以将 max_results 更改为您想要的任何限制。如果您没有得到任何结果,请尝试将 tweet.id 更改为具有转推的静态 ID 并仅测试那个,这是由于许多推文没有任何转推。

    您可以使用您的推特用户名here找到一种简单的方法来查找您的推特 ID

    【讨论】:

      猜你喜欢
      • 2022-10-05
      • 2013-03-04
      • 2011-03-16
      • 1970-01-01
      • 2022-10-18
      • 2022-12-10
      • 2021-12-31
      • 1970-01-01
      • 2016-08-11
      相关资源
      最近更新 更多