def main_impl(): args = utils.parse_args(REQUIRED_CONFIG_KEYS) account_id = args.config['account_id'] access_token = args.config['access_token'] CONFIG.update(args.config) FacebookAdsApi.init(access_token=access_token) user = fb_user.User(fbid='me') accounts = user.get_ad_accounts() account = None for acc in accounts: if acc['account_id'] == account_id: account = acc if not account: raise TapFacebookException( "Couldn't find account with id {}".format(account_id)) if args.discover: do_discover() elif args.properties: catalog = Catalog.from_dict(args.properties) do_sync(account, catalog, args.state) else: LOGGER.info("No properties were selected")
def main_impl(): args = utils.parse_args(REQUIRED_CONFIG_KEYS) account_id = args.config['account_id'] account_ids = account_id.split(",") access_token = args.config['access_token'] CONFIG.update(args.config) global RESULT_RETURN_LIMIT RESULT_RETURN_LIMIT = CONFIG.get('result_return_limit', RESULT_RETURN_LIMIT) global API API = FacebookAdsApi.init(access_token=access_token) user = fb_user.User(fbid='me') accounts = user.get_ad_accounts() selected_accounts = [] for acc in accounts: if acc['account_id'] in account_ids: selected_accounts.append(acc) if len(selected_accounts) < 1: raise TapFacebookException( "Couldn't find account with id {}".format(account_id)) if args.discover: do_discover() elif args.properties: catalog = Catalog.from_dict(args.properties) for account in selected_accounts: singer.logger.log_info("syncing account " + str(account["account_id"])) do_sync(account, catalog, args.state) else: LOGGER.info("No properties were selected")
def __init__( self, account_id: str, access_token: str, start_date: str, include_deleted: bool = False, insights_lookback_window: int = 28 ): self._account_id = account_id self._start_date = pendulum.parse(start_date) self._insights_lookback_window = insights_lookback_window self._api = FacebookAdsApi.init(access_token=access_token) self._apis = { "campaigns": CampaignAPI(self, include_deleted=include_deleted), "adsets": AdSetsAPI(self, include_deleted=include_deleted), "ads": AdsAPI(self, include_deleted=include_deleted), "adcreatives": AdCreativeAPI(self), "ads_insights": AdsInsightAPI(self, start_date=self._start_date, buffer_days=self._insights_lookback_window), "ads_insights_age_and_gender": AdsInsightAPI( self, start_date=self._start_date, breakdowns=["age", "gender"], buffer_days=self._insights_lookback_window ), "ads_insights_country": AdsInsightAPI( self, start_date=self._start_date, breakdowns=["country"], buffer_days=self._insights_lookback_window ), "ads_insights_region": AdsInsightAPI( self, start_date=self._start_date, breakdowns=["region"], buffer_days=self._insights_lookback_window ), "ads_insights_dma": AdsInsightAPI( self, start_date=self._start_date, breakdowns=["dma"], buffer_days=self._insights_lookback_window ), "ads_insights_platform_and_device": AdsInsightAPI( self, start_date=self._start_date, breakdowns=["publisher_platform", "platform_position", "impression_device"], buffer_days=self._insights_lookback_window, ), } super().__init__()
def main_impl(): args = parse_args(REQUIRED_CONFIG_KEYS) account_id = args.config['account_id'] access_token = args.config['access_token'] global auth auth = [account_id, access_token] CONFIG.update(args.config) global RESULT_RETURN_LIMIT RESULT_RETURN_LIMIT = CONFIG.get('result_return_limit', RESULT_RETURN_LIMIT) global API API = FacebookAdsApi.init(access_token=access_token) user = fb_user.User(fbid='me') accounts = user.get_ad_accounts() account = None for acc in accounts: if acc['account_id'] == account_id: account = acc if not account: raise TapFacebookException("Couldn't find account with id {}".format(account_id)) if args.discover: do_discover(args.select_all) elif args.properties: catalog = Catalog.from_dict(args.properties) do_sync(account, catalog, args.state) elif args.catalog: do_sync(account, args.catalog, args.state) else: LOGGER.info("No properties were selected")
def test_retries_and_good_response(self): """Facebook has a class called `FacebookResponse` and it is created from a `requests.Response`. Some `facebook_business` functions depend on calling `FacebookResponse.json()`, which sometimes returns a string instead of a dictionary. This leads to a `TypeError("string indices must be integers")` and we want to retry these. This test will return a "bad" API response the first time the function is called, then a "good" response that can be `json.loads()`. We check that the resulting object has our expected value in it. """ FacebookAdsApi.init(access_token='access_token') expected_value = {"foo": "bar"} account = AdAccount('abc_123') patcher = patch('requests.Session.request') mocked_request = patcher.start() mocked_bad_response = Response() mocked_bad_response._content = b'images' mocked_good_response = Response() # Convert our expected value into a JSON string, and then into bytes byte_string = json.dumps(expected_value).encode() mocked_good_response._content = byte_string mocked_request.side_effect = [ mocked_bad_response, mocked_good_response ] ad_creative_object = AdCreative('', account, '', '') with self.assertRaises(TypeError): ad_creative_object.account.get_ad_creatives(params={}) list_response = ad_creative_object.account.get_ad_creatives(params={}) actual_response = list_response.get_one() self.assertDictEqual(expected_value, actual_response._json) # Clean up tests patcher.stop()
def __init__(self, access_token: str, start_date: str): self._start_date = pendulum.parse(start_date) self._api = FacebookAdsApi.init(access_token=access_token) self._apis = { "media": MediaAPI(self), "stories": StoriesAPI(self), "users": UsersAPI(self), "user_lifetime_insights": UserLifetimeInsightsAPI(self), "user_insights": UserInsightsAPI(self), "media_insights": MediaInsightsAPI(self), "story_insights": StoriesInsightsAPI(self), } super().__init__()
def __init__(self, account_id: str, access_token: str, start_date: str): self._account_id = account_id self._start_date = pendulum.parse(start_date) self._api = FacebookAdsApi.init(access_token=access_token) self._apis = { "campaigns": CampaignAPI(self), "adsets": AdSetsAPI(self), "ads": AdsAPI(self), "adcreatives": AdCreativeAPI(self), "ads_insights": AdsInsightAPI(self, start_date=self._start_date), "ads_insights_age_and_gender": AdsInsightAPI(self, start_date=self._start_date, breakdowns=["age", "gender"]), "ads_insights_country": AdsInsightAPI(self, start_date=self._start_date, breakdowns=["country"]), "ads_insights_region": AdsInsightAPI(self, start_date=self._start_date, breakdowns=["region"]), "ads_insights_dma": AdsInsightAPI(self, start_date=self._start_date, breakdowns=["dma"]), "ads_insights_platform_and_device": AdsInsightAPI( self, start_date=self._start_date, breakdowns=["publisher_platform", "platform_position", "impression_device"] ), } super().__init__()
def main_impl(): try: args = utils.parse_args(REQUIRED_CONFIG_KEYS) account_id = args.config['account_id'] access_token = args.config['access_token'] CONFIG.update(args.config) global RESULT_RETURN_LIMIT RESULT_RETURN_LIMIT = CONFIG.get('result_return_limit', RESULT_RETURN_LIMIT) global API API = FacebookAdsApi.init(access_token=access_token) user = fb_user.User(fbid='me') accounts = user.get_ad_accounts() account = None for acc in accounts: if acc['account_id'] == account_id: account = acc if not account: raise SingerConfigurationError( "Couldn't find account with id {}".format(account_id)) except FacebookError as fb_error: raise_from(SingerConfigurationError, fb_error) if args.discover: try: do_discover() except FacebookError as fb_error: raise_from(SingerDiscoveryError, fb_error) elif args.properties: catalog = Catalog.from_dict(args.properties) try: do_sync(account, catalog, args.state) except FacebookError as fb_error: raise_from(SingerSyncError, fb_error) else: LOGGER.info("No properties were selected")
def __init__(self, access_token: str): self._api = FacebookAdsApi.init(access_token=access_token) # 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)
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)
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]
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] + ': ' +
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