Hussein Negm
Hussein Negm

Reputation: 601

Campaign cost (total spend) from Twitter Ads API

I am trying to pull campaign costs/total spend from the API I am 100% new to the API and I am not able to crack it through

I want to : 1- get cost per campaign 2- get campaign ids that showup on the GUI not just the kind of weird codes ie 8cdfn vs 1448530943

here is my python code so far

    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

Upvotes: 1

Views: 2573

Answers (4)

Im triying to get the same but I cant make it. I follow all the solution proposed but I received an answer which is the following: ` req =Request(Client, 'get', resource, params=params)

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

Upvotes: 0

chaitan94
chaitan94

Reputation: 2232

Disclaimer: I was a contributor to pywindsorai.

Assuming you just need the clicks (or spend) data, you can do this using windsor.ai as well, which is a bit simpler to use. You just have to connect your Twitter account to windsor.ai, and then use their Python SDK (pywindsorai) to load the data into 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'])

Upvotes: 0

mykisscool
mykisscool

Reputation: 872

I used much of what you initially wrote for a recent requirement of my own. This is what I came up with:

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, $37.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

Upvotes: 0

Hussein Negm
Hussein Negm

Reputation: 601

Here is the solution that worked for me the trick is that passing multiple placements doesn't work in the 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])

Upvotes: 0

Related Questions