forked from narrowcast/facebook-ads-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
facebookadspy.py
874 lines (789 loc) · 34.8 KB
/
facebookadspy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
import codecs
import datetime
import hashlib
import hmac
import io
import json
import logging
import mimetypes
import sys
import urllib
import urllib2
import uuid
import requests as r
# <codecell>
FACEBOOK_API = 'https://graph.facebook.com'
logger = logging.getLogger(__name__)
# <codecell>
def dicts_to_namedrecords(dicts, class_name=None):
""" Takes list of dictionaries and converts to list of recordtype objects"""
from recordtype import recordtype
from random import randint
from sets import Set
all_keys = []
for dic in dicts:
all_keys += dic.keys()
unique_keys = list(Set(all_keys))
key_defaults = [(key, None) for key in unique_keys]
if not class_name:
class_name = 'FB_Record_Type_'
Record = recordtype(class_name + str(randint(1,9999999)), key_defaults)
data = [Record(**dic) for dic in dicts]
return data
class MultipartFormdataEncoder(object):
def __init__(self):
self.boundary = uuid.uuid4().hex
self.content_type = 'multipart/form-data; boundary={}'.format(
self.boundary)
@classmethod
def u(cls, s):
if sys.hexversion < 0x03000000 and isinstance(s, str):
s = s.decode('utf-8')
if sys.hexversion >= 0x03000000 and isinstance(s, bytes):
s = s.decode('utf-8')
return s
def iter(self, fields, files):
"""
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, file-like) elements for data
to be uploaded as files.
Yield body's chunk as bytes
"""
encoder = codecs.getencoder('utf-8')
for key, value in fields.iteritems():
key = self.u(key)
yield encoder('--{}\r\n'.format(self.boundary))
yield encoder(self.u(
'Content-Disposition: form-data; name="{}"\r\n').format(key))
yield encoder('\r\n')
if isinstance(value, int) or isinstance(value, float):
value = str(value)
yield encoder(self.u(value))
yield encoder('\r\n')
for key, value in files.iteritems():
key = self.u(key)
filename = self.u(value.name)
yield encoder('--{}\r\n'.format(self.boundary))
yield encoder(self.u('Content-Disposition: form-data; name="{}"; filename="{}"\r\n').format(key, filename))
yield encoder('Content-Type: {}\r\n'.format(mimetypes.guess_type(filename)[0] or 'application/octet-stream'))
yield encoder('\r\n')
buff = value.read()
yield (buff, len(buff))
yield encoder('\r\n')
yield encoder('--{}--\r\b'.format(self.boundary))
def encode(self, fields, files):
body = io.BytesIO()
for chunk, chunk_len in self.iter(fields, files):
body.write(chunk)
return self.content_type, body.getvalue()
# <codecell>
class AdsAPIError(Exception):
"""
Errors as defined in the Facebook documentation
https://developers.facebook.com/docs/reference/ads-api/error-reference/
"""
def __init__(self, error):
data = json.load(error)
self.error = data
self.message = data['error']['message']
self.code = data['error']['code']
self.type = data['error']['type']
# <codecell>
class AdsAPIResponse(object):
""" A response object to encapsulate successfull requests """
def __init__(self, resp, get_all=False):
if type(resp) == str or type(resp) == unicode:
resp = json.loads(resp)
self.__dict__.update(resp)
elif type(resp) == dict:
self.__dict__.update(resp)
else:
raise NotImplementedError(str(type(resp)) + " is not yet supported \
by Response class yet")
originals = {}
for key, value in resp.iteritems():
originals['_'+key] = value
self.__dict__.update(originals)
if "paging" in resp.keys():
self.paging = [self.paging] # hack to keep track of all the pages in paging
self._paging = [self._paging]
else:
self.paging = None
self._paging = None
# When we want to load everything in one go.
if get_all:
self.get_all()
def to_namedrecords(self):
"""
Converts reponse data into recordtype objects which can be easily
accessed using dot notation. Very handy for ipython workflows.
It fetches all the pages before proceeding.
"""
if self._paging and 'next' in self._paging[len(self._paging)-1].keys():
self.load_all()
if self.data:
class_name = 'FB_Record_Type_'
self.data = dicts_to_namedrecords(self._data, class_name)
if self.paging:
class_name = 'Page_Type_'
self.paging = dicts_to_namedrecords(self._paging, class_name)
def to_pandas(self):
"""
Converts response data into pandas dataframe very naively.
It fetches all the pages before proceeding.
"""
from pandas import DataFrame
if self._paging and 'next' in self._paging[len(self._paging)-1].keys():
self.load_all()
if self.data:
self.data = DataFrame(self._data)
if self.paging:
self.paging = DataFrame(self._paging)
def load_all(self):
"""
Get all the pages for the response. This cannot be done after values
have been converted to to_namedrecords
"""
if not self._paging:
return
while 'next' in self._paging[len(self._paging)-1].keys():
try:
temp = r.get(self._paging[len(self._paging)-1]['next']).json()
except r.ConnectionError as err:
print '%s' % err
print "Check your connection mate"
raise AdsAPIError
self._data += temp['data']
self._paging.append(temp['paging'])
self.data = self._data
self.paging = self._paging
# <codecell>
class AdsAPI(object):
"""A client for the Facebook Ads API."""
DATA_LIMIT = 10000
def __init__(self, access_token, app_id, app_secret):
self.access_token = access_token
self.app_id = app_id
self.app_secret = app_secret
h = hmac.new(access_token, app_secret, hashlib.sha256)
self.appsecret_proof = h.hexdigest()
def make_request(self, path, method, args={}, files={}, batch=False):
"""Makes a request against the Facebook Ads API endpoint."""
if batch:
# Then just return a dict for the batch request
return {
'method': method,
'relative_url': '%s?%s' % (path, urllib.urlencode(args))
}
logger.info('Making a %s request at %s with %s' % (method, path, args))
if 'access_token' not in args:
args['access_token'] = self.access_token
try:
if method == 'GET':
url = '%s/%s?%s' % (FACEBOOK_API, path, urllib.urlencode(args)) # this hack is needed because requests doesn't expect access_token kwarg for some reason
f = r.get(url).json()
elif method == 'POST':
url = '%s/%s' % (FACEBOOK_API, path)
if files:
encoder = MultipartFormdataEncoder()
content_type, body = encoder.encode(args, files)
req = urllib2.Request(url, data=body)
req.add_header('Content-Type', content_type)
f = urllib2.urlopen(req)
else:
f = urllib2.urlopen(url, urllib.urlencode(args))
elif method == 'DELETE':
url = '%s/%s?%s' % (FACEBOOK_API, path, urllib.urlencode(args))
f = r.delete(req).json()
else:
raise
return Response(f)
except urllib2.HTTPError as e:
print '%s' % e
raise AdsAPIError(e)
except urllib2.URLError as e:
print 'URLError: %s' % e.reason
def make_batch_request(self, batch):
"""Makes a batched request against the Facebook Ads API endpoint."""
args = {}
args['access_token'] = self.access_token
args['batch'] = json.dumps(batch)
logger.info('Making a batched request with %s' % args)
try:
f = urllib2.urlopen(FACEBOOK_API, urllib.urlencode(args))
data = json.load(f)
# For debugging
self.data = data
for idx, val in enumerate(data):
data[idx] = json.loads(val['body'])
return data
except urllib2.HTTPError as e:
print '%s' % e
return json.load(e)
except urllib2.URLError as e:
print 'URLError: %s' % e.reason
# New API
def make_labeled_batch_request(self, batch):
"""Makes a batched request with label against the Facebook Ads API endpoint."""
try:
labels = batch.keys()
queries = batch.values()
data = self.make_batch_request(queries)
# For debugging
self.data = data
return dict(zip(labels, data))
except urllib2.HTTPError as e:
print '%s' % e
return json.load(e)
except urllib2.URLError as e:
print 'URLError: %s' % e.reason
def debug_token(self, token):
"""Returns debug information about the given token."""
path = 'debug_token'
args = {
'input_token': token,
'access_token': '%s|%s' % (self.app_id, self.app_secret)
}
return self.make_request(path, 'GET', args)
def get_events_by_app(self, app_id, batch=False):
"""Returns the events associated with an app"""
path = "{}/app_event_types".format(app_id)
return self.make_request(path, 'GET', batch=batch)
def get_adusers(self, account_id, batch=False):
"""Returns the users of the given ad account."""
path = 'act_%s/users' % account_id
return self.make_request(path, 'GET', batch=batch)
def get_adaccount(self, account_id, fields=False, batch=False):
"""Returns the fields of the given ad account."""
path = 'act_%s' % account_id
args = {}
if fields:
args = {'fields': fields}
return self.make_request(path, 'GET', args, batch=batch)
def get_adaccounts(self, user_id, fields=False, batch=False):
"""Returns the list of Facebook ad accounts."""
path = '%s/adaccounts' % user_id
args = {}
if fields:
args = {'fields': fields}
return self.make_request(path, 'GET', args, batch=batch)
# New API
def get_adcampaign_group(self, campaign_group_id, fields=False, batch=False):
"""Return the fields for the given ad campaign group."""
path = '%s' % campaign_group_id
args = {}
if fields:
args = {'fields': fields}
return self.make_request(path, 'GET', args, batch=batch)
# New API
def get_adcampaign_groups(self, account_id, fields=False, batch=False):
"""Returns the fields of all ad campaign groups from the given ad account."""
path = 'act_%s/adcampaign_groups' % account_id
args = {}
if fields:
args['fields'] = fields
args['limit'] = self.DATA_LIMIT
return self.make_request(path, 'GET', args, batch=batch)
# New API
def delete_adcampaign_group(self, campaign_group_id, batch=False):
"""Delete specific campaign group."""
path = '%s' % campaign_group_id
return self.make_request(path, 'DELETE', batch=batch)
def get_adcampaign(self, campaign_id, fields=False, batch=False):
"""Returns the fields for the given ad campaign."""
path = '%s' % campaign_id
args = {}
if fields:
args = {'fields': fields}
return self.make_request(path, 'GET', args, batch=batch)
# New API
def get_adcampaigns_of_campaign_group(self, campaign_group_id, fields=False, batch=False):
"""Return the fields of all adcampaigns from the given adcampaign group."""
path = '%s/adcampaigns' % campaign_group_id
args = {}
if fields:
args = {'fields': fields}
return self.make_request(path, 'GET', args, batch=batch)
# New API
def get_adcampaigns_of_account(self, account_id, fields=False, batch=False):
"""Returns the fields of all ad sets from the given ad account."""
path = 'act_%s/adcampaigns' % account_id
args = {}
if fields:
args = {'fields': fields}
return self.make_request(path, 'GET', args, batch=batch)
def get_adcampaigns(self, account_id, fields=False, batch=False):
"""Returns the fields of all ad sets from the given ad account."""
return self.get_adcampaigns_of_account(account_id, fields=False, batch=batch)
def get_adgroup(self, adgroup_id, fields=False, batch=False):
"""Returns the fields for the given ad group."""
path = '%s' % adgroup_id
args = {}
if fields:
args = {'fields': fields}
return self.make_request(path, 'GET', args, batch=batch)
def get_adgroups_by_adaccount(self, account_id, batch=False):
"""Returns the fields of all ad groups from the given ad account."""
path = 'act_%s/adgroups' % account_id
return self.make_request(path, 'GET', batch=batch)
def get_adgroups_by_adcampaign(self, campaign_id, batch=False):
"""Returns the fields of all ad groups from the given ad campaign."""
path = '%s/adgroups' % campaign_id
return self.make_request(path, 'GET', batch=batch)
def get_adcreative(self, creative_id, fields=False, batch=False):
"""Returns the fields for the given ad creative."""
path = '%s' % creative_id
args = {}
if fields:
args = {'fields': fields}
return self.make_request(path, 'GET', args, batch=batch)
def get_adcreatives(self, account_id, fields=False, batch=False):
"""Returns the fields for the given ad creative."""
path = 'act_%s/adcreatives' % account_id
args = {}
if fields:
args = {'fields': fields}
return self.make_request(path, 'GET', args, batch=batch)
def get_adimages(self, account_id, hashes=None, batch=False):
"""Returns the ad images for the given ad account."""
path = 'act_%s/adimages' % account_id
args = {}
if hashes is not None:
args = {'hashes': hashes}
return self.make_request(path, 'GET', args, batch=batch)
def get_stats_by_adaccount(self, account_id, batch=False):
"""Returns the stats for a Facebook campaign."""
path = 'act_%s/adcampaignstats' % account_id
return self.make_request(path, 'GET', batch=batch)
# New API
def get_stats_by_adcampaign_group(
self, campaign_group_id, fields=None, filters=None, batch=False):
"""Returns the stats for a Facebook campaign group."""
path = '%s/stats' % campaign_group_id
args = {}
if fields:
args['fields'] = json.dumps(fields)
if filters:
args['filters'] = json.dumps(filters)
return self.make_request(path, 'GET', args, batch=batch)
def get_stats_by_adcampaign(self, account_id, campaign_ids=None,
batch=False):
"""Returns the stats for a Facebook campaign by adcampaign."""
path = 'act_%s/adcampaignstats' % account_id
args = {}
if campaign_ids is not None:
args['campaign_ids'] = json.dumps(campaign_ids)
return self.make_request(path, 'GET', args, batch=batch)
def get_stats_by_adgroup(self, account_id, adgroup_ids=None, batch=False):
"""Returns the stats for a Facebook campaign by adgroup."""
path = 'act_%s/adgroupstats' % account_id
args = {}
if adgroup_ids is not None:
args['adgroup_ids'] = json.dumps(adgroup_ids)
return self.make_request(path, 'GET', args, batch=batch)
# New API
def get_time_interval(self, start, end):
"""Returns formatted time interval."""
if not start or not end:
return None
end = end + datetime.timedelta(1)
if not isinstance(start, datetime.datetime):
start = datetime.datetime(start)
if not isinstance(end, datetime.datetime):
end = datetime.datetime(end)
time_interval = dict(
day_start=dict(day=start.day, month=start.month, year=start.year),
day_stop=dict(day=end.day, month=end.month, year=end.year)
)
return json.dumps(time_interval)
def get_adreport_stats(self, account_id, date_preset, time_increment,
data_columns, filters=None, actions_group_by=None,
batch=False):
"""Returns the ad report stats for the given account."""
path = 'act_%s/reportstats' % account_id
args = {
'date_preset': date_preset,
'time_increment': time_increment,
'data_columns': json.dumps(data_columns),
}
if filters is not None:
args['filters'] = json.dumps(filters)
if actions_group_by is not None:
args['actions_group_by'] = actions_group_by
return self.make_request(path, 'GET', args, batch=batch)
# New API
def get_adreport_stats2(self, account_id, data_columns, date_preset=None,
date_start=None, date_end=None, time_increment=None,
actions_group_by=None, filters=None, async=False,
batch=False):
"""Returns the ad report stats for the given account."""
if date_preset is None and date_start is None and date_end is None:
raise BaseException(
"Either a date_preset or a date_start/end must be set when requesting a stats info.")
path = 'act_%s/reportstats' % account_id
args = {
'data_columns': json.dumps(data_columns),
}
if date_preset:
args['date_preset'] = date_preset
if date_start and date_end:
args['time_interval'] = \
self.get_time_interval(date_start, date_end)
if time_increment:
args['time_increment'] = time_increment
if filters:
args['filters'] = json.dumps(filters)
if actions_group_by:
args['actions_group_by'] = actions_group_by
if async:
args['async'] = 'true'
return self.make_request(path, 'POST', args=args, batch=batch)
return self.make_request(path, 'GET', args=args, batch=batch)
# New API
def get_async_job_status(self, job_id, batch=False):
"""Returns the asynchronously requested job status"""
path = '%s' % job_id
return self.make_request(path, 'GET', batch=batch)
# New API
def get_async_job_result(self, account_id, job_id, batch=False):
"""Returns completed result of the given async job"""
path = 'act_%s/reportstats' % account_id
args = {
'report_run_id': job_id
}
return self.make_request(path, 'GET', args=args, batch=batch)
def get_conversion_stats_by_adaccount(self, account_id, batch=False):
"""Returns the aggregated conversion stats for the given ad account."""
path = 'act_%s/conversions' % account_id
return self.make_request(path, 'GET', batch=batch)
def get_conversion_stats_by_adcampaign(self, account_id, campaign_ids=None,
include_deleted=False, batch=False):
"""Returns the conversions stats for all ad campaigns."""
path = 'act_%s/adcampaignconversions' % account_id
args = {}
if campaign_ids is not None:
args['campaign_ids'] = json.dumps(campaign_ids)
if include_deleted is not None:
args['include_deleted'] = include_deleted
return self.make_request(path, 'GET', args, batch=batch)
def get_conversion_stats_by_adgroup(self, account_id, adgroup_ids=None,
include_deleted=False, batch=False):
"""Returns the conversions stats for all ad groups."""
path = 'act_%s/adgroupconversions' % account_id
args = {}
if adgroup_ids is not None:
args['adgroup_ids'] = json.dumps(adgroup_ids)
if include_deleted is not None:
args['include_deleted'] = include_deleted
return self.make_request(path, 'GET', args, batch=batch)
def get_conversion_stats(self, adgroup_id, batch=False):
"""Returns the conversion stats for a single ad group."""
path = '%s/conversions' % adgroup_id
return self.make_request(path, 'GET', batch=batch)
def get_offsite_pixel(self, offsite_pixel_id, batch=False):
"""Returns the information for the given offsite pixel."""
path = '%s' % offsite_pixel_id
return self.make_request(path, 'GET', batch=batch)
def get_offsite_pixels(self, account_id, batch=False):
"""Returns the list of offsite pixels for the given account."""
path = 'act_%s/offsitepixels' % account_id
return self.make_request(path, 'GET', batch=batch)
def get_keyword_stats(self, adgroup_id, batch=False):
"""Returns the keyword stats for the given ad group."""
path = '%s/keywordstats' % adgroup_id
return self.make_request(path, 'GET', batch=batch)
def get_ratecard(self, account_id, batch=False):
"""Returns the rate card for Homepage Ads."""
path = 'act_%s/ratecard' % account_id
return self.make_request(path, 'GET', batch=batch)
def get_reach_estimate(self, account_id, currency, targeting_spec,
creative_action_spec=None,
bid_for=None, batch=False):
"""Returns the reach estimate for the given currency and targeting."""
path = 'act_%s/reachestimate' % account_id
args = {
'currency': currency,
'targeting_spec': targeting_spec,
}
if creative_action_spec is not None:
args['creative_action_spec'] = creative_action_spec
if bid_for is not None:
args['bid_for'] = bid_for
return self.make_request(path, 'GET', args, batch=batch)
def get_adcampaign_list(self, account_id):
"""Returns the list of ad campaigns and related data."""
fields = 'id, name, campaign_status, start_time, end_time, ' \
'daily_budget, lifetime_budget, budget_remaining'
batch = [
self.get_adaccount(account_id, ['currency'], batch=True),
self.get_adcampaigns(account_id, fields=False, batch=True),
self.get_stats_by_adcampaign(account_id, batch=True),
]
return self.make_batch_request(batch)
def get_adcampaign_detail(self, account_id, campaign_id, date_preset):
"""Returns the detail of an ad campaign."""
campaign_fields = [
'name', 'campaign_status', 'daily_budget', 'lifetime_budget',
'start_time', 'end_time']
campaign_data_columns = [
'campaign_name', 'reach', 'frequency', 'clicks',
'actions', 'total_actions', 'ctr', 'spend']
adgroup_data_columns = [
'campaign_id', 'campaign_name', 'adgroup_id', 'adgroup_name',
'reach', 'frequency', 'clicks', 'ctr', 'actions', 'cpm', 'cpc',
'spend']
demographic_data_columns = [
'campaign_id', 'reach', 'frequency', 'clicks', 'actions', 'spend',
'cpc', 'cpm', 'ctr', 'cost_per_total_action', 'age', 'gender']
placement_data_columns = [
'campaign_id', 'reach', 'frequency', 'clicks', 'actions', 'spend',
'cpc', 'cpm', 'ctr', 'cost_per_total_action', 'placement']
campaign_filters = [{
'field': 'campaign_id', 'type': 'in', 'value': [campaign_id]}]
batch = [
self.get_adaccount(account_id, ['currency'], batch=True),
self.get_adcampaign(
campaign_id, campaign_fields=False, batch=True),
self.get_adreport_stats(
account_id, date_preset, 'all_days', campaign_data_columns,
campaign_filters, ['action_type'], True),
self.get_adreport_stats(
account_id, date_preset, 1, campaign_data_columns,
campaign_filters, None, True),
self.get_adreport_stats(
account_id, date_preset, 'all_days', adgroup_data_columns,
campaign_filters, None, True),
self.get_adreport_stats(
account_id, date_preset, 'all_days', demographic_data_columns,
campaign_filters, None, True),
self.get_adreport_stats(
account_id, date_preset, 'all_days', placement_data_columns,
campaign_filters, None, True),
]
return self.make_batch_request(batch)
def get_user_pages(self, user_id, fields=None, batch=False):
"""Returns the list of pages to which user has access with tokens."""
path = '%s/accounts' % user_id
args = {}
if fields:
args['fields'] = json.dumps(fields)
return self.make_request(path, 'GET', args, batch=batch)
def get_autocomplete_data(self, q, type, want_localized_name=False,
list=None, limit=None, batch=False):
"""Returns the autocomplete data for the given query and type."""
path = '%s/search' % q
args = {'type': type}
if want_localized_name:
args['want_localized_name'] = want_localized_name
if list:
args['list'] = list
if limit:
args['limit'] = limit
return self.make_request(path, 'GET', args, batch=batch)
def get_page_access_token(self, page_id, batch=False):
"""Returns the page access token for the given page."""
path = '%s' % page_id
args = {'fields': 'access_token'}
return self.make_request(path, 'GET', args, batch=batch)
def create_link_page_post(self, page_id, link, message=None, picture=None,
thumbnail=None, name=None, caption=None,
description=None, published=None, batch=False):
"""Creates a link page post on the given page."""
# TODO: this method is calling the API twice; combine them into batch
page_access_token = self.get_page_access_token(page_id)
path = '%s/feed' % page_id
args = {
'link': link,
'access_token': page_access_token['access_token'],
}
files = {}
if message is not None:
args['message'] = message
if picture is not None:
args['picture'] = picture
if thumbnail is not None:
files['thumbnail'] = thumbnail
if published is not None:
args['published'] = published
if name is not None:
args['name'] = name
if caption is not None:
args['caption'] = caption
if description is not None:
args['description'] = description
return self.make_request(path, 'POST', args, files, batch=batch)
def create_video_page_post(self, page_id, source, title=None,
description=None, thumb=None, published=True,
scheduled_publish_time=None, batch=False):
# TODO: this method is calling the API twice; combine them into batch
page_access_token = self.get_page_access_token(page_id)
path = '%s/videos' % page_id
args = {
'published': published,
'access_token': page_access_token['access_token'],
}
files = {'source': source}
if title is not None:
args['title'] = title
if description is not None:
args['description'] = description
if thumb is not None:
files['thumb'] = thumb
if scheduled_publish_time is not None:
args['scheduled_publish_time'] = scheduled_publish_time
return self.make_request(path, 'POST', args, files, batch=batch)
# New API: 2014.03.07, This method is not working caused by facebook error.
def _create_adcampaign_group(self, account_id, name, campaign_group_status,
objective=None, batch=False):
"""Creates an ad campaign group for the given account."""
path = 'act_%s/adcampaign_groups'
args = {
'name': name,
'campaign_group_status': campaign_group_status,
}
if objective is not None:
args['objective'] = objective
return self.make_request(path, 'POST', args, batch=batch)
# New API
def update_adcampaign_group(self, campaign_group_id, name=None,
campaign_group_status=None, objective=None,
batch=False):
"""Updates condition of the given ad campaign group."""
path = '%s' % campaign_group_id
args = {}
if name is not None:
args['name'] = name
if campaign_group_status is not None:
args['campaign_group_status'] = campaign_group_status
if objective is not None:
args['objective'] = objective
return self.make_request(path, 'POST', args, batch=batch)
# New API: Need to change 'create_adcampaign' when facebook api is set new
# api.
def _create_adcampaign(self, account_id, campaign_group_id, name,
campaign_status,
daily_budget=None, lifetime_budget=None,
start_time=None, end_time=None, batch=False):
"""Creates an ad campaign for the given account."""
if daily_budget is None and lifetime_budget is None:
raise BaseException(
"Either a lifetime_budget or a daily_budget must be set when creating a campaign")
if lifetime_budget is not None and end_time is None:
raise BaseException(
"end_time is required when lifetime_budget is specified")
path = 'act_%s/adcampaigns' % account_id
args = {
'campaign_group_id': campaign_group_id,
'name': name,
'campaign_status': campaign_status,
}
if daily_budget:
args['daily_budget'] = daily_budget
if lifetime_budget:
args['lifetime_budget'] = lifetime_budget
if start_time:
args['start_time'] = start_time
if end_time:
args['end_time'] = end_time
return self.make_request(path, 'POST', args, batch=batch)
# Deprecated: this method will be update.
def create_adcampaign(self, account_id, name, campaign_status,
daily_budget=None, lifetime_budget=None,
start_time=None, end_time=None, batch=False):
"""Creates an ad campaign for the given account."""
if daily_budget is None and lifetime_budget is None:
raise BaseException(
"Either a lifetime_budget or a daily_budget must be set when creating a campaign")
if lifetime_budget is not None and end_time is None:
raise BaseException(
"end_time is required when lifetime_budget is specified")
path = 'act_%s/adcampaigns' % account_id
args = {
'name': name,
'campaign_status': campaign_status,
}
if daily_budget:
args['daily_budget'] = daily_budget
if lifetime_budget:
args['lifetime_budget'] = lifetime_budget
if start_time:
args['start_time'] = start_time
if end_time:
args['end_time'] = end_time
return self.make_request(path, 'POST', args, batch=batch)
# New API
def update_adcampaign(self, campaign_id, name=None, campaign_status=None,
daily_budget=None, lifetime_budget=None,
end_time=None, batch=False):
"""Updates condition of the given ad campaign."""
path = '%s' % campaign_id
args = {}
if name:
args['name'] = name
if campaign_status:
args['campaign_status'] = campaign_status
if daily_budget:
args['daily_budget'] = daily_budget
if lifetime_budget:
args['lifetime_budget'] = lifetime_budget
if end_time:
args['end_time'] = end_time
return self.make_request(path, 'POST', args, batch=batch)
# New API
def delete_adcampaign(self, campaign_id, batch=False):
"""Delete the given ad campaign."""
path = '%s' % campaign_id
return self.make_request(path, 'DELETE', batch=batch)
def create_adcreative_type_27(self, account_id, object_id,
auto_update=None, story_id=None,
url_tags=None, name=None, batch=False):
"""Creates an ad creative in the given ad account."""
path = 'act_%s/adcreatives' % account_id
args = {
'type': 27,
'object_id': object_id,
}
if auto_update:
args['auto_update'] = auto_update
if story_id:
args['story_id'] = story_id
if url_tags:
args['url_tags'] = url_tags
if name:
args['name'] = name
return self.make_request(path, 'POST', args, batch=batch)
def create_adgroup(self, account_id, name, bid_type, bid_info, campaign_id,
creative_id, targeting, conversion_specs=None,
tracking_specs=None, view_tags=None, objective=None,
batch=False):
"""Creates an adgroup in the given ad camapaign with the given spec."""
path = 'act_%s/adgroups' % account_id
args = {
'name': name,
'bid_type': bid_type,
'bid_info': bid_info,
'campaign_id': campaign_id,
'creative': json.dumps({'creative_id': creative_id}),
'targeting': json.dumps({"countries": targeting}),
}
if conversion_specs:
args['conversion_specs'] = json.dumps(conversion_specs)
if tracking_specs:
args['tracking_specs'] = json.dumps(tracking_specs)
if view_tags:
args['view_tags'] = json.dumps(view_tags)
if objective:
args['objective'] = objective
return self.make_request(path, 'POST', args, batch=batch)
def create_offsite_pixel(self, account_id, name, tag, batch=False):
"""Creates an offsite pixel for the given account."""
path = 'act_%s/offsitepixels' % account_id
args = {
'name': name,
'tag': tag,
}
return self.make_request(path, 'POST', args, batch=batch)
# <codecell>