如何在 Tweepy 中使用 3-legged OAuth 和 Twitter API v2 来读取受保护的推文?

发布于 2025-01-11 07:33:55 字数 2888 浏览 0 评论 0原文

我正在尝试使用 Tweepy 和 Twitter API v2 从 Twitter 句柄访问受保护的推文。为此,我知道我必须使用 3 足 OAuth。我已经完成并成功生成了访问令牌和访问令牌密钥。但是,使用这些访问密钥,当我使用同一帐户授权时,我无法看到自己受保护帐户的受保护推文。

有谁知道我在这里做错了什么?

这是一个具有授权功能的login.py文件

#!/usr/bin/env python
import tweepy 


def authrize():

    CONSUMER_KEY = "XXXXXXXXXXXxx"

    CONSUMER_SECRET = "XXXXXXXXXXXXXXXXx"

    BEARER_TOKEN = "XXXXXXXXXXXXXXXX"

    auth = tweepy.OAuth1UserHandler(CONSUMER_KEY, CONSUMER_SECRET,callback="oob")

    print(auth.get_authorization_url())

    verifier = input("Input PIN: ")
    ACCESS_TOKEN, ACCESS_TOKEN_SECRET = auth.get_access_token(verifier)

    print(ACCESS_TOKEN,"******",ACCESS_TOKEN_SECRET)
    return (CONSUMER_KEY,CONSUMER_SECRET,BEARER_TOKEN,ACCESS_TOKEN,ACCESS_TOKEN_SECRET)

,我的tweepy代码app.py如下

import tweepy
import login

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


def get_user_id(username):
    user = client.get_user(username=username)
    return user.data.id
    


def pagination(user_id):
    responses = tweepy.Paginator(client.get_users_tweets, user_id,
                                 exclude='replies,retweets',
                                 max_results=100,
                                 expansions='referenced_tweets.id',
                                 tweet_fields=['created_at', 'public_metrics', 'entities'])
    return responses

def get_original_tweets(user_id):
    tweet_list = []
    responses = pagination(user_id)
    for response in responses:
        if response.data ==None:
            continue
        else:
            for tweets in response.data:
                tweet_list.append([tweets.text,
                                tweets['public_metrics']['like_count'],
                                tweets['public_metrics']['retweet_count'],
                                tweets['created_at'].date()])

    return tweet_list


def user_details(username):
    user = {}
    user_response = client.get_user(username=username, user_fields=['public_metrics', 'description', 'url'])
    user_metrics = user_response.data['public_metrics']
    user['description'] = user_response.data['description']
    user['followers'] = user_metrics['followers_count']
    user['following'] = user_metrics['following_count']
    return user

keys = login.authrize()
client = get_client(*keys)
username = input("Username:")
userid = get_user_id(username)
print(user_details(username))
print(get_original_tweets(userid))

I am trying to access protected Tweets from Twitter handles using Tweepy and Twitter API v2. To do this I know I have to use 3-legged OAuth. I have done it and successfully generated an access token and access token secret. But with those access keys I am not able to see the protected Tweets of my own protected account when I am authorizing with the same account.

Does anyone know what I am doing wrong here?

This is a login.py file with the authorization function

#!/usr/bin/env python
import tweepy 


def authrize():

    CONSUMER_KEY = "XXXXXXXXXXXxx"

    CONSUMER_SECRET = "XXXXXXXXXXXXXXXXx"

    BEARER_TOKEN = "XXXXXXXXXXXXXXXX"

    auth = tweepy.OAuth1UserHandler(CONSUMER_KEY, CONSUMER_SECRET,callback="oob")

    print(auth.get_authorization_url())

    verifier = input("Input PIN: ")
    ACCESS_TOKEN, ACCESS_TOKEN_SECRET = auth.get_access_token(verifier)

    print(ACCESS_TOKEN,"******",ACCESS_TOKEN_SECRET)
    return (CONSUMER_KEY,CONSUMER_SECRET,BEARER_TOKEN,ACCESS_TOKEN,ACCESS_TOKEN_SECRET)

and my tweepy code app.py is as follows

import tweepy
import login

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


def get_user_id(username):
    user = client.get_user(username=username)
    return user.data.id
    


def pagination(user_id):
    responses = tweepy.Paginator(client.get_users_tweets, user_id,
                                 exclude='replies,retweets',
                                 max_results=100,
                                 expansions='referenced_tweets.id',
                                 tweet_fields=['created_at', 'public_metrics', 'entities'])
    return responses

def get_original_tweets(user_id):
    tweet_list = []
    responses = pagination(user_id)
    for response in responses:
        if response.data ==None:
            continue
        else:
            for tweets in response.data:
                tweet_list.append([tweets.text,
                                tweets['public_metrics']['like_count'],
                                tweets['public_metrics']['retweet_count'],
                                tweets['created_at'].date()])

    return tweet_list


def user_details(username):
    user = {}
    user_response = client.get_user(username=username, user_fields=['public_metrics', 'description', 'url'])
    user_metrics = user_response.data['public_metrics']
    user['description'] = user_response.data['description']
    user['followers'] = user_metrics['followers_count']
    user['following'] = user_metrics['following_count']
    return user

keys = login.authrize()
client = get_client(*keys)
username = input("Username:")
userid = get_user_id(username)
print(user_details(username))
print(get_original_tweets(userid))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风柔一江水 2025-01-18 07:33:55

默认情况下,Client.get_users_tweets 使用您的不记名令牌而不是 OAuth 1.0a 用户上下文进行身份验证。您需要将 user_auth 参数设置为 True

By default, Client.get_users_tweets uses your bearer token rather than OAuth 1.0a User Context to authenticate. You need to set the user_auth parameter to True.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文