简体   繁体   English

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

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

When I signed up for the Twitter API for research , they gave me 3 keys: API Key, API Secret Key, and Bearer Token. When I signed up for the Twitter API for research , they gave me 3 keys: API Key, API Secret Key, and Bearer Token. However the Hello Tweepy example, 4 keys are used: consumer_key, consumer_secret, access_token, access_token_secret.然而,Hello Tweepy 示例使用了 4 个密钥:consumer_key、consumer_secret、access_token、access_token_secret。 Obviously, the first two keys map to each other, but I don't see how consumer_secret and access_token map to Bearer Token.很明显,前两个key map 是相互关联的,但是我看不到consumer_secret 和access_token map 是如何得到Bearer Token 的。 I am using this:我正在使用这个:

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)

Where should I use the Bearer token?我应该在哪里使用 Bearer 令牌? Thanks谢谢

Unfortunately at this time, you will not be able to use Tweepy for accessing the new full archive search endpoint for academic research.不幸的是,此时您将无法使用 Tweepy 访问新的完整档案搜索端点以进行学术研究。 They are working on v2 support, but right now, you'd end up hitting the v1.1 standard search API.他们正在研究 v2 支持,但现在,您最终会遇到 v1.1 标准搜索 API。

If you are using Python I would suggest taking a look at the Twitter API v2 sample code , or the search_tweets client that Twitter provides. If you are using Python I would suggest taking a look at the Twitter API v2 sample code , or the search_tweets client that Twitter provides. You can then use the BEARER TOKEN by adding it as an environment variable, or if you prefer by adding it directly into the code, but if you do that, be careful not to accidentally commit it to source control where others might get access to it.然后,您可以通过将 BEARER TOKEN 添加为环境变量来使用它,或者如果您更喜欢将其直接添加到代码中,但如果您这样做,请注意不要意外将其提交给其他人可能会访问它的源代码控制.

To answer the piece about the consumer key/secret vs access token/secret vs bearer token:要回答有关消费者密钥/秘密与访问令牌/秘密与不记名令牌的文章:

  • the bearer token is granted based on the consumer key and secret, and represents just the application identity and credential不记名令牌是根据消费者密钥和秘密授予的,仅代表应用程序身份和凭证
  • the access token and secret represent the user identity.访问令牌和秘密代表用户身份。 If you are using those, you don't use the bearer token, you use that pair in combination with consumer key and secret instead.如果您使用这些,则不使用不记名令牌,而是将该对与消费者密钥和秘密结合使用。

In Tweepy terms, the Bearer token would be retrieved by the AppAuthHandler automatically, and the OAuthHandler would not be used in that case.在 Tweepy 术语中,Bearer 令牌将由AppAuthHandler自动检索,并且在这种情况下不会使用OAuthHandler

You don't need to use bearer key.您不需要使用不记名密钥。 You can find the access keys & secrets that you can use under the bearer key in the section where you get your passwords by logging into your Twitter Developer account.您可以通过登录 Twitter 开发人员帐户在获取密码的部分中的不记名密钥下找到可以使用的访问密钥和机密。

I believe the confusion lies in the different terminologies for the variables and the use of these variables.我认为混淆在于变量的不同术语和这些变量的使用。

First explained below, terminology clarification, with different terms referring to the same thing:下面首先解释,术语澄清,不同的术语指的是同一件事:

Client credentials:客户端凭据:

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
 

Temporary credentials:临时证件:

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

Token credentials:令牌凭据:

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

Next, the use of these.接下来,使用这些。 Note that bearer Token authenticates requests on behalf of your developer App.请注意,不记名令牌代表您的开发者应用程序对请求进行身份验证。 As this method is specific to the App, it does not involve any users.由于此方法是 App 特有的,不涉及任何用户。 Thus you can either go with requests on a user level or at an app level as follows:因此,您可以在用户级别或应用级别请求 go,如下所示:

User level (OAuth 1.0a):用户级别(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)  

App level (OAuth 2.0):应用级别(OAuth 2.0):

Bearer token: "ABDsdfj56nhiugd5tkggred"

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 [1] https://developer.twitter.com/en/docs/authentication/oauth-1-0a/obtaining-user-access-tokens

[2] https://docs.tweepy.org/en/latest/auth_tutorial.html [2] https://docs.tweepy.org/en/latest/auth_tutorial.html

@ScriptCode @脚本代码

but it is still unclear where to use the Bearer Token in tweepy's OAuthHandler and access_token?但目前还不清楚tweepy的OAuthHandler和access_token中的Bearer Token在哪里使用?

The Documentation for tweepy 3.10.0 at https://buildmedia.readthedocs.org/media/pdf/tweepy/latest/tweepy.pdf states under 3.3 OAuth 2 Authentication (using Bearer Token) The Documentation for tweepy 3.10.0 at https://buildmedia.readthedocs.org/media/pdf/tweepy/latest/tweepy.pdf states under 3.3 OAuth 2 Authentication (using Bearer Token)

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

so you use AppAuthHandler and basically leave out the step:所以你使用 AppAuthHandler 并且基本上省略了这一步:

auth.set_access_token(key, secret)

Of course you have to make sure you have registered a Bearer Token for a read-only App in the Twitter Dev Backend.当然,您必须确保您已在 Twitter 开发后端中为只读应用程序注册了 Bearer Token。

I tried it and it worked...我试过了,它奏效了......

From Tweepy documentation ( OAuth 2 Authentication )来自 Tweepy 文档( OAuth 2 身份验证

Tweepy also supports OAuth 2 authentication. Tweepy 还支持 OAuth 2 身份验证。 OAuth 2 is a method of authentication where an application makes API requests without the user context. OAuth 2 是一种身份验证方法,其中应用程序在没有用户上下文的情况下发出 API 请求。 Use this method if you just need read-only access to public information.如果您只需要对公共信息进行只读访问,请使用此方法。

So basically, since your app just requires read-only access, you don't need "Access Token" & "Access token secret" and can ignore the 3rd & 4th Steps.所以基本上,由于您的应用程序只需要只读访问权限,因此您不需要“访问令牌”和“访问令牌秘密”并且可以忽略第 3 和第 4 步。 A simple code for this solution would be as follow:此解决方案的简单代码如下:

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 has been updated to 4.4.0 which supports Twitter API v2. Tweepy 已更新至 4.4.0,支持 Twitter API v2。 Here is a sample code given you have Academic Research Account [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("================")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM