[英]with the Twitter API - how can I get authentication for the engagement endpoint using a bearer token
我正在嘗試獲取我公司推文的參與度數據,以用於營銷儀表板。 我可以通過 Tweepy 進行身份驗證以獲取基本的 Twitter 提要數據,但參與端點給我帶來了麻煩。 我是否有可能通過使用 Tweepy 進行身份驗證然后使用不記名令牌來搞砸事情?
import tweepy
import requests
import json
import base64
import urllib.parse
consumer_key = <>
consumer_secret = <>
access_token = <>
access_token_secret = <>
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
print(api.me().name)
def get_tweet_ids():
scandy_tweets = api.user_timeline('TwitterHandle', count=5)
tweet_id_list = []
for twit in scandy_tweets:
json_str = json.loads(json.dumps(twit._json))
tweet_id_list.append(json_str['id'])
return tweet_id_list
def get_bearer_token():
uri_token_endpoint = 'https://api.twitter.com/oauth2/token'
key_secret = f"{consumer_key}:{consumer_secret}".encode('ascii')
b64_encoded_key = base64.b64encode(key_secret)
b64_encoded_key = b64_encoded_key.decode('ascii')
auth_headers = {
'Authorization': 'Basic {}'.format(b64_encoded_key),
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
auth_data = {
'grant_type': 'client_credentials'
}
auth_resp = requests.post(uri_token_endpoint, headers=auth_headers, data=auth_data)
print(auth_resp.status_code)
bearer_token = auth_resp.json()['access_token']
return bearer_token
bearer_token = get_bearer_token()
bearer_header = {
'Accept-Encoding': 'gzip',
'Authorization': 'Bearer {}'.format(bearer_token),
'oauth_consumer_key': consumer_key
}
recent_tweets = get_tweet_ids()
engage_data = {
'tweet_id_list': recent_tweets,
'engagement_types': ['impressions', 'engagements', 'favorites'],
'groupings': {'grouping name': {'group_by': ['tweet.id', 'engagement.type']}}
}
uri_28hr_endpoint = 'https://data-api.twitter.com/insights/engagement/28hr'
engagement_resp = requests.post(uri_28hr_endpoint, headers=bearer_header, data=engage_data)
print(engagement_resp.status_code)
print(engagement_resp.json())
當我調用print(engagement_resp.json())
時,我得到以下 output:
403 {'errors': ['您的應用程序 ID 未被授權。']}
答案在 Andy Piper 的評論中。 在Twitter 的開發者網站上這個頁面的頂部,它說:
這是僅在我們的托管訪問級別內可用的企業 API。 要使用此 API,您必須先在我們的企業銷售團隊中設置一個帳戶
在描述 API 訪問的不同級別的此頁面上,您可以找到標准(免費)、高級和企業 API 層中的可能性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.