def create_tiered_lookalikes(self, account_id, name, seed_id, tiers, country): """ Take a seed custom audiences ID and create tiered lookalike audiences """ tiered_audiences = [] for tier in range(1, tiers + 1): lookalike = CustomAudience(parent_id=account_id) lookalike[CustomAudience.Field.name] = \ '{0} LAL {1}'.format(name, tier) lookalike[CustomAudience.Field.origin_audience_id] = seed_id lal_spec = { LookalikeSpec.Field.ratio: tier / 100.0, LookalikeSpec.Field.country: country, } if (tier > 1): lal_spec[ # LookalikeSpec.Field.LookalikeSpec.starting_ratio 'starting_ratio'] = (tier - 1) / 100.0 lookalike[CustomAudience.Field.lookalike_spec] = lal_spec lookalike[CustomAudience.Field.subtype] = \ CustomAudience.Subtype.lookalike lookalike.remote_create() tiered_audiences.append(lookalike) return tiered_audiences
def get_matching_saved_audiences(audiences): aud_list = [] for audience in audiences: audience = CustomAudience(audience) val_aud = audience.remote_read(fields=['targeting']) aud_list.append(val_aud) aud_list = aud_list[0]['targeting'] return aud_list
def add_users_mk(ca_id, users): FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token) audience = CustomAudience(ca_id) schema = [ CustomAudience.Schema.MultiKeySchema.email, ] audience.add_users(schema, users, is_raw=True) return audience.get_id()
def upload_users_to_audience(self, audienceid, users, schema=CustomAudience.Schema.email_hash): """ Adds user emails to an existing audience. The SDK automatically hashes the emails. Only the hash is sent to Facebook. """ audience = CustomAudience(audienceid) return audience.add_users(schema, users)
def delete_users_from_audience(self, audienceid, users, schema=CustomAudience.Schema.email_hash): """ Deletes user emails from an existing audience. The SDK automatically hashes the emails. Only the hash is sent to Facebook. """ audience = CustomAudience(audienceid) return audience.remove_users(schema, users)
def get_ad_sets_for_custom_audience(self, ca_id): """ retrieve adsets which refer the custom audience """ custom_audience = CustomAudience(ca_id) result = custom_audience.get_ads([Ad.Field.adset_id]) adset_ids = [] for ad in result: if ad[Ad.Field.adset_id] not in adset_ids: adset_ids.append(ad[Ad.Field.adset_id]) return adset_ids
def opt_out_user_from_targeting(self, schema, users, is_raw=False, app_ids=None, pre_hashed=None): from facebook_business.adobjects.customaudience import CustomAudience """Opts out users from being targeted by this ad account. Args: schema: A CustomAudience.Schema value users: a list of identites that follow the schema given Returns: Return FacebookResponse object """ return self.get_api_assured().call( 'DELETE', (self.get_id_assured(), 'usersofanyaudience'), params=CustomAudience.format_params(schema, users, is_raw, app_ids, pre_hashed), )
def CreateAudience(): access_token = dict1['my_access_token'] app_secret = dict1['my_app_secret'] app_id = dict1['my_app_id'] id = dict1['account_id'] FacebookAdsApi.init(access_token=access_token) custAud = CustomAudience(parent_id=dict1['account_id']) custAud[CustomAudience.Field.name]= 'My audience' custAud[CustomAudience.Field.description]="My audience description" custAud[Targeting.Field.age_max]=30 custAud[Targeting.Field.age_min]=20 custAud[Targeting.Field.countries]=['US'] custAud[Targeting.Field.connections] = '' custAud[CustomAudience.Field.customer_file_source]='USER_PROVIDED_ONLY' custAud[CustomAudience.Field.subtype] = 'CUSTOM' custAud.remote_create(params={'customer_file_source':0,'subtype':0}) print(custAud) # CreateAudience()
def add_users_mk(ca_id, users): FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token) audience = CustomAudience(ca_id) audience_to_query = list() used_ids = list() for line in users: contact_id, aud_name, email, phone, used = line audience_to_query.append([email, phone]) used_ids.append(contact_id) schema = [ CustomAudience.Schema.MultiKeySchema.email, CustomAudience.Schema.MultiKeySchema.phone ] audience.add_users(schema, audience_to_query, is_raw=True, pre_hashed=True) print(used_ids) return audience.get_id()
def _add_batch_to_custom_audience(app_id, app_secret, access_token, audience_id, schema, batch, added_so_far, total_rows): # Since this method runs in parallel, we need to re-initialize the Facebook API each time # to avoid SSL-related errors. Basically, the FacebookAdsApi python framework isn't # built to run in parallel. FacebookAdsApi.init(app_id, app_secret, access_token) # Note that the FB SDK handles basic normalization and hashing of the data CustomAudience(audience_id).add_users(schema, batch, is_raw=True) logger.info(f"Added {added_so_far+len(batch)}/{total_rows} users to custom audience...")
def delete_custom_audience(self, audience_id): """ Deletes a FB custom audience. `Args:` audience_id: str The ID of the custom audience to delete. """ CustomAudience(audience_id).api_delete()
def add_users_mk(ca_id, name, users): try: FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token) audience = CustomAudience(ca_id) audience_to_query = list() for line in users: if line[0].strip() == name.strip(): aud_name, email, phone = line audience_to_query.append([email, phone]) schema = [ CustomAudience.Schema.MultiKeySchema.email, CustomAudience.Schema.MultiKeySchema.phone ] audience.add_users(schema, audience_to_query, is_raw=True) return audience.get_id() except Exception as e: print(type(e))
def create_lookalike_audience(name: str, spec: Dict[str, Any], source: CustomAudience) -> Instruction: params = { CustomAudience.Field.name: name, CustomAudience.Field.subtype: CustomAudience.Subtype.lookalike, CustomAudience.Field.origin_audience_id: source.get_id(), CustomAudience.Field.lookalike_spec: json.dumps(spec), } return Instruction("custom_audience", "create", params, None)
def create_lals( self, account_id, seed_id, base_name, countries, ratios, ): """ Function that creates the lookalike audiences Params: * `account_id` is your Facebook AdAccount id * `seed_id` is the source custom audience * `base_name` the lookalike audiences will have names in the format of `[base_name] [COUNTRY_CODE] [RATIO]` * `countries` array of country codes * `ratios` array of integers stating the lookalike ratio, from 1 to 10 currency is USD, dailybudget=1000 says your budget is 1000 USD """ lal_created = [] for country, ratio in itertools.product(countries, ratios): # Create the lookalike audience lookalike = CustomAudience(parent_id=account_id) lookalike[CustomAudience.Field.name] = "{0} {1} {2}".format( base_name, country, ratio, ) lookalike[CustomAudience.Field.origin_audience_id] = seed_id lookalike[CustomAudience.Field.lookalike_spec] = { LookalikeSpec.Field.ratio: ratio / 100.0, LookalikeSpec.Field.country: country, } lookalike[CustomAudience.Field.subtype] = \ CustomAudience.Subtype.lookalike lookalike.remote_create() lal_created.append(lookalike) return lal_created
def create_custom_audience(name): try: FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token) my_account = AdAccount(f'act_{ad_account}') audience = CustomAudience(parent_id=my_account.get_id_assured()) audience.update({ CustomAudience.Field.name: name, CustomAudience.Field.subtype: CustomAudience.Subtype.custom, CustomAudience.Field.customer_file_source: CustomAudience.CustomerFileSource.both_user_and_partner_provided }) audience.remote_create() audience = CustomAudience(audience[CustomAudience.Field.id]) return audience['id'] except Exception as e: print(type(e))
def opt_out_user_from_targeting(self, schema, users, is_raw=False, app_ids=None, pre_hashed=None): from facebook_business.adobjects.customaudience import CustomAudience """Opts out users from being targeted by this ad account. Args: schema: A CustomAudience.Schema value users: a list of identites that follow the schema given Returns: Return FacebookResponse object """ return self.get_api_assured().call( 'DELETE', (self.get_id_assured(), 'usersofanyaudience'), params=CustomAudience.format_params(schema, users, is_raw, app_ids, pre_hashed), )
def create_audience(self, accountid, name, description, optoutlink): """ Creates a new custom audience and returns the id. """ audience = CustomAudience(parent_id=accountid) audience.update({ CustomAudience.Field.name: name, CustomAudience.Field.description: description, CustomAudience.Field.opt_out_link: optoutlink, CustomAudience.Field.subtype: CustomAudience.Subtype.custom, }) audience.remote_create() caid = audience[CustomAudience.Field.id] return caid
def create_audience( self, accountid, app_id, name, retention_days, event, period, greater_than=None, less_than=None, ): """ Creates a new custom audience and returns the id. The custom audience is created based on the cumulative values of the events (add to cart or purchase) during the selected period, provided that app is logging the selected app event and passing the right value with them. """ audience = CustomAudience(parent_id=accountid) technique = { 'technique_name': 'absolute', } if greater_than is not None: technique['lower_bound'] = greater_than if less_than is not None: technique['upper_bound'] = less_than rule = { '_application': app_id, '_eventName': event, '_cumulativeRule': { 'metric': 'amount', 'period': period, 'technique': technique, }, } audience.update({ CustomAudience.Field.name: name, CustomAudience.Field.subtype: CustomAudience.Subtype.app, CustomAudience.Field.retention_days: retention_days, CustomAudience.Field.rule: json.dumps(rule), }) audience.remote_create() caid = audience[CustomAudience.Field.id] return caid
def DeleteCustomAudience(audience_id): audience = CustomAudience(audience_id) print('Deleting audience id ' + audience[CustomAudience.Field.id]) return audience.api_delete()
# 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.customaudience import CustomAudience from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<CUSTOM_AUDIENCE_ID>' FacebookAdsApi.init(access_token=access_token) fields = [ ] params = { 'payload': {'schema':['EMAIL','LOOKALIKE_VALUE'],'data':[['9b431636bd164765d63c573c346708846af4f68fe3701a77a3bdd7e7e5166254',44.5],['8cc62c145cd0c6dc444168eaeb1b61b351f9b1809a579cc9b4c9e9d7213a39ee',140],['4eaf70b1f7a797962b9d2a533f122c8039012b31e0a52b34a426729319cb792a',0],['98df8d46f118f8bef552b0ec0a3d729466a912577830212a844b73960777ac56',0.9]]}, } print CustomAudience(id).create_user( 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.customaudience import CustomAudience from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<ID>' FacebookAdsApi.init(access_token=access_token) fields = [] params = { 'name': 'Updated Name for CA', } print CustomAudience(id).update( fields=fields, params=params, )
sourcedir = maindir + '/SOURCE' filelist = (os.listdir(sourcedir)) movedir = maindir + '/ARCHIVE' apipath = maindir + '/SOURCE/' filecount = 0 totalrecords = 0 print('Lets get started') print('Source Directory: ' + sourcedir) print('Archive Directory: ' + movedir) for index, filenamez in enumerate(filelist): #if os.path.splitext(filename)[-1].lower() == '.csv': #3 - create a blank custom audience filename = str(filenamez) print('filename is ' + filename) audience = CustomAudience(parent_id=my_account) audience[CustomAudience.Field.subtype] = CustomAudience.Subtype.custom audience[CustomAudience.Field.name] = filename[:-4] audience[CustomAudience.Field.description] = filename[:-4] audience[CustomAudience.Field.customer_file_source] = 'USER_PROVIDED_ONLY' #the below command actually creates the custom audience audience.remote_create() #remote_create is being depricated soon. Will need to migrate to #AdAccount(api=self._api, fbid=parent_id).create_custom_audience(fields, params, batch, success, failure, pending) #not sure how to use this yet. caid = audience[CustomAudience.Field.id] print('my new custom audience id is: ' + caid) #4 - add records to the blank custom audience.
def add_users_email(ca_id, audience_list): FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token) audience = CustomAudience(ca_id) users = audience_list audience.add_users(CustomAudience.Schema.email_hash, users)
# Facebook. # 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.customaudience import CustomAudience from facebook_business.adobjects.abstractobject import AbstractObject from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<CUSTOM_AUDIENCE_ID>' FacebookAdsApi.init(access_token=access_token) fields = [] params = {} print CustomAudience(id).delete( fields=fields, params=params, )
def DeleteCustomAudience(audience_id): audience = CustomAudience(audience_id) print('Deleting audience id ' + audience[CustomAudience.Field.id]) return audience.api_delete()
def _remove_batch_from_custom_audience(app_id, app_secret, access_token, audience_id, schema, batch, added_so_far, total_rows): FacebookAdsApi.init(app_id, app_secret, access_token) CustomAudience(audience_id).remove_users(schema, batch, is_raw=True) logger.info(f"Removed {added_so_far+len(batch)}/{total_rows} users from custom audience...")
# 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.customaudience import CustomAudience from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<CUSTOM_AUDIENCE_ID>' FacebookAdsApi.init(access_token=access_token) fields = [ 'name', 'rule', ] params = {} print CustomAudience(id).get( fields=fields, params=params, )