将CURL转换为Python-对于Twitter API

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

我希望通过Python'requests'获取Twitter参与度指标(展示次数,收藏夹等)。我可以通过下面的代码获得授权:

client_key = '*{Client Key}*'
client_secret = '*{Client Secret}*' 

import base64

key_secret = '{}:{}'.format(client_key,client_secret).encode('ascii')
b64_encoded_key = base64.b64encode(key_secret)
b64_encoded_key = b64_encoded_key.decode('ascii')

import requests

base_url = 'https://api.twitter.com/'
auth_url = '{}oauth2/token'.format(base_url)

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(auth_url, headers = auth_headers, data=auth_data)

但是,我不知道如何将下面的CURL转换为Python代码:

curl --request POST 
  --url https://data-api.twitter.com/insights/engagement/totals 
  --header 'accept-encoding: gzip' 
  --header 'authorization: Bearer ' 
  --header 'content-type: application/json' 
  --data '{
                "tweet_ids": [
                    "1070059276213702656","1021817816134156288","1067094924124872705"
                ],
                "engagement_types": [
                    "favorites","retweets","replies","video_views"
                ],
                "groupings": {
                    "perTweetMetricsUnowned": {
                        "group_by": [
                            "tweet.id",
                            "engagement.type"
                        ]
                    }
                }
            } 
  --verbose 
  --compressed

Twitter API参考:https://developer.twitter.com/en/docs/metrics/get-tweet-engagement/api-reference/post-insights-engagement#Historical

有人有解决方案吗?提前致谢!

大多数人会使用Tweepy来传输Twitter数据。但是,我一直想在整个时间内观察Tweet的传递,因此我必须使用Tweepy没有涵盖的'https://data-api.twitter.com/insights/engagement/'端点。

python api twitter
1个回答
0
投票

应该只能够创建数据和标题字典并发布:

headers = {
    'accept-encoding': 'gzip',
    'authorization': 'Bearer',
    'content-type': 'application/json',
}
data = {
    "tweet_ids": [
        "1070059276213702656","1021817816134156288","1067094924124872705"
    ],
    "engagement_types": [
        "favorites","retweets","replies","video_views"
    ],
    "groupings": {
        "perTweetMetricsUnowned": {
            "group_by": [
                "tweet.id",
                "engagement.type"
            ]
        }
    }
}
req = requests.post(
    "https://data-api.twitter.com/insights/engagement/totals",
    headers=headers,
    data=data
)
© www.soinside.com 2019 - 2024. All rights reserved.