def __init__(self, account_id: str, access_token: str): self._account_id = account_id # design flaw in MyFacebookAdsApi requires such strange set of new default api instance self.api = MyFacebookAdsApi.init(access_token=access_token, crash_log=False) FacebookAdsApi.set_default_api(self.api)
from functools import partial 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() ### Setup session and api objects session = FacebookSession( config['app_id'], config['app_secret'], config['access_token'], ) api = FacebookAdsApi(session) if __name__ == '__main__': FacebookAdsApi.set_default_api(api) # Get my account (first account associated with the user associated with the # session of the default api) my_account = AdAccount.get_my_account() print('**** Pausing all active ad campaigns...') active_campaigns_iterator = my_account.get_ad_campaigns( fields=[ AdCampaign.Field.status, AdCampaign.Field.name, ],
import os 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() ### Setup session and api objects session = FacebookSession( config['app_id'], config['app_secret'], config['access_token'], ) api = FacebookAdsApi(session) if __name__ == '__main__': FacebookAdsApi.set_default_api(api) # Get my account (first account associated with the user associated with the # session of the default api) my_account = AdAccount.get_my_account() ##################### # Create multiple ads ##################### print('**** Creating multiple ads...') # Create my ads (will use batch calling)
Function of the script: Pull in the potential audience size for each Facebook Ad Set. How it works: 1. Export selected campaigns on ads manager to excel. 2. Remove Duplicates on an ad set ID level, so each row will be a unique ad set. 3. Fill in the app ids, app secret and access token. (To authenticate you have access to the account) 4. Run the script (assume Python 3.6 is installed), drag and drop the exported excel file, press enter. 5. The file will run and populate on to the excel file. 6. More instruction will be on the Excel file. ''' my_app_id = '<INSERT APP AD>' my_app_secret = '<INSERT APP SECRET' my_access_token = '<INSERT ACCESS TOKEN>' FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token) filepath = input("Input file path: ") filepath = filepath.replace("'", "") filename = input("Insert Beat Name: ") workbook = load_workbook(filepath) sheet = workbook.active script_fp = os.path.dirname(__file__) templatefolder = r"/THE TEMPLATE/" excelfile = "ReachEstimateTemplatev2.xlsx" templatefilepath = "".join([script_fp, templatefolder, excelfile]) export_wb = load_workbook(templatefilepath)
config_filename = os.path.join(this_dir, 'config.json') config_file = open(config_filename) config = json.load(config_file) config_file.close() ### Setup session and api objects session = FacebookSession( config['app_id'], config['app_secret'], config['access_token'], ) api = FacebookAdsApi(session) if __name__ == '__main__': FacebookAdsApi.set_default_api(api) # Get my account (first account associated with the user associated with the # session of the default api) my_account = AdAccount.get_my_account() print('**** Creating ad...') # Create my ad my_ad = ad_creation_utils.create_website_clicks_ad( account=my_account, name="Visit Seattle", country='US', title="Visit Seattle", # How it looks
from facebook_business.adobjects.adset import AdSet from facebook_business.adobjects.campaign import Campaign from facebook_business.adobjects.adcreative import AdCreative import os fbtoken = os.getenv('FB_GA_TOKEN') fbappkey = os.getenv('FB_GA_APPKEY') job = '999_Test_Job' videos = [ '2926386880739508', '506640253392515', '485759768730516' ] FacebookAdsApi.init('2389713357935376', fbappkey, fbtoken) fbact = AdAccount('act_659750741197329') template = Campaign('23844416049080002') template = template.api_get(fields=[Campaign.Field.name]) cr = template.create_copy(fields=None, params={'deep_copy': True}) c = Campaign(cr._data['copied_campaign_id']) c = c.api_get(fields=[Campaign.Field.id, Campaign.Field.name]) cname = template[Campaign.Field.name] + job c.api_update(params={Campaign.Field.name: cname}) adsets = c.get_ad_sets() adsett = adsets[0]
pp = pprint.PrettyPrinter(indent=4) 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() ### Setup session and api objects session = FacebookSession( config['app_id'], config['app_secret'], config['access_token'], ) api = FacebookAdsApi(session) if __name__ == '__main__': FacebookAdsApi.set_default_api(api) print('\n\n\n********** Reading objects example. **********\n') ### Setup user and read the object from the server me = AdUser(fbid='me') ### Read user permissions print('>>> Reading permissions field of user:') pp.pprint(me.remote_read(fields=[AdUser.Field.permissions])) ### Get first account connected to the user my_account = me.get_ad_account()
pp = pprint.PrettyPrinter(indent=4) 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() ### Setup session and api objects session = FacebookSession( config['app_id'], config['app_secret'], config['access_token'], ) api = FacebookAdsApi(session) class Command(BaseCommand): help = 'Gets Campaign data from Facebook' # def add_arguments(self, parser): # parser.add_argument('insta', nargs='+', type=str) def handle(self, *args, **kwargs): FacebookAdsApi.set_default_api(api) # print('\n\n\n********** Reading objects example. **********\n') # Pro tip: Use list(me.get_ad_accounts()) to make a list out of # all the elements out of the iterator
def handle(self, *args, **kwargs): FacebookAdsApi.set_default_api(api) # print('\n\n\n********** Reading objects example. **********\n') # Pro tip: Use list(me.get_ad_accounts()) to make a list out of # all the elements out of the iterator business_account = AdAccount(config['act_id']) business_account.remote_read(fields=[AdAccount.Field.tos_accepted]) camp = business_account.get_campaigns() # for attr, value in camp.__dict__.items(): # print(attr, 'campaign_name') for campaign in camp: get_camp_insights = campaign.get_insights(fields=[ 'campaign_name', 'impressions', 'clicks', 'unique_clicks', 'actions', 'spend', 'cpm', ]) # print("Testing "+str(get_camp_insights)) if (bool(get_camp_insights) == True): client = get_camp_insights[0]['campaign_name'] # print(get_camp_insights) imp_ressions = get_camp_insights[0]['impressions'] spend = get_camp_insights[0]['spend'] date_start = get_camp_insights[0]['date_start'] date_stop = get_camp_insights[0]['date_stop'] client = client.replace(' - ', '@@') split_array = client.split('@@') damo = date.today() bill_month = '{:02}'.format(damo.month) bill_year = '{:04}'.format(damo.year) bill_date = '0' for value in split_array: if 'BD' in value: if len(value) == 3 or len(value) == 4: bill_date = value.replace('BD', '') # bill_date = bill_year+'-'+bill_month+'-'+bill_date if bill_month == '02' and bill_date > '28': bill_date = '28' bill_date = bill_year + '-' + bill_month + '-' + bill_date else: continue if split_array[0][1:5] == 'TEST': client_id = '9876' else: client_id = (re.findall(r'\d+', client.split('@@')[0])[0]) client_name = (client.split('@@')[0].split('] ')[1].strip()) try: if 'for ' in client: target_impressions = int( (re.findall(r'\d+', client.split('for ')[1])[0])) else: target_impressions = int( (re.findall(r'\d+', client.split('@@')[1])[0])) except: target_impressions = 0 status = 'na' days = (datetime.now().date() - datetime.strptime(bill_date, "%Y-%m-%d").date()).days if days < 0: bill_datea = datetime.strptime(bill_date, "%Y-%m-%d") bill_dateaa = bill_datea + relativedelta(months=-1) days = (datetime.now() - bill_dateaa).days days_range_dict = { 15: 10, 16: 20, 17: 30, 18: 40, 19: 50, 20: 60, 21: 70, 22: 80, 23: 90, 24: 100 } if target_impressions > 0: get_percent = (int(imp_ressions) / target_impressions) * 100 #print(days_range_dict) if get_percent > 250: status = 'co' elif get_percent >= 120 and get_percent <= 250: status = 'ov' elif days > 17 and days < 25: if get_percent < 120 and days > 14 and days < 25: if (days_range_dict[days]): status = 'ot' else: status = 'cu' else: status = 'cu' elif get_percent < 120 and days > 14 and days < 25: if (days_range_dict[days]): status = 'ot' elif days > 14 and days < 18: if (days_range_dict[days]): status = 'un' elif days > 9 and days < 15: if imp_ressions == 0: status = 'un' else: pass else: get_percent = 0 pass # print(status) app_tag = 'resultli' data = { 'spend': spend, 'target_impressions': target_impressions, 'date_start': date_start, 'date_stop': date_stop, 'impressions': imp_ressions, 'client_id': client_id, 'client_name': client_name, 'bill_date': bill_date, 'percentage': get_percent, 'status': status, 'app_tag': app_tag, 'days': days } print(data)
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 = AdPreview.AdFormat.instagram_standard creative_spec = { AdCreative.Field.instagram_actor_id: jasper_ig_account, AdCreative.Field.object_story_id: story_id, } params = { 'creative': creative_spec, '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))
import pprint import sys pp = pprint.pprint this_dir = os.path.dirname(__file__) 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] + ': ' +
pp = pprint.pprint this_dir = os.path.dirname(__file__) 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] + ': ' +
from facebook_business.adobjects.advideo import AdVideo config_filename = os.path.join(sdk_path, './config.json') config_file = open(config_filename) config = json.load(config_file) config_file.close() ### Setup session and api objects session = FacebookSession( config['app_id'], config['app_secret'], config['access_token'], ) FacebookAdsApi.set_default_api(FacebookAdsApi(session)) if __name__ == '__main__': # create video object video = AdVideo(parent_id=config['act_id']) video_path = os.path.join(os.path.dirname(__file__), os.pardir, 'facebook_business/test/misc/video.mp4') # set video fields video[AdVideo.Field.filepath] = video_path # remote create video.remote_create() video.waitUntilEncodingReady()
def __init__(self, account_id: str, access_token: str, start_date: str, include_deleted: bool = False): super().__init__() self._api = FacebookAdsApi.init(access_token=access_token) self._account_id = account_id self._start_date = isoparse(start_date) self._include_deleted = include_deleted