def create_ad(self, accountid, name, adsetid, creativeid, appinfo): """ Step 5: finally create the ad within our campaign, ad set and creative. See [Ad Group](https://developers.facebook.com/docs/marketing-api/adgroup) for further details on the API used here. """ ad = Ad(parent_id=accountid) ad[Ad.Field.name] = name ad[Ad.Field.adset_id] = adsetid ad[Ad.Field.creative] = {'creative_id': str(creativeid)} tracking_specs = [{ 'action.type': ['mobile_app_install'], 'application': [appinfo['fbapplication_id']] }, { 'action.type': ['app_custom_event'], 'application': [appinfo['fbapplication_id']] }] if not (appinfo['fboffsitepixel_id'].strip() == 'null'): tracking_specs.append({ 'action.type': ['offsite_conversion'], 'offsite_pixel': [appinfo['fboffsitepixel_id']] }) ad[Ad.Field.tracking_specs] = tracking_specs ad.remote_create(params={'status': Ad.Status.paused}) return ad[Ad.Field.id]
def create_ad(adset: AdSet, creative: AdCreative, status: str) -> Ad: a = Ad() a[Ad.Field.name] = creative["name"] a[Ad.Field.status] = status a[Ad.Field.adset_id] = adset["id"] a[Ad.Field.creative] = creative return a
def _ad(c, adset): a = Ad() a[Ad.Field.adset_id] = adset["id"] a["name"] = c["name"] a["creative"] = c a["status"] = "ACTIVE" return a
def test_get_ad_creatives(self): with warnings.catch_warnings(record=True) as warning: self.mock_response.status_code = StatusCode.SUCCESS self.mock_response._content = str.encode( '{' '"' + str(FieldName.NAME) + '":"' + str(TestValue.NAME) + '",' '"' + str(FieldName.ID) + '":"' + str(TestValue.CREATIVE_ID) + '"' '}') self.mock_request.return_value = self.mock_response fields = [ FieldName.NAME, FieldName.ID, ] params = {} creatives = Ad(TestValue.AD_ID).get_ad_creatives( fields=fields, params=params, ) self.assertEqual(len(warning), 0) self.assertTrue(isinstance(creatives[0], AdCreative)) self.assertEqual(creatives[0][FieldName.NAME], TestValue.NAME) self.assertEqual(creatives[0][FieldName.ID], TestValue.CREATIVE_ID)
def collect_ad_and_creative_data(): ads_df = pd.DataFrame(columns=[ "adset_id", "ad_id", "ad_name", "inline_link_clicks", "unique_inline_link_clicks", "spend", "impressions", "reach", "date_start", "date_stop", "relevance_score", "cpc", "cpm", "frequency" ]) i = 0 for date_val in total_dates: fields = { "adset_id", "adset_name", "ad_id", "ad_name", "spend", "inline_link_clicks", "unique_inline_link_clicks", "reach", "impressions", "cpc", "cpm", "relevance_score", "created_time", "updated_time" } params = { 'level': 'ad', 'time_range': { 'since': str(date_val), 'until': str(date_val) }, } ad_insights = my_account.get_insights(fields=fields, params=params) creative = Ad(ads['ad_id']).get_ad_creatives(fields=creative_fields)
def create_ad(_creative, _adset_id=None, _name=None, _status='Active', _ad_account=ad_account_id): from facebook_business.adobjects.ad import Ad if _name is None: _name='API Test Ad Name - DELETE' ad = Ad(parent_id=_ad_account) ad[Ad.Field.name] = _name ad[Ad.Field.adset_id] = _adset_id ad[Ad.Field.tracking_specs] = [ { "action.type": ["offsite_conversion"], "fb_pixel": ["153097368750576"] }, ] if is_number(_creative): ad[Ad.Field.creative] = { 'creative_id': _creative, } else: ad[Ad.Field.creative] = _creative if _status == 'Active': ad.remote_create(params={ 'status': Ad.Status.active, }) else: ad.remote_create(params={ 'status': Ad.Status.paused, }) return ad
def update_facebook(app_id, app_secret, access_token, options): # pragma: no cover """ Update status of ads on Facebook if different from respective suggestion; return dataframe with updated ads """ api = FacebookAdsApi.init(app_id, app_secret, access_token) updated = [] # Determine number of required batches since # Facebook only allows 50 API calls per batch num_options = len(options.index) batch_size = 50 batches = int(num_options / batch_size) + 1 # Split options into batches and loop through those i = 0 for _ in range(batches): option_batch = options.loc[i:i + batch_size, :] i += batch_size update_batch = api.new_batch() # Loop through options within batch, compare current and suggested # ad status and update if changed for _, row in option_batch.iterrows(): ad_id = str(row['ad_id']) ad = Ad(ad_id) ad.api_get(fields=[Ad.Field.status]) old_status = ad[Ad.Field.status] new_status = row['ad_status'] if old_status != new_status: ad[Ad.Field.status] = new_status updated.append([ad_id, old_status + ' -> ' + new_status]) ad.api_update(batch=update_batch, fields=[], params={Ad.Field.status: new_status}) update_batch.execute() return pd.DataFrame(updated, columns=['ad_id', 'updated'])
def loadAdFromJson(self, jsonFile): ad = Ad(parent_id=self.account_id) config_file = open(jsonFile) config = json.load(config_file) config_file.close() for key in config.keys(): ad[key] = config[key] return ad
def ad_status_update(self, ad_id): try: ad = Ad(ad_id) ad[Ad.Field.status] = 'ACTIVE' ad.remote_update() print("Successfully Ad updated!") except Exception as e: print(e)
def get_ad_data_or_sleep(self, ad): """ Get needed data for ads or sleep :param ad: :return: """ while True: ad_data = {'ad_id': ad} try: ad = Ad(ad) creative = AdCreative( ad.api_get(fields=[Ad.Field.creative])['creative']['id']) fields = [ AdCreative.Field.call_to_action_type, AdCreative.Field.object_story_spec ] creative.api_get(fields=fields) creative = dict(creative) try: call_to_action = creative['object_story_spec'][ 'video_data']['call_to_action'] try: print(creative['object_story_spec']['photo_data']) except KeyError: pass ad_data['website_url'] = call_to_action['value']['link'] ad_data['call_to_action_type'] = call_to_action['type'] ad_data['headline'] = creative['object_story_spec'][ 'video_data']['title'] ad_data['description'] = creative['object_story_spec'][ 'video_data']['message'] video = AdVideo(creative['object_story_spec']['video_data'] ['video_id']) ad_data['video_name'] = video.api_get( fields=[AdVideo.Field.title])['title'] except KeyError: pass self.current_ads.append(ad_data) except FacebookRequestError as e: print(type(e.api_error_code())) if e.api_error_code() == 803: break print('Sleeping right now for ads') time.sleep(600) else: break return ad_data
def do_request(): params = {'limit': RESULT_RETURN_LIMIT} if self.current_bookmark: params.update({ 'filtering': [{ 'field': CREATED_TIME_KEY, 'operator': 'GREATER_THAN', 'value': self.current_bookmark.int_timestamp }] }) #print("yield",Ad(23845021434510170).get_leads(fields=self.automatic_fields(), params=params)) yield Ad(CONFIG['adset_id']).get_leads( fields=self.automatic_fields(), params=params) # pylint: disable=no-member
def createAd(self, name): print("Creating Image Hash...") img_path = 'Icon-1024.png' image = AdImage() image['_parent_id'] = id image[AdImage.Field.filename] = img_path image.remote_create() print("**Image Hash...**") # Output image Hash image_hash = image[AdImage.Field.hash] ##image_hash = "5c2f70590d5a1381f1871a5e3731ecb1" print("**Image Hash : {}**".format(image_hash)) print("** Creating Ad Creative...**") website_url = "www.example.com" page_id = '181951488809425' link_data = AdCreativeLinkData() link_data[AdCreativeLinkData.Field.name] = 'main text 001' link_data[AdCreativeLinkData.Field.message] = 'title 001' link_data[AdCreativeLinkData.Field.link] = website_url link_data[AdCreativeLinkData.Field.image_hash] = image_hash object_story_spec = AdCreativeObjectStorySpec() object_story_spec[AdCreativeObjectStorySpec.Field.page_id] = page_id object_story_spec[ AdCreativeObjectStorySpec.Field.link_data] = link_data creative = AdCreative() creative['_parent_id'] = id creative[AdCreative.Field.object_story_spec] = object_story_spec creative[AdCreative.Field.title] = 'Main text 001' creative[AdCreative.Field.body] = 'Title 001' creative[AdCreative.Field.actor_id] = page_id creative[AdCreative.Field.link_url] = website_url creative[AdCreative.Field.object_type] = AdCreative.ObjectType.domain creative[AdCreative.Field.image_hash] = image_hash print("Ad Creative created successfully!") print("***Ad...*") ad = Ad() ad['_parent_id'] = self.id ad[Ad.Field.name] = name ad[Ad.Field.adset_id] = self.adset_id ad[Ad.Field.creative] = creative ad.remote_create(params={ 'status': Ad.Status.paused, }) self.ad_id = str(ad[Ad.Field.id]) print("**Ad ID: {}**".format(self.ad_id)) return ad
def test_split_job_smallest(self, mocker, api): """Test that split will correctly downsize edge_object""" interval = pendulum.Period(pendulum.Date(2010, 1, 1), pendulum.Date(2010, 1, 10)) params = {"time_increment": 1, "breakdowns": []} job = InsightAsyncJob(api=api, edge_object=Ad(1), interval=interval, params=params) with pytest.raises( ValueError, match="The job is already splitted to the smallest size."): job.split_job()
def test_read_with_ad_management_query(self, mock_query_ad_management): temp_kwargs = self.kwargs.copy() temp_kwargs.update({"ad_insights": False, "field": ["id", "status"]}) row1, row2 = Ad(), Ad() row1.set_data({"id": "123456789", "status": "ACTIVE"}) row2.set_data({"id": "987654321", "status": "PAUSED"}) mock_query_ad_management.return_value = [row1, row2] data = next(FacebookReader(**temp_kwargs).read()) expected = [ { "id": "123456789", "status": "ACTIVE" }, { "id": "987654321", "status": "PAUSED" }, ] for record, report in zip(data.readlines(), iter(expected)): self.assertEqual(record, report)
def fetch_ads(adaccount): ads = adaccount.get_ads(fields=[ Ad.Field.name, Ad.Field.account_id, Ad.Field.id, Ad.Field.adset_id, Ad.Field.status, Ad.Field.effective_status, Ad.Field.created_time, Ad.Field.updated_time ]) for ad in ads: # ad = dict(ad[0]) ad_ins = Ad(ad['id']) ad_creative = fetch_ad_creative(ad_ins) ad_creative = dict(ad_creative[0]) result = {} result['name'] = ad['name'] if 'name' in ad else '' result['facebook_account_id'] = ad['account_id'] if\ 'account_id' in ad else '' result['facebook_ad_id'] = ad['id'] if 'id' in ad else '' result['facebook_adset_id'] = ad['adset_id'] if\ 'adset_id' in ad else '' result['status'] = ad['status'] if 'status' in ad else '' result['effective_status'] = ad['effective_status'] if\ 'effective_status' in ad else '' result['name'] = ad['name'] if 'name' in ad else '' result['ad_created_time'] = ad['created_time'] if\ 'created_time' in ad else '' result['updated_time'] = ad['updated_time'] if\ 'updated_time' in ad else '' result['created_time'] =\ datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") result['thumbnail'] = ad_creative['thumbnail_url'] if\ 'thumbnail_url' in ad_creative else '' result['url_tags'] = ad_creative['url_tags'] if\ 'url_tags' in ad_creative else '' # result['video_id'] = ad_creative['video_id'] if\ # 'video_id' in ad_creative else '' result['big_image'] = ad_creative['image_url'] if\ 'image_url' in ad_creative else '' result['title'] = ad_creative['title'] if\ 'title' in ad_creative else '' try: result['destination'] = ad_creative['object_story_spec'][ 'video_data']['call_to_action']['value']['link'] result['short_destination'] = ad_creative['object_story_spec'][ 'video_data']['call_to_action']['value']['link_caption'] except Exception as e: result['destination'] = '' result['short_destination'] = '' # print(result) yield result
def create_ad(name, adset_id, creative_id, status): print('Creating Ad: (name={})'.format(name)) params = { Ad.Field.name: name, Ad.Field.adset_id: adset_id, Ad.Field.creative: { 'creative_id': creative_id, }, Ad.Field.status: status, } ad = Ad(parent_id=account_id, api=api) # ad = ad.remote_create(params=params) # print(ad) return ad
def test_get_ad_creatives_with_wrong_fields(self): with warnings.catch_warnings(record=True) as warning: self.mock_response.status_code = StatusCode.ERROR self.mock_request.return_value = self.mock_response fields = [ 'unexist_field', ] params = {} with self.assertRaises(FacebookRequestError): creatives = Ad(TestValue.AD_ID).get_ad_creatives( fields=fields, params=params, ) self.assertEqual(len(warning), 1) self.assertTrue(issubclass(warning[0].category, UserWarning))
def do_request_multiple(): params = {'limit': RESULT_RETURN_LIMIT} bookmark_params = [] if self.current_bookmark: bookmark_params.append({ 'field': CREATED_TIME_KEY, 'operator': 'GREATER_THAN', 'value': self.current_bookmark.int_timestamp }) for del_info_filt in iter_delivery_info_filter('lead'): params.update({'filtering': [del_info_filt] + bookmark_params}) filt_leads = Ad(CONFIG['adset_id']).get_leads( fields=self.automatic_fields(), params=params) # pylint: disable=no-member yield filt_leads
def test_get_insights(self): with warnings.catch_warnings(record=True) as warning: self.mock_response.status_code = StatusCode.SUCCESS self.mock_response._content = str.encode( '{' '"' + str(FieldName.AD_NAME) + '":"' + str(TestValue.NAME) + '",' '"' + str(FieldName.AD_ID) + '":"' + str(TestValue.AD_ID) + '",' '"' + str(FieldName.DATE_START) + '":"' + str(TestValue.DATE_START) + '",' '"' + str(FieldName.DATE_STOP) + '":"' + str(TestValue.DATE_STOP) + '"' '}') self.mock_request.return_value = self.mock_response fields = [ FieldName.AD_NAME, ] params = { FieldName.ACTION_BREAKDOWNS: [TestValue.ACTION_BREAKDOWNS], FieldName.ACTION_ATTRIBUTION_WINDOWS: [TestValue.ACTION_ATTRIBUTION_WINDOWS], FieldName.DATE_PRESET: TestValue.DATE_PRESET, FieldName.LEVEL: TestValue.LEVEL, FieldName.SUMMARY_ACTION_BREAKDOWNS: [TestValue.SUMMARY_ACTION_BREAKDOWNS], } ad_insights = Ad(TestValue.AD_ID).get_insights( fields=fields, params=params, ) self.assertEqual(len(warning), 0) self.assertTrue(isinstance(ad_insights[0], AdsInsights)) self.assertEqual(ad_insights[0][FieldName.AD_NAME], TestValue.NAME) self.assertEqual(ad_insights[0][FieldName.DATE_START], TestValue.DATE_START) self.assertEqual(ad_insights[0][FieldName.DATE_STOP], TestValue.DATE_STOP)
def fetch_ad_data(ad_id): ad = Ad(ad_id) ad_datas = ad.get_insights( fields=[ AdsInsights.Field.ad_id, AdsInsights.Field.spend, AdsInsights.Field.impressions, AdsInsights.Field.reach, AdsInsights.Field.unique_actions, AdsInsights.Field.ad_name ], params={ 'breakdowns': ['hourly_stats_aggregated_by_audience_time_zone'], 'time_range': { 'since': yesterday, 'until': today } }) for ad_data in ad_datas: print(ad_data) result = {} result['spend'] = ad_data['spend'] if 'spend' in ad_data else '' result['impression_count'] = ad_data['impressions'] if\ 'impressions' in ad_data else '' result['reach_count'] = ad_data['reach'] if 'reach' in ad_data else '' result['link_click_count'] = ad_data['link_click'] if\ 'link_click_count' in ad_data else '' result['ad_id'] = ad_data['ad_id'] if 'ad_id' in ad_data else '' result['stat_dt'] = ad_data['date_start'] print(result['stat_dt']) result['stat_hour'] = \ str(int(ad_data['hourly_stats_aggregated_by_audience_time_zone'][0:2]) + 1) try: for actions in ad_data['unique_actions']: if actions['action_type'] == 'link_click': result['link_click_count'] = actions['value'] if actions[ 'action_type'] == 'offsite_conversion.fb_pixel_purchase': result['effective_count'] = actions['value'] except Exception as e: result['effective_count'] = '' result['link_click_count'] = '' result['create_time'] = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S") yield result
def test_get_insights_with_wrong_fields_and_params(self): with warnings.catch_warnings(record=True) as warning: self.mock_response.status_code = StatusCode.ERROR self.mock_request.return_value = self.mock_response fields = [ 'unexisted_fields', ] params = { FieldName.ACTION_BREAKDOWNS: 3, FieldName.LEVEL: 'wrong_level', } with self.assertRaises(FacebookRequestError): ad_insights = Ad(TestValue.AD_ID).get_insights( fields, params, ) self.assertEqual(len(warning), 3) self.assertTrue(issubclass(warning[0].category, UserWarning))
def handle_ads(self, ad): ad_ins = Ad(ad['id']) ad_creative = self.fetch_adcreatives(ad_ins) ad_creative = dict(ad_creative[0]) result = dict() result['facebook_campaign_id'] = ad.get('campaign_id', '') result['name'] = ad.get('name', '').replace("'", '\"') result['facebook_account_id'] = ad.get('account_id', '') result['facebook_ad_id'] = ad.get('id', '') result['facebook_adset_id'] = ad.get('adset_id', '') result['status'] = ad.get('status', '') result['effective_status'] = ad.get('effective_status', '') result['ad_created_time'] = ad.get('created_time', '') result['updated_time'] = ad.get('updated_time', '') result['created_time'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S") result['thumbnail'] = ad_creative.get('thumbnail_url', '') result['url_tags'] = ad_creative.get('url_tags', '') result['big_image'] = ad_creative.get('image_url', '') result['title'] = ad_creative.get('title', '') result['object_type'] = ad_creative.get('object_type', '') story = ad_creative.get('object_story_spec', '') if story: try: result['object_type'] = story['object_type'] except: result['object_type'] = '' try: result['destination'] = story['link_data']['link'] except Exception as e: result['destination'] = story['link_data']['call_to_action'][ 'value']['link'] try: result['short_destination'] = story['video_data'][ 'call_to_action']['value']['link'] except Exception as e: result['short_destination'] = '' finally: self.model.replace_into_ad_basic(result) else: self.model.replace_into_ad_basic(result)
def create_ad(self, account_id, name, adset_id, creative_id, app_id): """ Step 5: finally create the ad within our campaign, ad set and creative. See [Ad Group](https://developers.facebook.com/docs/marketing-api/adgroup) for further details on the API used here. """ adgroup = Ad(parent_id=account_id) adgroup[Ad.Field.name] = name adgroup[Ad.Field.adset_id] = adset_id adgroup[Ad.Field.creative] = {'creative_id': str(creative_id)} tracking_specs = [{ 'action.type': ['mobile_app_install'], 'application': [app_id] }, { 'action.type': ['app_custom_event'], 'application': [app_id] }] adgroup[Ad.Field.tracking_specs] = tracking_specs adgroup.remote_create(params={'status': Ad.Status.paused}) return adgroup[Ad.Field.id]
print('creative_id:', creative_id, '\n') fields = [] params = { 'name': 'My Ad', 'adset_id': ad_set_id, 'creative': { 'creative_id': creative_id }, 'status': 'PAUSED', 'special_ad_categories': 'None', } ad = AdAccount(ad_account_id).create_ad( fields=fields, params=params, ) print('ad', ad) ad_id = ad.get_id() print('ad_id:', ad_id, '\n') fields = [] params = { 'ad_format': 'DESKTOP_FEED_STANDARD', 'special_ad_categories': 'None', } print(Ad(ad_id).get_previews( fields=fields, params=params, ))
# As with any software that integrates with the Facebook platform, your use # of this software is subject to the Facebook Developer Principles and # Policies [http://developers.facebook.com/policy/]. This copyright notice # shall be included in all copies or substantial portions of the software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. from facebook_business.adobjects.ad import Ad from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<ADGROUP_ID>' FacebookAdsApi.init(access_token=access_token) fields = [] params = { 'name': 'My New Ad', } print Ad(id).update( fields=fields, params=params, )
# TODO: Clean up this part and create methods / class with verification File.write( "../data/" + output_filename, arrayToTSVLine([ "ad_name".upper(), "ad_id".upper(), "campaign_id".upper(), "account_id".upper(), "adset_id".upper(), "status".upper(), "clicks".upper(), "cpc".upper(), "cpm".upper(), "cpp".upper(), "ctr".upper(), "spend".upper(), "relevance_score".upper(), "date_start".upper(), "date_end".upper() ])) for ad in account.get_ads(fields, params=params): # Ad Initialization current_ad = Ad(ad["id"]) status = ad["status"] fields = [ 'spend', 'clicks', 'ad_id', 'adset_id', 'account_id', 'campaign_id', 'cost_per_unique_click', 'cpc', 'cpp', 'cpc', 'cpm', 'ctr', 'date_start', 'date_stop', 'reach', 'frequency', 'impressions', 'social_spend', 'unique_ctr', 'unique_clicks', 'ad_name' ] params = {'date_presets': 'lifetime'} # Get all insights above from current AD ad_insights = current_ad.get_insights(fields, params) if ad_insights:
def test_get_ad(self): with warnings.catch_warnings(record=True) as warning: self.mock_response.status_code = StatusCode.SUCCESS self.mock_response._content = str.encode( '{' '"' + str(FieldName.ACCOUNT_ID) + '":"' + str(TestValue.ACCOUNT_ID) + '",' '"' + str(FieldName.AD_REVIEW_FEEDBACK) + '":' + str(TestValue.AD_REVIEW_FEEDBACK) + ',' '"' + str(FieldName.ADLABELS) + '":' + str(TestValue.AD_LABEL) + ',' '"' + str(FieldName.ADSET_ID) + '":"' + str(TestValue.ADSET_ID) + '",' '"' + str(FieldName.BID_AMOUNT) + '":"' + str(TestValue.BID_AMOUNT) + '",' '"' + str(FieldName.CONFIGURED_STATUS) + '":"' + str(TestValue.CONFIGURED_STATUS) + '",' '"' + str(FieldName.CREATIVE) + '":' + str(TestValue.CREATIVE) + ',' '"' + str(FieldName.EFFECTIVE_STATUS) + '":"' + str(TestValue.EFFECTIVE_STATUS) + '",' '"' + str(FieldName.ISSUES_INFO) + '":' + str(TestValue.ISSUES_INFO) + ',' '"' + str(FieldName.PRIORITY) + '":"' + str(TestValue.PRIORITY) + '",' '"' + str(FieldName.TARGETING) + '":' + str(TestValue.TARGETING) + ',' '"' + str(FieldName.DATE_FORMAT) + '":"' + str(TestValue.DATE_FORMAT) + '",' '"' + str(FieldName.EXECUTION_OPTIONS) + '":"' + str(TestValue.EXECUTION_OPTIONS) + '"' '}') self.mock_request.return_value = self.mock_response fields = [ FieldName.ACCOUNT_ID, FieldName.AD_REVIEW_FEEDBACK, FieldName.ADLABELS, FieldName.ADSET_ID, FieldName.BID_AMOUNT, FieldName.CONFIGURED_STATUS, FieldName.CREATIVE, FieldName.EFFECTIVE_STATUS, FieldName.ISSUES_INFO, FieldName.PRIORITY, FieldName.TARGETING, FieldName.DATE_FORMAT, FieldName.EXECUTION_OPTIONS, ] params = {} ad = Ad(TestValue.AD_ID).api_get( fields=fields, params=params, ) self.assertEqual(len(warning), 0) self.assertTrue(isinstance(ad, Ad)) self.assertEqual(ad[FieldName.ACCOUNT_ID], TestValue.ACCOUNT_ID) self.assertEqual(ad[FieldName.AD_REVIEW_FEEDBACK], json.loads(TestValue.AD_REVIEW_FEEDBACK)) self.assertEqual(ad[FieldName.ADLABELS], [json.loads(TestValue.AD_LABEL)]) self.assertEqual(ad[FieldName.ADSET_ID], TestValue.ADSET_ID) self.assertEqual(ad[FieldName.BID_AMOUNT], TestValue.BID_AMOUNT) self.assertEqual(ad[FieldName.CONFIGURED_STATUS], TestValue.CONFIGURED_STATUS) self.assertTrue(isinstance(ad[FieldName.CREATIVE], AdCreative)) self.assertEqual(ad[FieldName.EFFECTIVE_STATUS], TestValue.EFFECTIVE_STATUS) self.assertEqual(ad[FieldName.ISSUES_INFO], [json.loads(TestValue.ISSUES_INFO)]) self.assertEqual(ad[FieldName.PRIORITY], TestValue.PRIORITY) self.assertTrue(isinstance(ad[FieldName.TARGETING], Targeting)) self.assertEqual(ad[FieldName.DATE_FORMAT], TestValue.DATE_FORMAT) self.assertEqual(ad[FieldName.EXECUTION_OPTIONS], [TestValue.EXECUTION_OPTIONS])
def create_lookalike_ads( self, account_id, name, tiered_lookalikes, optimization_goal, billing_event, tiered_bid_amounts, title, body, url, image_path, daily_budget=None, lifetime_budget=None, start_time=None, end_time=None, campaign=None, ): """ Take the tiered lookalike audiences and create the ads """ results = { 'adsets': [], 'ads': [], } tiers = len(tiered_lookalikes) if tiers != len(tiered_bid_amounts): raise TypeError('Audience and bid amount number mismatch.') # Create campaign if not campaign: campaign = Campaign(parent_id=account_id) campaign[Campaign.Field.name] = '{} Campaign'.format(name) campaign[Campaign.Field.objective] = \ Campaign.Objective.link_clicks campaign.remote_create(params={ 'status': Campaign.Status.paused, }) # Upload image img = AdImage(parent_id=account_id) img[AdImage.Field.filename] = image_path img.remote_create() image_hash = img.get_hash() # Inline creative for ads inline_creative = { AdCreative.Field.title: title, AdCreative.Field.body: body, AdCreative.Field.object_url: url, AdCreative.Field.image_hash: image_hash, } for tier in range(1, tiers + 1): # Create ad set ad_set = AdSet(parent_id=account_id) ad_set[AdSet.Field.campaign_id] = campaign.get_id_assured() ad_set[AdSet.Field.name] = '{0} AdSet tier {1}'.format(name, tier) ad_set[AdSet.Field.optimization_goal] = optimization_goal ad_set[AdSet.Field.billing_event] = billing_event ad_set[AdSet.Field.bid_amount] = tiered_bid_amounts[tier - 1] if daily_budget: ad_set[AdSet.Field.daily_budget] = daily_budget else: ad_set[AdSet.Field.lifetime_budget] = lifetime_budget if end_time: ad_set[AdSet.Field.end_time] = end_time if start_time: ad_set[AdSet.Field.start_time] = start_time audience = tiered_lookalikes[tier - 1] targeting = { Targeting.Field.custom_audiences: [{ 'id': audience[CustomAudience.Field.id], 'name': audience[CustomAudience.Field.name], }] } ad_set[AdSet.Field.targeting] = targeting ad_set.remote_create(params={ 'status': AdSet.Status.paused, }) # Create ad ad = Ad(parent_id=account_id) ad[Ad.Field.name] = '{0} Ad tier {1}'.format(name, tier) ad[Ad.Field.adset_id] = ad_set['id'] ad[Ad.Field.creative] = inline_creative ad.remote_create(params={ 'status': Ad.Status.paused, }) results['adsets'].append(ad_set) results['ads'].append(ad) return results
for campaign_info in campaign_list: campaign = get_campaign(campaign_info) campaign_name = campaign.get('name') campaign_id = campaign.get('id') print("==============================") print("LIST CAMPAIGN ID ", campaign_id, " NAME ", campaign_name) adsets = get_adset(campaign_id) for adset in adsets: adset_id = adset['id'] adset_name = adset['name'] print('LIST ADSET ID ', adset_id, " NAME ", adset_name) ads = get_ads(adset_id) for ad in ads: ad_id = ad['id'] ad_name = ad['name'] ad_insights = Ad(ad_id) print('LIST AD ID ', ad_id, " NAME ", ad_name) insights = get_insight(ad_insights) if insights is not None: for insight in insights: insight_id = insight['ad_id'] insight_name = insight['ad_name'] insight_clicks = insight['clicks'] insight_cpc = insight['cpc'] insight_cpm = insight['cpm'] insight_cpp = insight['cpp'] insight_ctr = insight['ctr'] insight_spend = insight['spend'] insight_dict = { 'insight_id': insight_id, 'insight_name': insight_name,
# of this software is subject to the Facebook Developer Principles and # Policies [http://developers.facebook.com/policy/]. This copyright notice # shall be included in all copies or substantial portions of the software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. from facebook_business.adobjects.ad import Ad from facebook_business.adobjects.lead import Lead from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<AD_GROUP_ID>' FacebookAdsApi.init(access_token=access_token) fields = [ ] params = { 'filtering': [{'field':'time_created','operator':'GREATER_THAN','value':1613591600}], } print Ad(id).get_leads( fields=fields, params=params, )