如何在 python 中使用 tweepy 访问带有不记名令牌的推文?

How to acess tweets with bearer token using tweepy, in python?

当我注册 Twitter API 进行研究 时,他们给了我 3 个密钥:API 密钥,API 密钥和不记名令牌。但是,Hello Tweepy 示例使用了 4 个密钥:consumer_key、consumer_secret、access_token、access_token_secret。显然,前两个键相互映射,但我看不到 consumer_secret 和 access_token 如何映射到 Bearer Token。我正在使用这个:

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 令牌? 谢谢

很遗憾,此时您将无法使用 Tweepy 访问用于学术研究的新的完整档案搜索端点。他们正在努力支持 v2,但现在,您最终会遇到 v1.1 标准搜索 API。

如果您正在使用 Python,我建议您查看 Twitter 提供的 Twitter API v2 sample code, or the search_tweets client。然后,您可以通过将 BEARER TOKEN 添加为环境变量来使用它,或者如果您愿意,可以将其直接添加到代码中,但如果这样做,请注意不要意外地将其提交到其他人可能访问它的源代码管理中.

回答关于消费者 key/secret 与访问 token/secret 与不记名令牌的文章:

  • 不记名令牌是根据消费者密钥和秘密授予的,仅代表应用程序身份和凭证
  • 访问令牌和密码代表用户身份。如果您正在使用这些,则不使用不记名令牌,而是将该对与消费者密钥和秘密结合使用。

在 Tweepy 术语中,Bearer 令牌将由 AppAuthHandler 自动检索,并且在这种情况下不会使用 OAuthHandler

您不需要使用不记名密钥。您可以在通过登录 Twitter 开发者帐户获取密码的部分中的不记名密钥下找到可以使用的访问密钥和机密。

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

术语

下面先解释一下,名词解释,不同名词指的是同一个东西:

客户端凭据:

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

接下来,使用这些。请注意,承载令牌代表您的开发人员应用程序对请求进行身份验证。由于该方法是App特定的,不涉及任何用户。 因此,您可以按照以下方式处理用户级别或应用级别的请求:

用户级别(OAuth 1.0a):

API key:"hgrthgy2374RTYFTY"
API key secret:"hGDR2Gyr6534tjkht"
Access token:"HYTHTYH65TYhtfhfgkt34"
Access token secret: "ged5654tHFG"

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(key, secret)
api = tweepy.API(auth)  

应用级别 (OAuth 2.0):

Bearer token: "ABDsdfj56nhiugd5tkggred"
auth = tweepy.Client("Bearer Token here")
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

@ScriptCode

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

https://buildmedia.readthedocs.org/media/pdf/tweepy/latest/tweepy.pdf 的 tweepy 3.10.0 文档说明 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 Backend 中为只读应用程序注册了 Bearer Token。

我试过了,成功了...

来自 Tweepy 文档 (OAuth 2 Authentication)

Tweepy also supports OAuth 2 authentication. OAuth 2 is a method of authentication where an application makes API requests without the user context. Use this method if you just need read-only access to public information.

所以基本上,由于您的应用只需要只读访问权限,因此您不需要“访问令牌”和“访问令牌机密”,并且可以忽略第 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)

Tweepy 已更新至 4.4.0,支持 Twitter API v2。如果您有学术研究帐户 [more examples]:

,这是一个示例代码
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("================")