如何使用Tweepy和Bearer令牌访问推特?

20

当我注册Twitter的研究API时,他们给了我三个密钥:API密钥,API密钥密码和Bearer令牌。然而,在Hello Tweepy示例中,使用了四个密钥:consumer_key、consumer_secret、access_token和access_token_secret。显然,前两个密钥互相对应,但我不知道consumer_secret和access_token如何对应Bearer令牌。我正在使用以下内容:

CONSUMER_KEY = 'a'
CONSUMER_SECRET = 'b'
ACCESS_TOKEN = 'c'
ACCESS_TOKEN_SECRET = 'd'
BEARER_TOKEN='e'


# Set Connection
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True)

Bearer token 应该在哪里使用?谢谢。

6个回答

15

我认为混淆在于变量的不同术语以及这些变量的使用。

术语

首先,下面解释术语澄清,不同术语指的是同一事物:

客户端凭据:

1. App Key === API Key === Consumer API Key === Consumer Key === Customer Key === oauth_consumer_key
2. App Key Secret === API Secret Key === Consumer Secret === Consumer Key === Customer Key === oauth_consumer_secret
3. Callback URL === oauth_callback
 

临时凭证:

1. Request Token === oauth_token
2. Request Token Secret === oauth_token_secret
3. oauth_verifier
 

令牌凭证:

1. Access token === Token === resulting oauth_token
2. Access token secret === Token Secret === resulting oauth_token_secret

接下来,使用这些内容。请注意,持有者令牌在您的开发者应用程序代表请求进行身份验证。由于此方法特定于应用程序,因此不涉及任何用户。 因此,您可以按以下方式选择在用户级别或应用程序级别进行请求:

用法

用户级别(OAuth 1.0a):

api_key = "hgrthgy2374RTYFTY"  # CONSUMER_KEY
api_secret_key = "hGDR2Gyr6534tjkht"  # CONSUMER_SECRET
access_token = "HYTHTYH65TYhtfhfgkt34"  # ACCESS_TOKEN
access_token_secret = "ged5654tHFG"  # ACCESS_TOKEN_SECRET

auth = tweepy.OAuthHandler(api_key, api_secret_key)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)  

应用程序级别(OAuth 2.0):

bearer_token = "ABDsdfj56nhiugd5tkggred"  # BEARER_TOKEN
auth = tweepy.Client(bearer_token)
api = tweepy.API(auth)

或者,另一种选择是:
auth = tweepy.AppAuthHandler(consumer_key, consumer_secret)
api = tweepy.API(auth)

[1] https://developer.twitter.com/en/docs/authentication/oauth-1-0a/obtaining-user-access-tokens

[2] https://docs.tweepy.org/en/latest/authentication.html#twitter-api-v2


3
很遗憾,目前您将无法使用Tweepy来访问新的完整存档搜索端点进行学术研究。他们正在开发v2支持,但现在,您最终会使用v1.1标准搜索API。
如果您使用Python,我建议查看Twitter API v2示例代码或Twitter提供的search_tweets客户端。然后,您可以通过将其添加为环境变量来使用BEARER TOKEN,或者如果您愿意,直接将其添加到代码中,但如果这样做,请小心不要意外提交到源代码控制,以免其他人获取访问权限。
回答有关consumer key/secret与access token/secret与bearer token之间区别的部分:
  • bearer token是基于consumer key和secret授予的,仅表示应用程序的身份和凭据
  • access token和secret表示用户身份。如果您使用这些,您不会使用bearer token,而是与consumer key和secret一起使用该对。
在Tweepy术语中,Bearer令牌将由AppAuthHandler自动检索,并且在这种情况下不会使用OAuthHandler

这个在过去一个月里有没有改变的可能性?我刚刚获得了学术访问权限,需要完整的存档。之前只用过Tweepy,如果可以避免的话,我不想重写我的处理格式。 - Jibril
1
看起来他们刚刚添加了支持:https://dev.to/twitterdev/a-comprehensive-guide-for-using-the-twitter-api-v2-using-tweepy-in-python-15d9#:~:text=Tweepy%20是一个流行的包,用于使用 Twitter API v2 进行开发。它支持各种功能,从简单的推文获取到学术研究产品跟踪。 - joeyagreco

1

Tweepy已更新到4.4.0,支持Twitter API v2。以下是一个样例代码,假设您拥有学术研究账户[更多示例]

import tweepy

client = tweepy.Client(bearer_token="add_your_Bearer_Token")

# Replace with your own search query
#replace place_country with the code of your country of interest or remove.
query = 'COVID19 place_country:GB'

# Starting time period YYYY-MM-DDTHH:MM:SSZ (max period back is March 2006)
start_time = '2018-01-01T00:00:00Z'

# Ending time period YYYY-MM-DDTHH:MM:SSZ
end_time = '2018-08-03T00:00:00Z'

#I'm getting the geo location of the tweet as well as the location of the user and setting the number of tweets returned to 10 (minimum) - Max is 100

tweets = client.search_all_tweets(query=query, tweet_fields=['context_annotations', 'created_at', 'geo'], place_fields=['place_type', 'geo'], user_fields=['location'], expansions='author_id,geo.place_id', start_time=start_time, end_time=end_time, max_results=10)

# Get list of places and users
places = {p["id"]: p for p in tweets.includes['places']}
users = {u["id"]: u for u in tweets.includes['users']}

#loop through the tweets to get the tweet ID, Date, Text, Author ID, User Location and Tweet Location
for tweet in tweets.data:
    print(tweet.id)
    print(tweet.created_at)
    print(tweet.text)
    print(tweet.author_id)
    if users[tweet.author_id]:
        user = users[tweet.author_id]
        print(user.location) #note that users can add whatever they want as location
    if places[tweet.geo['place_id']]:
        place = places[tweet.geo['place_id']]
        print(place.full_name)
        print("================")

1

@ScriptCode

但是还不清楚在 tweepy 的 OAuthHandler 和 access_token 中何时使用 Bearer Token?

tweepy 3.10.0 文档https://buildmedia.readthedocs.org/media/pdf/tweepy/latest/tweepy.pdf 在 3.3 OAuth 2 认证 (使用 Bearer Token) 下说明。

auth = tweepy.AppAuthHandler(consumer_key, consumer_secret)
api = tweepy.API(auth)

所以你使用AppAuthHandler,基本上跳过了这一步骤:

auth.set_access_token(key, secret)

当然,您必须确保在Twitter Dev后端为只读应用程序注册了Bearer Token。
我尝试过并且成功了...

我已经尝试过了,它可以工作!你需要在 Twitter 开发者仪表板上注册一个只读权限的应用程序,网址为 https://developer.twitter.com/en/portal/dashboard,并创建一个 Bearer 令牌。然后使用上面发布的 AppAuthHandler,它就可以工作了! - Moses

1
你不需要使用承载密钥。在登录到 Twitter 开发者帐户后,在获取密码的部分中,您可以找到可以在承载密钥下使用的访问密钥和机密。

1
最好在可能的情况下始终共享答案中的屏幕截图。 - Anurag Sharma

0

来自Tweepy文档(OAuth 2认证

Tweepy还支持OAuth 2认证。 OAuth 2是一种身份验证方法,其中应用程序在没有用户上下文的情况下进行API请求。 如果您只需要对公共信息进行只读访问,请使用此方法。

因此,由于您的应用程序仅需要只读访问权限,因此您不需要“访问令牌”和“访问令牌密钥”,可以忽略第3和第4步。 此解决方案的简单代码如下:

auth = tweepy.AppAuthHandler(consumer_key, consumer_secret)
api = tweepy.API(auth)
for tweet in tweepy.Cursor(api.search, q='cool').items(3):
    print(tweet.text)

我在你的代码上遇到了这个错误:AttributeError: 'API' object has no attribute 'search' - Shayan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接