使用Twitter API,如何使用令牌获取对参与端点的身份验证。

6
我正在为公司的营销仪表盘获取推特的互动数据。我已经通过 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())时,我会得到以下输出:

403 {'errors': ['Your Application ID is not authorized.']}


1
相关链接:https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/ - Laurent LAPORTE
1
你有访问Engagement API的权限吗?这是一组商业功能。 - Andy Piper
我使用Twitter应用程序获取了密钥、令牌和密码。还有其他步骤吗? - Charles Carriere
1个回答

3
安迪·派珀(Andy Piper)在评论中提供了答案。在Twitter开发者网站的这个页面的顶部,写着:

这是仅在我们管理的访问级别中提供的企业API。要使用此API,您必须先与我们的企业销售团队建立账户。

描述不同API访问级别的这个页面上,您可以了解标准(免费)、高级和企业API层中可能实现的功能。

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