def get_ads_insight(self, account_id, report_date): """ Pull insights from the Insight edge and return an array of insight report Params: * `account_id` is your Facebook AdAccount id * `report_date` is the date for the insight report For more information see the [Ads Insights doc]( https://developers.facebook.com/docs/marketing-api/insights-api) """ ad_account = AdAccount(fbid=account_id) limit = 10 fields = [ 'campaign_name', 'adset_name', 'adset_id', 'impressions', 'website_clicks', 'app_store_clicks', 'deeplink_clicks', 'spend', 'reach', 'actions', 'action_values' ] params = { 'time_range': { 'since': report_date, 'until': report_date }, 'action_attribution_windows': ['28d_click'], 'breakdowns': ['impression_device', 'placement'], 'level': 'adset', 'limit': limit if limit > 0 else None } insights = ad_account.get_insights(fields, params) insights_value = self.get_insights_value(insights, report_date, limit) return insights_value
def export_report_facebook(config): #pull report thru facebook api # Get insights stats for this account id account_id = config[0] param = config[1] count = config[-1] account = AdAccount(account_id) async_job = account.get_insights(params=param, async=True) async_job.remote_read() while async_job[AdReportRun.Field.async_percent_completion] < 100: time.sleep(20) print(AdReportRun.Field.async_percent_completion) async_job.remote_read() #print(async_job) #read file in bulk #pd.read_csv("""https://www.facebook.com/ads/ads_insights/export_report/?report_run_id=%s"""%async_job['report_run_id']+"&name=myreport&format=csv&access_token=" + my_access_token,chunksize=10**5) download_address = """https://www.facebook.com/ads/ads_insights/export_report/?report_run_id=%s""" % async_job[ 'report_run_id'] + "&format=csv&access_token=" + my_access_token chunksize = 10**5 downloadpath = path + "\\raw_data\\" + subdirectory for chunk in pd.read_csv(download_address, chunksize=chunksize): chunk.ix[chunk["Placement"] == 'Instagram Feed on Mobile Devices', "Placement"] = 'Instagram' chunk.ix[chunk["Placement"] != 'Instagram', "Placement"] = 'Facebook' chunk = chunk[[ 'Reporting Starts', 'Reporting Ends', "Placement", 'Campaign Name', 'Ad Name', 'Ad Set Name', 'Clicks (All)', 'Impressions', 'Amount Spent (USD)', "Website Purchases" ]] chunk.to_csv(downloadpath + "\\facebook_%s.csv" % (count), index=False)
def __init__(self, account=None, table='customers'): FacebookAdsApi.set_default_api(self.__api) if account: self._account = 'act_{}'.format(account) self.__api.set_default_account_id = self._account self._audiences = AdAccount(self._account).get_custom_audiences( fields=[CustomAudience.Field.name, CustomAudience.Field.id]) self._responses = []
def create_ads_pixel(): account = AdAccount(test_config.account_id) pixel = account.get_ads_pixels([AdsPixel.Field.code]) if pixel is None: pixel = AdsPixel(parent_id=test_config.account_id) pixel[AdsPixel.Field.name] = unique_name('Test Pixel') pixel.remote_create() return pixel
def estimate( self, account_id, product_set_id, targeting_spec, ): """ This function will estimate product audience of `product_set_id`, defined with `targeting_spec`, in the context of ad account `account_id`. You need to ensure that ad account and product set are belong to same business, otherwise probably we will get invalid response or zero audience from Facebook. Params: * `account_id`: The ad account id to use in estimation, in format of `act_xxxxxx`. * `product_set_id`: The product set id to use in estimation. * `targeting_spec`: The product audience targeting spec without `product_set_id` as we will set it in code. Please check here for how to define product audience rules (https://developers.facebook.com/docs/marketing-api/dynamic-product-ads/product-audiences, step 3). """ adaccount = AdAccount(account_id) ts = copy.deepcopy(targeting_spec) ts['product_set_id'] = product_set_id targeting_spec = {'product_audience_specs': [ts]} params = { 'currency': 'USD', 'optimize_for': ReachEstimate.OptimizeFor.link_clicks, 'targeting_spec': targeting_spec, } reachestimates = adaccount.get_reach_estimate(params=params) return reachestimates.get_one()
def get_ad_sets(self, account_id, include_archived, limit): """ Retrieves and displays a list of ad sets of a given account, and analyze how likely a similar ad for Instagram can be created. Params: * `account_id` is your Facebook Ad Account id. * `include_archived` specifies whether archived ad sets should be analyzed. * `limit` is how many ad sets to analyze. This script will analyze the first `limit` ad sets as in the response, not including those which use Instagram placement already. The more this limit is, the longer it takes to run. If you run the script directly and are willing to wait for a while, you can drop the lines of code around it. For more information see the [Instagram Ads document]( https://developers.facebook.com/docs/marketing-api/guides/instagramads/) """ locale.setlocale(locale.LC_ALL, '') if include_archived: params = { 'limit': limit, AdSet.Field.configured_status: [ 'PENDING', 'ACTIVE', 'PAUSED', 'PENDING_REVIEW', 'DISAPPROVED', 'PREAPPROVED', 'PENDING_BILLING_INFO', 'CAMPAIGN_PAUSED', 'CAMPAIGN_GROUP_PAUSED', 'ARCHIVED' ], } else: params = {'limit': limit} account = AdAccount(account_id) ad_sets = account.get_ad_sets(fields=[ AdSet.Field.id, AdSet.Field.campaign_id, AdSet.Field.name, AdSet.Field.configured_status, AdSet.Field.targeting, ], params=params) cache = {} count = 0 results = [] for ad_set in ad_sets: if count >= limit: break count += 1 result = {} result['id'] = ad_set['id'] result['name'] = ad_set['name'] logger.error(ad_set) # Get targeting from ad set targeting = ad_set.get(AdSet.Field.targeting, None) logger.error(targeting) if targeting is not None: publisher_platforms = targeting.get('publisher_platforms', None) pp_str = '' if publisher_platforms is None: result['publisher_platforms'] = '<li>DEFAULT</li>' else: for pp in publisher_platforms: pp_str += ('<li>' + self.translate_placement_publisher( str(pp)) + '</li>') result['publisher_platforms'] = pp_str params = { 'currency': 'USD', 'targeting_spec': targeting, 'optimize_for': AdSet.OptimizationGoal.impressions, } if publisher_platforms is not None and "instagram" in \ publisher_platforms: count -= 1 continue reach_fb = account.get_reach_estimate(params=params)[0].get( 'users', 0) targeting['publisher_platforms'] = ["instagram"] targeting['facebook_positions'] = None params = { 'currency': 'USD', 'targeting_spec': targeting, 'optimize_for': AdSet.OptimizationGoal.impressions, } reach_ig = account.get_reach_estimate(params=params)[0].get( 'users', 0) self.add_check_result(result, self.check_audience(reach_fb, reach_ig)) result["audience"] = reach_ig * 100 / reach_fb result["ig_audience"] = locale.format("%d", reach_ig, grouping=True) # Get objective and status from Campaign campaign_id = ad_set[AdSet.Field.campaign_id] campaign = self.get_ad_campaign(cache, campaign_id) result["c_objective"] = \ campaign[Campaign.Field.objective].replace("_", " ") result["c_status"] = campaign[Campaign.Field.configured_status] check = self.check_objective(result["c_objective"]) if check['eligibility'] == 5: result['objective_supported'] = 1 elif check['eligibility'] == 1: result['objective_supported'] = 0 else: result['objective_supported'] = 2 self.add_check_result(result, check) # Get creative and check the media if campaign[Campaign.Field.objective] == 'PRODUCT_CATALOG_SALES': result['preview_url'] = \ 'Images from product catalog are not supported.' results.append(result) result['creative_ready'] = False continue creatives = ad_set.get_ad_creatives([ AdCreative.Field.object_story_id, ]) result['creative_ready'] = False if not creatives: comment = 'No creative found in this ad set.' self.add_check_result(result, { "eligibility": 3, }) result['preview_url'] = comment results.append(result) continue creative = creatives[0] story_id = creative.get(AdCreative.Field.object_story_id, 0) if story_id == 0: comment = 'No post fround in the first creative of this ad set.' self.add_check_result(result, { "eligibility": 3, }) result['preview_url'] = comment results.append(result) continue # Check whether the creative's post is IG ready try: # This Graph API call is not a part of Ads API thus no SDK post = FacebookAdsApi.get_default_api().call( 'GET', (story_id, ), params={ 'fields': 'is_instagram_eligible,child_attachments' }, ) post_ig_eligible = post.json()['is_instagram_eligible'] except FacebookRequestError: post_ig_eligible = False result['creative_ready'] = post_ig_eligible if post_ig_eligible: self.add_check_result(result, { "eligibility": 5, }) # Generate preview # As we do not know which IG account you will use, # just use a hardcoded one for preview. jasper_ig_account = "1023317097692584" ad_format = 'INSTAGRAM_STANDARD' creative_spec = { 'instagram_actor_id': jasper_ig_account, 'object_story_id': story_id, } params = { AdPreview.Field.creative: creative_spec, AdPreview.Field.ad_format: ad_format, } preview = account.get_generate_previews(params=params) result['preview_url'] = preview[0].get_html() \ .replace('width="320"', 'width="340"', 1) else: comment = 'The creative needs to be modified for Instagram.' self.add_check_result(result, { "eligibility": 3, }) result['preview_url'] = comment results.append(result) return list( sorted(results, key=lambda result: result['eligibility'], reverse=True))
from __future__ import print_function from __future__ import unicode_literals ''' This is a template for DocSmith samples in Python. This file will throw an exception. This is used to test facebookads/docs_runner/doc_runner.py when something breaks ''' import sys import os this_dir = os.path.dirname(__file__) repo_dir = os.path.join(this_dir, os.pardir, os.pardir) sys.path.insert(1, repo_dir) from facebookads import bootstrap bootstrap.auth() ''' Example tha intentionally throws an exception to be used as a test for DocExampleTest ''' from facebookads.objects import AdAccount if __name__ == '__main__': ad_account_id = 'invalid_id_1111' print('**** READ AD ACCOUNT ****') ad_account = AdAccount(fbid=ad_account_id) ad_account.remote_read() print(ad_account.remote_read())
stat = "DELETE FROM ad_set_insight WHERE start_date = '{0}' AND end_date = '{1}'".format( report_date, report_date) cur = con.cursor() cur.execute(stat) ########################## function ends ########################## ########################## main ########################## # get all ad campaign from an ad account con = mdb.connect(db_host, db_username, db_password, db_name) with con: deleteAdSetsInsight(con, report_date) for my_ad_account_id in my_ad_account_ids: ad_account = AdAccount(my_ad_account_id) fields = [ 'campaign_group_name', 'campaign_name', 'campaign_id', 'impressions', 'clicks', 'spend', 'reach', 'actions', 'action_values' ] params = { 'time_range': { 'since': report_date, 'until': report_date }, 'action_attribution_windows': ['28d_click'], 'breakdowns': ['impression_device', 'placement'], 'level': 'campaign', 'limit': 100000 }
def audiences(self): return AdAccount(self._account).get_custom_audiences( fields=[CustomAudience.Field.name, CustomAudience.Field.id])
import configparser import os config = configparser.RawConfigParser() this_dir = os.path.dirname(__file__) config_filename = os.path.join(this_dir, 'my_app_session.cfg') with open(config_filename) as config_file: config.readfp(config_file) FacebookAdsApi.init( config.get('Authentication', 'app_id'), config.get('Authentication', 'app_secret'), config.get('Authentication', 'access_token'), ) if __name__ == '__main__': my_account = AdAccount('act_<AD_ACCOUNT_ID>') # create video object video = AdVideo(parent_id=my_account.get_id_assured()) # set video fields video[AdVideo.Field.filepath] = os.path.join(this_dir, 'test_video.mp4') # remove create video.remote_create() video.waitUntilEncodingReady() print(video)
config_filename = os.path.join(this_dir, 'config.json') ### Setup session and api objects config_file = open(config_filename) config = json.load(config_file) config_file.close() auth_info = ( config['app_id'], config['app_secret'], config['access_token']) FacebookAdsApi.init(*auth_info) ### Get account from config file my_account = AdAccount(config['act_id']) def ListCustomAudiences(**kwargs): audiences = my_account.get_custom_audiences(fields=[ CustomAudience.Field.name, CustomAudience.Field.description]) if audiences: print(">>> Account") print(my_account[CustomAudience.Field.id]) print(">>> Audiences") for audience in audiences: print(audience[CustomAudience.Field.id] + ': ' + audience[CustomAudience.Field.name])
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]
item.Spend = cp_insight["spend"] item.StartDate = cp_insight["date_start"] item.EndDate = cp_insight["date_stop"] item.Actived = True item.UserCreated = 1 listaIns.append(item) if mes: FBInsights().SalvarMensalLista(listaIns) else: FBInsights().SalvarLista(listaIns) for config in listaConfig: acc = AdAccount('act_{}'.format(config.MarcaConta.FBContaId)) options = { 1: ReportDiario, 2: ReportMenosXDias, 3: ReportIntervaloDiaADia, 4: ReportIntervaloTotal, 5: ReportIntervaloMensal } data_ini_config = config.StartDate data_fim_config = config.EndDate hoje = datetime.datetime.now().date() for campaign in acc.get_campaigns(fields=[ Campaign.Field.name, Campaign.Field.start_time,
from facebookads.objects import AdAccount, AsyncJob from facebookads.api import FacebookAdsApi import time import os import json this_dir = os.path.dirname(__file__) config_filename = os.path.join(this_dir, 'config.json') config_file = open(config_filename) config = json.load(config_file) config_file.close() api = FacebookAdsApi.init(access_token=config['access_token']) account_id = config['act_id'] account = AdAccount(account_id) # Both Insights and Reportstats i_async_job = account.get_insights(params={'level': 'ad'}, async=True) # Insights while True: job = i_async_job.remote_read() print("Percent done: " + str(job[AsyncJob.Field.async_percent_completion])) time.sleep(1) if job: # print "Done!" break print(i_async_job.get_result())
# _DOC vars [ad_account_id:s] from facebookads.objects import AdsPixel pixel = AdsPixel(parent_id=ad_account_id) pixel[AdsPixel.Field.name] = 'My new Pixel' pixel.remote_create() # _DOC close [ADSPIXEL_CREATE] pixel_id = pixel.get_id() # _DOC open [ADSPIXEL_READ_PIXEL_CODE] # _DOC vars [ad_account_id:s] from facebookads.objects import AdsPixel, AdAccount account = AdAccount(ad_account_id) account.get_ads_pixels(fields=[AdsPixel.Field.code]) # _DOC close [ADSPIXEL_READ_PIXEL_CODE] destination_account_id = config.secondary_account_id business_id = config.business_id # _DOC open [ADSPIXEL_SHARE_ADACCOUNT] # _DOC vars [business_id:s, destination_account_id:s, pixel_id] from facebookads.objects import AdsPixel pixel = AdsPixel(pixel_id) response = pixel.share_pixel(business_id, destination_account_id) print(response.body()) # _DOC close [ADSPIXEL_SHARE_ADACCOUNT]
this_dir = os.path.dirname(__file__) config_filename = os.path.join(this_dir, 'my_app_session.cfg') ### Setup session and api objects with open(config_filename) as config_file: config.readfp(config_file) auth_info = ( config.get('Authentication', 'app_id'), config.get('Authentication', 'app_secret'), config.get('Authentication', 'access_token')) FacebookAdsApi.init(*auth_info) ### Get account from config file my_account = AdAccount('act_' + config.get('Defaults', 'ad_account')) def ListCustomAudiences(**kwargs): audiences = my_account.get_custom_audiences(fields=[ CustomAudience.Field.name, CustomAudience.Field.description]) if(audiences): print(">>> Account") print(my_account[CustomAudience.Field.id]) print(">>> Audiences") for audience in audiences: print(audience[CustomAudience.Field.id] + ': ' + audience[CustomAudience.Field.name])