python Twitter API V2关注查找

ca1c2owp  于 2023-08-02  发布在  Python
关注(0)|答案(1)|浏览(145)

bounty还有6天到期。回答此问题可获得+50声望奖励。Ebikeneser正在寻找一个答案从一个有信誉的来源:我想一个工作的例子,最好备份一个可信的资源。

我正在尝试使用Python检索Twitter帐户关注的人的列表。
在意识到免费层API访问不提供此端点后,我将我的开发人员帐户升级到基本计划(每月100美元),因为它明确指出,一旦注册,您可以检索帐户的追随者或追随者。
我已经创建了一个脚本,应该检索的追随者帐户的基础上,用户id -

import requests

def get_followers(user_id, bearer_token):
    url = f'https://api.twitter.com/2/users/{user_id}/followers'
    headers = {'Authorization': f'Bearer {bearer_token}'}

    all_followers = []

    while True:
        response = requests.get(url, headers=headers)

        if response.status_code == 200:
            result_data = response.json()
            all_followers.extend(result_data['data'])

            if 'next_token' in result_data['meta']:
                next_token = result_data['meta']['next_token']
                url = f'https://api.twitter.com/2/users/{user_id}/followers?pagination_token={next_token}'
            else:
                break
        else:
            print(f"Failed to get followers for user ID '{user_id}' with status code: {response.status_code}")
            print(response.json())
            return None

    return all_followers

字符串
然而,我得到了以下(似乎很常见)错误响应-

{
   "client_id":"my-id",
   "detail":"When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal.",
   "registration_url":"https://developer.twitter.com/en/docs/projects/overview",
   "title":"Client Forbidden",
   "required_enrollment":"Appropriate Level of API Access",
   "reason":"client-not-enrolled",
   "type":"https://api.twitter.com/2/problems/client-forbidden"
}


我已经确保我的应用程序位于一个与V2 ACCESS标记关联的项目中。
我也尝试使用Tweepy,但遇到了相同的错误响应。
同样在阅读Twitter docs中的特定页面时,快速入门指南和API资源管理器按钮都会导致断开链接!

rnmwe5a2

rnmwe5a21#

2023年4月18日,我回答了另一个关于获得Twitter followers using tweepy的问题。

下面的代码来自我对另一个问题的回答。

对于API v1.1:

import tweepy
import requests

auth = tweepy.OAuth1UserHandler(
        consumer_key, consumer_secret,
        access_token, access_token_secret
)

api = tweepy.API(auth, wait_on_rate_limit=True)

user = api.get_user(screen_name="target_user_screen_name")
followers_count = user.followers_count
try:
    for query_response in tweepy.Cursor(api.get_followers,
                                user_id = user.id,
                                screen_name = user.screen_name,
                                count = 200).items(followers_count):
        print(query_response.screen_name)
        print(query_response.id)

except requests.exceptions.ReadTimeout:
   pass
except requests.exceptions.Timeout:
   pass
except tweepy.errors.TweepyException as e:
    pass

字符串
对于API v2.0:

import tweepy

def create_session(token):
    tweepy_client = tweepy.Client(bearer_token=token, wait_on_rate_limit=True)
    return tweepy_client

def query_user_followers(user_id, next_token, tweepy_client):
    if len(next_token) == 0:
        query_response = tweepy_client.get_users_followers(id=user_id,
                                                           max_results=1,
                                                           user_fields=['id', 'name', 'username'],
                                                           pagination_token = None)
        return query_response
    elif len(next_token) > 0:
        query_response = tweepy_client.get_users_followers(id=user_id,
                                                           max_results=1,
                                                           user_fields=['id', 'name', 'username'],
                                                           pagination_token = next_token)
        return query_response

tweepy_data = []
tweepy_session = create_session(bearer_token)
initial_query = query_user_followers('target_user_id', '', tweepy_session)
tweepy_data.append(initial_query)
next_token = initial_query.meta['next_token']
while True:
    try:
        next_query = query_user_followers('target_user_id', next_token, tweepy_session)
        tweepy_data.append(next_query)
        next_token = next_query.meta['next_token']
    except requests.exceptions.ReadTimeout:
        continue
    except requests.exceptions.Timeout:
        continue
    except tweepy.errors.TweepyException as e:
        continue


旁注:tweepypytwitter中的速率限制反馈几乎不存在。因此,当您达到速率限制时,您的代码将不会提供任何反馈。我打开了一个pull request来在pytwitter中纠正这个问题。

相关问题