来自 Twitter 广告的活动成本(总支出)API

Campaign cost (total spend) from Twitter Ads API

我正在尝试从 API 中提取广告系列 costs/total 的支出 我是 API 的 100% 新手,我无法破解它

我想: 1- 获取每个广告系列的费用 2- 获取在 GUI 上显示的活动 ID,而不仅仅是那种奇怪的代码,即 8cdfn vs 1448530943

这是我目前的 python 代码

    from twitter_ads.client import Client
    from twitter_ads.cursor import Cursor
    from twitter_ads.http import Request
    from twitter_ads.error import Error
    import time
    from twitter_ads.campaign import LineItem
    from twitter_ads.enum import METRIC_GROUP
    from twitter_ads.enum import GRANULARITY
    client = Client(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
    account = client.accounts(ACCOUNT_ID)
    cids = map(lambda x: x.id, account.campaigns())
    resource = ‘/2/stats/accounts/{account_id}/’.format(account_id=account.id)
    params = { ‘entity’:‘CAMPAIGN’,
    ‘entity_ids’:cids,
    ‘start_time’: ‘2017-12-10’,
    ‘end_time’:‘2017-12-16’,
    ‘granularity’:‘TOTAL’,
    ‘metric_groups’: ‘BILLING’,
    ‘placement’: ‘PUBLISHER_NETWORK’}

    try, build and execute the request with error handling
    try:
    response = Request(client, ‘get’, resource, params=params).perform()
    print(response.body[‘data’])
    except Error as e:
    # see twitter_ads.error for more details
    print e.details
    raise

这是对我有用的解决方案 诀窍是传递多个展示位置在 API

中不起作用
from datetime import date,timedelta
import datetime
import logging
import sys
import os
import gzip
import shutil
import csv
import requests
import json
from twitter_ads.client import Client
from twitter_ads.cursor import Cursor
from twitter_ads.http import Request
from twitter_ads.error import Error
from twitter_ads.client import Client
from twitter_ads.campaign import LineItem
from twitter_ads.enum import METRIC_GROUP
from twitter_ads.enum import GRANULARITY
import twitter_ads
import time
client = Client(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)



# load the advertiser account instance
  account = client.accounts(ACCOUNT_ID)
  cids = list(map(lambda x: x.id.encode('utf-8'), account.campaigns()))
  campaigns = list(map(lambda x: [x.id.encode('utf-8'),x.name.encode('utf-8'), int(x.id,36)] , account.campaigns()))
  resource = '/2/stats/accounts/{account_id}/'.format(account_id=account.id)
  spend=[]
  for c in campaigns:
    for p in ['ALL_ON_TWITTER', 'PUBLISHER_NETWORK']:
      params = { 'entity':'CAMPAIGN',
  'entity_ids':c[0], #cids,
  'start_time': target_date,
  'end_time':target_date+timedelta(1),
  'granularity':'DAY',
  'metric_groups': ['BILLING','ENGAGEMENT'],
         'placement': p
           }

# try, build and execute the request with error handling
      try:
        req =Request(client, 'get', resource, params=params)
        response = req.perform()
        val = response.body['data']
        val.append(p)
        val.append(c[0])
        val.append(c[1])
        val.append(c[2])
        spend.append(val)
      except Error as e:
        # see twitter_ads.error for more details
        print e.details
        raise
  ddd= json.loads(json.dumps(spend))
  with open(target_path+row['account_id']+'_campaign_spend.csv', "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerow(['time_id','campaign_id_36', 'campaign_id','campaign_desc','placement','spend_micro', 'account_id'])
    for val in ddd:
        if (val[0]["id_data"][0]["metrics"]['billed_charge_local_micro'] and val[0]["id_data"][0]["metrics"]['billed_charge_local_micro'][0]):
          writer.writerow([str(target_date).replace("/","-"),val[2],val[4],val[3],val[1], val[0]["id_data"][0]["metrics"]['billed_charge_local_micro'][0], ACCOUNT_ID])

我使用了你最初写的大部分内容来满足我自己最近的需求。这是我想出的:

from twitter_ads.client import Client
from twitter_ads.enum import ENTITY, GRANULARITY, METRIC_GROUP, PLACEMENT
from twitter_ads.http import Request
from twitter_ads.error import Error
from datetime import date, timedelta


CONSUMER_KEY = "CONSUMER_KEY"
CONSUMER_SECRET = "CONSUMER_SECRET"
ACCESS_TOKEN = "ACCESS_TOKEN"
ACCESS_TOKEN_SECRET = "ACCESS_TOKEN_SECRET"
ACCOUNT_ID = "ACCOUNT_ID"

client = Client(consumer_key=CONSUMER_KEY,
                consumer_secret=CONSUMER_SECRET,
                access_token=ACCESS_TOKEN,
                access_token_secret=ACCESS_TOKEN_SECRET)

# For yesterday's total spend - for other date ranges you'll naturally need to
# update these two variables
time_offset = "T00:00:00-04:00"
yesterday = (date.today() - timedelta(1)).strftime("%Y-%m-%d") + time_offset
today = str(date.today()) + time_offset

# Could be done in a campaign loop as well ...
# account = client.accounts(id=ACCOUNT_ID)
# for camp in account.campaigns():
    # print(str(camp.id) + ": " + camp.name)

resource = f"/7/stats/accounts/{ACCOUNT_ID}/"

params = {
  "entity": ENTITY.CAMPAIGN,
  "entity_ids": "CAMPAIGN ID HERE",
  "start_time": yesterday,
  "end_time": today,
  "granularity": GRANULARITY.TOTAL,
  "metric_groups": METRIC_GROUP.BILLING,
  "placement": PLACEMENT.ALL_ON_TWITTER
}

try:
    req = Request(client=client,
                  method="GET",
                  resource=resource,
                  params=params)

    response = req.perform()

    # Total spend in "micros"; for USD, .50 is represented as 37500000
    spend_in_micros = response.body["data"][0]["id_data"][0]["metrics"]["billed_charge_local_micro"][0]

    spend = round((spend_in_micros / 1000000), 2)

    print(spend)

except Error as e:
    print(e.details)
    raise

免责声明:我是 pywindsorai 的贡献者。

假设您只需要点击(或支出)数据,您也可以使用 windsor.ai 来完成此操作,这样使用起来更简单一些。您只需将您的 Twitter 帐户连接到 windsor.ai,然后使用他们的 Python SDK (pywindsorai) 将数据加载到 pandas.

import pandas as pd
 
from pywindsorai.client import Client
from pywindsorai.enums import LAST_7D
from pywindsorai.enums import FIELD_SOURCE, FIELD_CAMPAIGN, FIELD_CLICKS
 
api_key = 'xxx'  # Get this from your windsor.ai account
 
client = Client(api_key)
campaign_clicks = client.connectors(date_preset=LAST_7D, fields=[FIELD_SOURCE, FIELD_CAMPAIGN, FIELD_CLICKS])

df = pd.DataFrame(campaign_clicks['data'])

我想做同样的事情,但我做不到。 我遵循了所有提出的解决方案,但收到的答复如下: ` req =Request(Client, 'get', resource, params=params)

 response =req.perform() 
 val = response.body['data']
 val.append(p)  
 val.append(c[0])`