def test_normal(self): images = self.images[-3:] # Only three images needed linktitles = ['Title 1', 'Title 2', 'Title 3'] deeplinks = None optimization_goal = 'APP_INSTALLS' billing_event = 'IMPRESSIONS' bid_amount = 100 result = self.cmaia_sample.carousel_app_ad_create( self.account_id, "CMAIA test", # basename "Try my app!", # message images, linktitles, deeplinks, "1000", # dailybudget, self.app_info, optimization_goal, billing_event, bid_amount, self.mobile_targeting, ) self.assertIn('campaignid', result) self.assertIn('adsetid', result) self.assertIn('creativeid', result) self.assertIn('adid', result) self.campaign = Campaign() self.campaign[Campaign.Field.id] = result['campaignid'] self.campaign.remote_read() self.assertEqual(self.campaign.get_id(), result['campaignid'])
def test_normal(self): optimization_goal = 'LINK_CLICKS' billing_event = 'LINK_CLICKS' bid_amount = '100' # stands for $1.00 result = self.appengagement_sample.app_engagement_ad_create( self.account_id, "appengagement_test", # basename "Try my app! Only 8 clicks you are done!", # message self.images[0], "500", # dailybudget stands for $5.00, self.app_info, optimization_goal, billing_event, bid_amount, self.mobile_targeting) self.assertIn('campaignid', result) self.assertIn('adsetid', result) self.assertIn('creativeid', result) self.assertIn('adid', result) self.campaign = Campaign() self.campaign[Campaign.Field.id] = result['campaignid'] self.campaign.remote_read() self.assertEqual(self.campaign.get_id(), result['campaignid'])
def test_normal(self): optimization_goal = 'APP_INSTALLS' billing_event = 'IMPRESSIONS' bid_amount = 100 result = self.maia_sample.create_app_install_ad( self.account_id, "MAIA Test", # basename "Try my app!", # message self.images[0], "1000", # dailybudget, self.page_id, optimization_goal, billing_event, bid_amount, self.mobile_targeting, self.app_info['fbapplication_id'], self.app_info['app_name'], self.app_info['appstore_link'], self.app_info['app_deep_link'], ) self.assertIn('campaign_id', result) self.assertIn('adset_id', result) self.assertIn('creative_id', result) self.assertIn('ad_id', result) self.campaign = Campaign() self.campaign[Campaign.Field.id] = result['campaign_id'] self.campaign.remote_read() self.assertEqual(self.campaign.get_id(), result['campaign_id'])
def campaigns_with_insights(start, end): response = [] try: my_session = FacebookSession(my_app_id, my_app_secret, my_access_token) my_api = FacebookAdsApi(my_session) FacebookAdsApi.set_default_api(my_api) me = objects.AdUser(fbid='me') my_accounts = list(me.get_ad_accounts()) my_account = my_accounts[0] fields = [ AdsInsights.Field.clicks, AdsInsights.Field.spend, AdsInsights.Field.impressions, AdsInsights.Field.unique_clicks, AdsInsights.Field.cost_per_unique_click, AdsInsights.Field.cost_per_inline_link_click ] params = { 'time_range': { 'since': start, 'until': end }, 'effective_status': ["ACTIVE"] } campaigns = my_account.get_campaigns( params=params, fields=[Campaign.Field.name, Campaign.Field.status]) headers = [ "Name", 'Cost', "Impressions", "Clicks", "Unique Clicks", "Cost per unique click", ] for i in campaigns: try: campaign = Campaign(i['id']) campaign_data = campaign.get_insights(params=params, fields=fields) campaign_dict = { 'id': i['id'], 'name': i['name'], 'Cost': campaign_data[0]['spend'], "Clicks": campaign_data[0]['clicks'], "Unique_Clicks": campaign_data[0]['unique_clicks'], "Cost_per_unique_click": campaign_data[0]['cost_per_unique_click'], "Impressions": campaign_data[0]['impressions'] } response.append(campaign_dict) except: pass except: pass return {'headers': headers, 'rows': response}
def test_normal(self): result = self.sample.create_lead_ad( account_id=self.account_id, name="My Awesome Lead Ad", page_id=self.page_id, form_id=self.form_id, optimization_goal='LEAD_GENERATION', billing_event='IMPRESSIONS', bid_amount=100, daily_budget=1000, targeting=self.mobile_targeting, image_path=self.images[0], message="My message", link="fb.me/fmd", caption="My Caption", description="My description", cta_type="SIGN_UP") self.assertIn('image_hash', result) self.assertIn('campaign_id', result) self.assertIn('adset_id', result) self.assertIn('creative_id', result) self.assertIn('ad_id', result) self.campaign = Campaign() self.campaign[Campaign.Field.id] = result['campaign_id'] self.campaign.remote_read() self.assertEqual(self.campaign.get_id(), result['campaign_id'])
def tearDown(self): super(TieredLookalikeTestCase, self).tearDown() if hasattr(self, 'results'): campaign_id = str(self.results['adsets'][0]['campaign_id']) campaign = Campaign(campaign_id) campaign.remote_delete() if hasattr(self, 'tiered_lookalikes'): for lookalike in self.tiered_lookalikes: lookalike.remote_delete()
def create_campaign(self, account_id, name): """ Step 2: create a campaign. See [Campaign][1] for further details on the API used here. [1]: https://developers.facebook.com/docs/marketing-api/adcampaign """ campaign = Campaign(parent_id=account_id) campaign[Campaign.Field.name] = name campaign[Campaign.Field.objective] = ( Campaign.Objective.mobile_app_installs) campaign.remote_create(params={'status': Campaign.Status.paused}) return campaign[Campaign.Field.id]
def get_campaign_stats(campaign): campaign = Campaign(campaign) params = { 'data_preset': 'lifetime', 'fields': [ Insights.Field.impressions, Insights.Field.unique_clicks, Insights.Field.reach, Insights.Field.cpm, Insights.Field.spend, ] } data_set = campaign.get_insights(params=params) return data_set[0]
def get_ad_campaign(self, cache, campaign_id): """ Get the ad campaign. As some ad sets being analyzed belong to the same ad campaign, a caching is used to reduce the API calls. Params: * `cache` ad campaigns obtained already. * `campaign_id` the id of the ad campaign to be queried out. """ if (cache.get(campaign_id) is None): campaign = Campaign(fbid=campaign_id) campaign.remote_read(fields=[ Campaign.Field.name, Campaign.Field.configured_status, Campaign.Field.objective, ]) cache[campaign_id] = campaign return cache.get(campaign_id)
def create_lead_ad( self, account_id, name, page_id, form_id, optimization_goal, billing_event, bid_amount, daily_budget, targeting, image_path, message, link, caption, description, cta_type='SIGN_UP', ): """ Create Campaign """ campaign = Campaign(parent_id=account_id) campaign[Campaign.Field.name] = name + ' Campaign' campaign[Campaign.Field.objective] = \ Campaign.Objective.lead_generation campaign[Campaign.Field.buying_type] = \ Campaign.BuyingType.auction campaign.remote_create(params={'status': Campaign.Status.paused}) """ Create AdSet """ adset = AdSet(parent_id=account_id) adset[AdSet.Field.campaign_id] = campaign.get_id_assured() adset[AdSet.Field.name] = name + ' AdSet' adset[AdSet.Field.promoted_object] = { 'page_id': page_id, } adset[AdSet.Field.optimization_goal] = optimization_goal adset[AdSet.Field.billing_event] = billing_event adset[AdSet.Field.bid_amount] = bid_amount adset[AdSet.Field.daily_budget] = daily_budget adset[AdSet.Field.targeting] = targeting adset.remote_create() """ Image """ image = AdImage(parent_id=account_id) image[AdImage.Field.filename] = image_path image.remote_create() image_hash = image[AdImage.Field.hash] """ Create Creative """ link_data = LinkData() link_data[LinkData.Field.message] = message link_data[LinkData.Field.link] = link link_data[LinkData.Field.image_hash] = image_hash link_data[LinkData.Field.caption] = caption link_data[LinkData.Field.description] = description link_data[LinkData.Field.call_to_action] = { 'type': cta_type, 'value': { 'lead_gen_form_id': form_id, }, } object_story_spec = ObjectStorySpec() object_story_spec[ObjectStorySpec.Field.page_id] = page_id object_story_spec[ObjectStorySpec.Field.link_data] = link_data creative = AdCreative(parent_id=account_id) creative[AdCreative.Field.name] = name + ' Creative' creative[AdCreative.Field.object_story_spec] = object_story_spec creative.remote_create() """ Create Ad """ ad = Ad(parent_id=account_id) ad[Ad.Field.name] = name ad[Ad.Field.adset_id] = adset.get_id_assured() ad[Ad.Field.creative] = {'creative_id': str(creative.get_id_assured())} ad.remote_create() return { 'image_hash': image_hash, 'campaign_id': campaign['id'], 'adset_id': adset['id'], 'creative_id': creative['id'], 'ad_id': ad['id'], }
def create_carousel_ad( self, accountid, page_id, site_link, caption, message, optimization_goal, billing_event, bid_amount, name, targeting, products, call_to_action_type=None, ): """ There are 5 steps in this sample: 1. Create a campaign 2. Create an ad set 3. For each product: a. Upload the product's image and get an image hash b. Create a story attachment using the product's creative elements 4. Prepare the ad creative 5. Create the ad using the ad creative """ daily_budget = 10000 """ Step 1: Create new campaign with WEBSITE_CLICKS objective See [Campaign Group](https://developers.facebook.com/docs/marketing-api/reference/ad-campaign-group) for further details on the API used here. """ campaign = Campaign(parent_id=accountid) campaign[Campaign.Field.name] = name + ' Campaign' campaign[Campaign.Field.objective] = \ Campaign.Objective.link_clicks campaign.remote_create(params={'status': Campaign.Status.paused}) """ Step 2: Create AdSet using specified optimization goal, billing event and bid. See [AdSet](https://developers.facebook.com/docs/marketing-api/reference/ad-campaign) for further details on the API used here. """ ad_set = AdSet(parent_id=accountid) ad_set[AdSet.Field.campaign_id] = campaign.get_id_assured() ad_set[AdSet.Field.name] = name + ' AdSet' ad_set[AdSet.Field.optimization_goal] = optimization_goal ad_set[AdSet.Field.billing_event] = billing_event ad_set[AdSet.Field.bid_amount] = bid_amount ad_set[AdSet.Field.daily_budget] = daily_budget ad_set[AdSet.Field.targeting] = targeting ad_set.remote_create() story_attachments = [] """ Step 3: Upload images and get image hashes for use in ad creative. See [Ad Image](https://developers.facebook.com/docs/marketing-api/reference/ad-image#Creating) for further details on the API used here. Then create a new attachment with the product's creative """ call_to_action = { 'type': call_to_action_type, 'value': { 'link': site_link, 'link_caption': call_to_action_type, } } if call_to_action_type else None for product in products: img = AdImage(parent_id=accountid) img[AdImage.Field.filename] = product['image_path'] img.remote_create() image_hash = img.get_hash() attachment = AttachmentData() attachment[AttachmentData.Field.link] = product['link'] attachment[AttachmentData.Field.name] = product['name'] attachment[ AttachmentData.Field.description] = product['description'] attachment[AttachmentData.Field.image_hash] = image_hash if call_to_action: attachment[ AttachmentData.Field.call_to_action] = call_to_action story_attachments.append(attachment) """ Step 4: Prepare the ad creative including link information Note that here we specify multi_share_optimized = True this means you can add up to 10 products and Facebook will automatically select the best performing 5 to show in the ad. Facebook will also select the best ordering of those products. """ link = LinkData() link[link.Field.link] = site_link link[link.Field.caption] = caption link[link.Field.child_attachments] = story_attachments link[link.Field.multi_share_optimized] = True link[link.Field.call_to_action] = call_to_action story = ObjectStorySpec() story[story.Field.page_id] = page_id story[story.Field.link_data] = link creative = AdCreative() creative[AdCreative.Field.name] = name + ' Creative' creative[AdCreative.Field.object_story_spec] = story """ Step 5: Create the ad using the above creative """ ad = Ad(parent_id=accountid) ad[Ad.Field.name] = name + ' Ad' ad[Ad.Field.adset_id] = ad_set.get_id_assured() ad[Ad.Field.creative] = creative ad.remote_create(params={'status': Ad.Status.paused}) return (campaign, ad_set, ad)
def get_report(request): Campaign.objects.all().delete() Account.objects.all().delete() #check if user is authenticated if not request.user.is_authenticated(): return render(request, 'account/login.html') #setting the user information my_app_id = '1604519246476149' my_app_secret = '5a93aee73f1d2856dd542f53e268e483' current_user = SocialAccount.objects.get(user=request.user, provider='facebook') current_token = SocialToken.objects.get(account=current_user) my_access_token = current_token.token FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token) me = objects.AdUser(fbid='me') my_accounts = list(me.get_ad_accounts()) if len(my_accounts) == 0: return HttpResponse("no Ad Accounts Exist") index = 0 for current_account in my_accounts: if index == 5: break index = index + 1 current_account.remote_read(fields=[ AdAccount.Field.account_id, AdAccount.Field.name, AdAccount.Field.amount_spent, ]) account_model = Account() account_model.account_name = str(current_account[AdAccount.Field.name]) account_model.account_id = str( current_account[AdAccount.Field.account_id]) account_model.account_cost = str( float(current_account[AdAccount.Field.amount_spent]) / 100) account_model.save() ad_campaigns = current_account.get_ad_campaigns() for current_campaign in ad_campaigns: current_campaign.remote_read(fields=[ AdCampaign.Field.name, AdCampaign.Field.status, AdCampaign.Field.id, ]) fields = {'impressions', 'clicks', 'cpc'} data = str(current_campaign.get_insights(fields=fields)) data = '[' + data[12:] try: ast.literal_eval(data) json_string = json.dumps(data) parsed_data = json.loads(data) except: continue campaign_model = Campaign() campaign_model.name = str(current_campaign[AdCampaign.Field.name]) campaign_model.campaign_id = str( current_campaign[AdCampaign.Field.id]) campaign_model.status = str( current_campaign[AdCampaign.Field.status]) campaign_model.clicks = int(parsed_data[0]['clicks']) campaign_model.cpc = float(parsed_data[0]['cpc']) campaign_model.impressions = int(parsed_data[0]['impressions']) campaign_model.account = account_model campaign_model.save() return HttpResponse("Good Humes")
def retrieve_eligible_adsets_for_an( self, accountid, includepaused=False, ): """ This method returns all eligible ad sets that can have audience networked turned on for a given ad account id. Args: accountid: The ad account id (should be of the form act_<act_id>) for which you are running this exercise. inlcudepaused: Boolen parameter to make your method consider ad sets with paused states (PAUSED & CAMPAIGN_PAUSED). Checks only ACTIVE by default. Returns: List of ad set objects (if found satisfying the conditions) or an empty list. """ # use accountid to retrieve all active adsets account = AdAccount(accountid) adsetfields = [ AdSet.Field.id, AdSet.Field.name, AdSet.Field.campaign_id, AdSet.Field.targeting, AdSet.Field.effective_status, ] adsets = list(account.get_ad_sets(fields=adsetfields)) # Filter ad sets received by desired status and placement types. # Further filter by campaign objectives listed in the criteria below. # # Ref: https://developers.facebook.com/docs/ # marketing-api/audience-network/v2.5 desired_campaign_status = set(['ACTIVE']) # mostly useful in testing when you don't have active campaigns if includepaused is True: desired_campaign_status.update({'PAUSED', 'CAMPAIGN_PAUSED'}) desired_campaign_objectives = set([ 'MOBILE_APP_INSTALLS', 'MOBILE_APP_ENGAGEMENT', 'LINK_CLICKS', 'CONVERSIONS', 'PRODUCT_CATALOG_SALES', ]) # Hold the result set eligible_adsets = [] for adset in adsets: if adset[AdSet.Field.effective_status] in desired_campaign_status: """ 'devide_platforms', 'publisher_platforms' and 'facebook_positions' could be absent for the default of 'ALL' """ device_platforms = None if TargetingSpecsField.device_platforms in \ adset[AdSet.Field.targeting]: device_platforms = set(adset[AdSet.Field.targeting][ TargetingSpecsField.device_platforms]) publisher_platforms = None if TargetingSpecsField.publisher_platforms in \ adset[AdSet.Field.targeting]: publisher_platforms = set(adset[AdSet.Field.targeting][ TargetingSpecsField.publisher_platforms]) facebook_positions = None if TargetingSpecsField.facebook_positions in \ adset[AdSet.Field.targeting]: facebook_positions = set(adset[AdSet.Field.targeting][ TargetingSpecsField.facebook_positions]) if ((facebook_positions is None or 'feed' in facebook_positions) and (device_platforms is None or 'mobile' in device_platforms)): if (publisher_platforms is None or 'audience_network' in publisher_platforms): # audience network already enabled, so just pass continue else: campaign = Campaign(adset[AdSet.Field.campaign_id]) campaignfields = [ Campaign.Field.id, Campaign.Field.name, Campaign.Field.effective_status, Campaign.Field.objective, ] campaign = campaign.remote_read(fields=campaignfields) if (campaign[Campaign.Field.objective] in desired_campaign_objectives): eligible_adsets.append(adset) return eligible_adsets
def create_multiple_link_clicks_ads( self, accountid, pageid, name, titles, bodies, urls, image_paths, targeting, optimization_goal, billing_event, bid_amount, daily_budget=None, lifetime_budget=None, start_time=None, end_time=None, ): """ There are 7 steps in this sample: 1. Create a campaign 2. Create an ad set 3. Upload images 4. Make combinations of specified creative elements 5. Prepare an API batch 6. For each creative combination, add a call to the batch to create a new ad 7. Execute API batch Params: * `accountid` is your Facebook AdAccount id * `name` is a string of basename of your ads. * `page` is the Facebook page used to publish the ads * `titles` array of strings of what user will see as ad title * `bodies` array of strings of what user will see as ad body * `image_paths` array of image file paths * `targeting` is a JSON string specifying targeting info of your ad See [Targeting Specs](https://developers.facebook.com/docs/marketing-api/targeting-specs) for details. * `optimization_goal` the optimization goal for the adsets * `billing_event` what you want to pay for * `bid_amount` how much you want to pay per billing event * `daily_budget` is integer number in your currency. E.g., if your currency is USD, dailybudget=1000 says your budget is 1000 USD * `lifetime_budget` lifetime budget for created ads * `start_time` when the campaign should start * `end_time` when the campaign should end """ my_account = AdAccount(fbid=accountid) """ Take different title body url and image paths, create a batch of ads based on the permutation of these elements """ # Check for bad specs if daily_budget is None: if lifetime_budget is None: raise TypeError( 'One of daily_budget or lifetime_budget must be defined.') elif end_time is None: raise TypeError( 'If lifetime_budget is defined, end_time must be defined.') """ Step 1: Create new campaign with WEBSITE_CLICKS objective See [Campaign Group](https://developers.facebook.com/docs/marketing-api/reference/ad-campaign-group) for further details on the API used here. """ campaign = Campaign(parent_id=accountid) campaign[Campaign.Field.name] = name + ' Campaign' campaign[Campaign.Field.objective] = \ Campaign.Objective.link_clicks campaign.remote_create(params={ 'status': Campaign.Status.paused, }) """ Step 2: Create AdSet using specified optimization goal, billing event and bid. See [AdSet](https://developers.facebook.com/docs/marketing-api/reference/ad-campaign) for further details on the API used here. """ # Create ad set ad_set = AdSet(parent_id=accountid) ad_set[AdSet.Field.campaign_id] = campaign.get_id_assured() ad_set[AdSet.Field.name] = name + ' AdSet' ad_set[AdSet.Field.optimization_goal] = optimization_goal ad_set[AdSet.Field.billing_event] = billing_event ad_set[AdSet.Field.bid_amount] = bid_amount 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 ad_set[AdSet.Field.targeting] = targeting ad_set.remote_create() """ Step 3: Upload images and get image hashes for use in ad creative. See [Ad Image](https://developers.facebook.com/docs/marketing-api/reference/ad-image#Creating) for further details on the API used here. """ # Upload the images first one by one image_hashes = [] for image_path in image_paths: img = AdImage(parent_id=accountid) img[AdImage.Field.filename] = image_path img.remote_create() image_hashes.append(img.get_hash()) ADGROUP_BATCH_CREATE_LIMIT = 10 ads_created = [] def callback_failure(response): raise response.error() """ Step 4: Using itertools.product get combinations of creative elements. """ for creative_info_batch in generate_batches( itertools.product(titles, bodies, urls, image_hashes), ADGROUP_BATCH_CREATE_LIMIT): """ Step 5: Create an API batch so we can create all ad creatives with one HTTP request. See [Batch Requests](https://developers.facebook.com/docs/graph-api/making-multiple-requests#simple) for further details on batching API calls. """ api_batch = my_account.get_api_assured().new_batch() for title, body, url, image_hash in creative_info_batch: # Create the ad """ Step 6: For each combination of creative elements, add to the batch an API call to create a new Ad and specify the creative inline. See [AdGroup](https://developers.facebook.com/docs/marketing-api/adgroup/) for further details on creating Ads. """ ad = Ad(parent_id=accountid) ad[Ad.Field.name] = name + ' Ad' ad[Ad.Field.adset_id] = ad_set.get_id_assured() ad[Ad.Field.creative] = { AdCreative.Field.object_story_spec: { "page_id": pageid, "link_data": { "message": body, "link": url, "caption": title, "image_hash": image_hash } }, } ad.remote_create(batch=api_batch, failure=callback_failure) ads_created.append(ad) """ Step 7: Execute the batched API calls See [Batch Requests](https://developers.facebook.com/docs/graph-api/making-multiple-requests#simple) for further details on batching API calls. """ api_batch.execute() return [campaign, ad_set, ads_created]
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 = { TargetingSpecsField.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