使用Twitter API-如何使用承载令牌获得参与性终结点的身份验证

问题描述 投票:5回答:1

我正在尝试获取有关公司用于市场营销仪表板的推文的参与度数据。我可以通过Tweepy进行身份验证,以获取基本的Twitter feed数据,但是参与端点给我带来了麻烦。我是否有可能先通过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())时,将得到以下输出:

403 {'错误':['您的应用程序ID未经授权。']}

python api authentication twitter
1个回答
0
投票

答案在安迪·派珀(Andy Piper)的评论中。在this page on Twitter's Developer site的顶部说:

这是企业API,仅在我们的托管访问级别内可用。要使用此API,您必须先在我们的企业销售团队中建立一个帐户]

this page that describes the different levels of API access上,您可以找到标准(免费),高级和企业API层中的功能。

© www.soinside.com 2019 - 2024. All rights reserved.