def create_ad_set(self, account_id, name, daily_budget, campaign_id, optimization_goal, billing_event, bid_amount, targeting, app_id, app_store_link): """ Step 3: create an ad set in campaign we just created. See [Ad Set][1] for further details on the API used here. [1]: https://developers.facebook.com/docs/marketing-api/adset """ pdata = { AdSet.Field.name: name, AdSet.Field.optimization_goal: optimization_goal, AdSet.Field.billing_event: billing_event, AdSet.Field.bid_amount: bid_amount, AdSet.Field.daily_budget: daily_budget, AdSet.Field.campaign_id: campaign_id, AdSet.Field.promoted_object: { 'application_id': app_id, 'object_store_url': app_store_link }, AdSet.Field.targeting: targeting, } pdata['status'] = AdSet.Status.paused adset = AdSet(parent_id=account_id) adset.remote_create(params=pdata) return adset[AdSet.Field.id]
def get_adsets(adset_id): adset = AdSet(adset_id) fields = [ AdSet.Field.name, ] adset.remote_read(fields=fields) return adset
def copy(self): store_url = config['link_url'][self.param['account']][self.param['os']] link_url = store_url.replace('https://', 'http://') campaign = AdCampaign(self.param['campaign_id']) campaign.remote_read( fields=[ AdCampaign.Field.name ] ) adset = AdSet(self.param['adset_id']) adset.remote_read( fields=[ AdSet.Field.name, AdSet.Field.daily_budget, AdSet.Field.pacing_type, AdSet.Field.promoted_object, AdSet.Field.targeting, AdSet.Field.is_autobid, AdSet.Field.billing_event, AdSet.Field.optimization_goal, AdSet.Field.bid_amount, AdSet.Field.rtb_flag ] ) # pp.pprint(adset) adgroups = adset.get_ad_groups( fields=[ AdGroup.Field.name, AdGroup.Field.creative, AdGroup.Field.tracking_specs, AdGroup.Field.status ], params={ AdGroup.Field.status: ['ACTIVE'] } ) # pp.pprint(adgroups) object_store_url = adset['promoted_object']['object_store_url'] replace_url = object_store_url.replace('https://', 'http://') if link_url != replace_url: return self.different_os_copy(campaign, adset, adgroups) else: return self.same_os_copy(campaign, adset, adgroups)
def create_adset(campaign=create_adcampaign()): adset = AdSet(parent_id=test_config.account_id) adset[AdSet.Field.name] = unique_name('Test Adset') adset[AdSet.Field.campaign_group_id] = campaign.get_id() adset[AdSet.Field.targeting] = { 'geo_locations': { 'countries': ['US'] } } adset[AdSet.Field.optimization_goal] = AdSet.OptimizationGoal.impressions adset[AdSet.Field.billing_event] = AdSet.BillingEvent.impressions adset[AdSet.Field.bid_amount] = 100 adset[AdSet.Field.daily_budget] = 1000 adset.remote_create() atexit.register(remote_delete, adset) return adset
def enable_an_on_adsets(self, adsetids): """ Method that takes a list of ad set ids and enables the audience network placement on them. Please note that this method does not perform any pre-validation check to see whether the ad set passed satisfies the pre-requisites to have audience network enabled. Args: adsetids: List of ad set ids on which you want audience network enabled. Even if you have just one id, pass it as a list. Returns: A list of 'ad set id' vs. 'status' mapping with a further 'message' node whenever there was a failure to update the audience network. Returns an empty list when an empty list or non list element is passed. status 1 is a success. status 0 is a failure. Sample response format: [ {'<ad_set_id_1>': {'status': 1}}, {'<ad_set_id_2>': {'status': 0, 'message': '<exception_msg>'}}, ... ] """ results = [] # check if adsets is a list if type(adsetids) is not list: return results # go over the list of adset ids for adsetid in adsetids: try: # read ad set info adset = AdSet(fbid=adsetid) adsetobj = adset.remote_read(fields=[AdSet.Field.targeting]) # edit targeting spec info for placements targetinginfo = copy.deepcopy(adsetobj[AdSet.Field.targeting]) targetinginfo[TargetingSpecsField.publisher_platforms]. \ append('audience_network') # update ad set info adset.update({AdSet.Field.targeting: targetinginfo}) adset.remote_update() # update result list along with status results.append({adsetid: {'status': 1}}) except FacebookError as e: # update result list along with status & message results.append({adsetid: {'status': 0, 'message': e.message}}) return results
def create_adset(campaign_id): adset = AdSet(parent_id='act_259842962') adset.update({ AdSet.Field.name: 'My Ad Set', AdSet.Field.campaign_id: campaign_id, AdSet.Field.daily_budget: 10000, AdSet.Field.billing_event: AdSet.BillingEvent.impressions, AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach, AdSet.Field.bid_amount: 2, AdSet.Field.targeting: { Targeting.Field.geo_locations: { 'countries': ['IN'], }, Targeting.Field.age_min: 20, Targeting.Field.age_max: 24 }, AdSet.Field.status: AdSet.Status.paused, }) adset.remote_create() return adset
def create_adset(campaign=None, params={}): if campaign is None: campaign = create_campaign() adset = AdSet(parent_id=test_config.account_id) adset[AdSet.Field.name] = unique_name('Test Adset') adset[AdSet.Field.campaign_id] = campaign.get_id() adset[AdSet.Field.targeting] = { 'geo_locations': { 'countries': ['US'], }, } adset[AdSet.Field.optimization_goal] = AdSet.OptimizationGoal.impressions adset[AdSet.Field.billing_event] = AdSet.BillingEvent.impressions adset[AdSet.Field.bid_amount] = 100 adset[AdSet.Field.daily_budget] = 1000 adset.update(params) adset.remote_create() atexit.register(remote_delete, adset) return adset
def create_ad_set(self, account_id, name, daily_budget, campaign_id, optimization_goal, billing_event, bid_amount, targeting, app_id, app_store_link): """ create an ad set in campaign we just created. """ pdata = { AdSet.Field.name: name, AdSet.Field.optimization_goal: optimization_goal, AdSet.Field.billing_event: billing_event, AdSet.Field.bid_amount: bid_amount, AdSet.Field.daily_budget: daily_budget, AdSet.Field.campaign_id: campaign_id, AdSet.Field.promoted_object: { 'application_id': app_id, 'object_store_url': app_store_link }, AdSet.Field.targeting: targeting, } pdata['status'] = AdSet.Status.paused adset = AdSet(parent_id=account_id) adset.remote_create(params=pdata) return adset[AdSet.Field.id]
from examples.docs import fixtures from facebookads import test_config from facebookads.objects import Campaign ad_account_id = test_config.account_id pixel_id = fixtures.create_ad_conversion_pixel().get_id() campaign_id = fixtures.create_campaign({ Campaign.Field.objective: Campaign.Objective.conversions, }).get_id_assured() # !_DOC [pruno] # _DOC open [ADSET_CREATE_CONVERSIONS] # _DOC vars [ad_account_id:s, campaign_id, pixel_id] from facebookads.objects import AdSet, TargetingSpecsField adset = AdSet(parent_id=ad_account_id) adset.update({ AdSet.Field.name: 'Conversions Ad Set', AdSet.Field.promoted_object: {'pixel_id': pixel_id}, AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach, AdSet.Field.billing_event: AdSet.BillingEvent.impressions, AdSet.Field.bid_amount: 2, AdSet.Field.daily_budget: 1000, AdSet.Field.campaign_id: campaign_id, AdSet.Field.targeting: { TargetingSpecsField.geo_locations: { 'countries': ['US'], }, }, })
# 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 examples.docs import fixtures from facebookads import test_config ad_account_id = test_config.account_id pixel_id = fixtures.create_ads_pixel().get_id() campaign_id = fixtures.create_campaign().get_id_assured() # _DOC open [ADSET_CREATE_CONVERSIONS_PURCHASE] # _DOC vars [ad_account_id:s, campaign_id, pixel_id] from facebookads.objects import AdSet, TargetingSpecsField adset = AdSet(parent_id=ad_account_id) adset.update( { AdSet.Field.name: "Ad Set oCPM", AdSet.Field.bid_amount: 150, AdSet.Field.billing_event: AdSet.BillingEvent.impressions, AdSet.Field.optimization_goal: AdSet.OptimizationGoal.offsite_conversions, AdSet.Field.promoted_object: {"pixel_id": pixel_id, "custom_event_type": "PURCHASE"}, AdSet.Field.daily_budget: 1000, AdSet.Field.campaign_id: campaign_id, AdSet.Field.targeting: {TargetingSpecsField.geo_locations: {"countries": ["US"]}}, } ) adset.remote_create(params={"status": AdSet.Status.paused}) print(adset)
# 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 examples.docs import fixtures from facebookads import test_config ad_account_id = test_config.account_id campaign_id = fixtures.create_campaign().get_id_assured() # _DOC open [ADSET_CREATE_INTERESTS_TARGETING] # _DOC vars [ad_account_id:s, campaign_id] from facebookads.objects import AdSet adset = AdSet(parent_id=ad_account_id) adset.update({ AdSet.Field.name: 'My AdSet', AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach, AdSet.Field.billing_event: AdSet.BillingEvent.impressions, AdSet.Field.bid_amount: 150, AdSet.Field.daily_budget: 2000, AdSet.Field.campaign_id: campaign_id, AdSet.Field.targeting: { 'geo_locations': { 'countries': ['US'], }, 'interests': [ { 'id': 6003139266461, 'name': 'Movies',
from facebookads import test_config from facebookads.objects import Campaign ad_account_id = test_config.account_id app_id, app_store_url = fixtures.get_promotable_ios_app() params = { Campaign.Field.objective: Campaign.Objective.conversions, } campaign_id = fixtures.create_campaign(params).get_id_assured() # _DOC open [ADSET_CREATE_CPA_APP_EVENTS] # _DOC vars [ad_account_id:s, app_id, campaign_id, app_store_url:s] import time from facebookads.objects import AdSet adset = AdSet(parent_id=ad_account_id) adset.update({ AdSet.Field.name: 'LifetimeBudgetSet', AdSet.Field.campaign_id: campaign_id, AdSet.Field.lifetime_budget: 10000, AdSet.Field.start_time: int(time.time()), AdSet.Field.end_time: int(time.time() + 100000), AdSet.Field.optimization_goal: AdSet.OptimizationGoal.offsite_conversions, AdSet.Field.billing_event: AdSet.BillingEvent.impressions, AdSet.Field.bid_amount: 500, AdSet.Field.promoted_object: { 'application_id': app_id, 'object_store_url': app_store_url, 'custom_event_type': 'ADD_TO_CART', }, AdSet.Field.targeting: {
# 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 examples.docs import fixtures from facebookads import test_config ad_account_id = test_config.account_id campaign_id = fixtures.create_campaign().get_id_assured() # _DOC open [ADSET_CREATE_BROAD_CATEGORY_TARGETING] # _DOC vars [ad_account_id:s, campaign_id] from facebookads.objects import AdSet adset = AdSet(parent_id=ad_account_id) adset.update({ AdSet.Field.name: 'My AdSet', AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach, AdSet.Field.billing_event: AdSet.BillingEvent.impressions, AdSet.Field.bid_amount: 150, AdSet.Field.daily_budget: 2000, AdSet.Field.campaign_id: campaign_id, AdSet.Field.targeting: { 'geo_locations': { 'countries': ['US'], }, 'user_adclusters': [ { 'id': 6002714885172, 'name': 'Cooking',
### Get first account connected to the user my_account = me.get_ad_account() ### Create a Campaign campaign = Campaign(parent_id=my_account.get_id_assured()) campaign.update({ Campaign.Field.name: 'Seattle Ad Campaign', Campaign.Field.objective: 'LINK_CLICKS', Campaign.Field.effective_status: Campaign.Status.paused, }) campaign.remote_create() print("**** DONE: Campaign created:") pp.pprint(campaign) ### Create an Ad Set ad_set = AdSet(parent_id=my_account.get_id_assured()) ad_set.update({ AdSet.Field.name: 'Puget Sound AdSet', AdSet.Field.effective_status: AdSet.Status.paused, AdSet.Field.daily_budget: 3600, # $36.00 AdSet.Field.billing_event: 'IMPRESSIONS', # $36.00 AdSet.Field.is_autobid: 'true', # $36.00 AdSet.Field.start_time: int(time.time()) + 15, # 15 seconds from now AdSet.Field.campaign_id: campaign.get_id_assured(), AdSet.Field.targeting: { TargetingSpecsField.geo_locations: { 'countries': [ 'US', ], }, },
# 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 examples.docs import fixtures from facebookads import test_config ad_account_id = test_config.account_id page_id = test_config.page_id campaign_id = fixtures.create_campaign().get_id() # _DOC open [ADSET_CREATE_LOCAL_AWARENESS] # _DOC vars [ad_account_id:s, campaign_id:s, page_id] from facebookads.objects import AdSet adset = AdSet(parent_id=ad_account_id) adset.update({ AdSet.Field.name: 'Local awareness adset', AdSet.Field.daily_budget: 10000, AdSet.Field.campaign_id: campaign_id, AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach, AdSet.Field.billing_event: AdSet.BillingEvent.impressions, AdSet.Field.bid_amount: 300, AdSet.Field.promoted_object: { 'page_id': page_id, }, AdSet.Field.targeting: { 'page_types': ['mobilefeed'], 'geo_locations': { 'custom_locations': [ {
# DEALINGS IN THE SOFTWARE. from examples.docs import fixtures from facebookads import test_config from facebookads.objects import Campaign ad_account_id = test_config.account_id campaign_id = fixtures.create_campaign({ Campaign.Field.objective: Campaign.Objective.link_clicks, }).get_id_assured() # _DOC open [ADSET_CREATE_AUDIENCE_NETWORK] # _DOC vars [campaign_id, ad_account_id:s] from facebookads.objects import AdSet, TargetingSpecsField adset = AdSet(parent_id=ad_account_id) adset.update({ AdSet.Field.name: 'My Ad Set', AdSet.Field.campaign_id: campaign_id, AdSet.Field.daily_budget: 1000, AdSet.Field.billing_event: AdSet.BillingEvent.link_clicks, AdSet.Field.optimization_goal: AdSet.OptimizationGoal.link_clicks, AdSet.Field.bid_amount: 2, AdSet.Field.targeting: { TargetingSpecsField.geo_locations: { 'countries': ['US'], }, TargetingSpecsField.page_types: [ 'mobileexternal', 'mobilefeed', ],
# Exclude people who've already liked the page # 'exclusions': [ # { # 'connections': [{'id':'103185246428488'},], # }, # ], } # Code to retrieve the campaign ID: # campaign = Campaign(campaign_id) # campaign.remote_read(fields=[Campaign.Field.name, Campaign.Field.objective,]) # print(campaign) # Create the Adset adset = AdSet(parent_id=my_id) campaign_id = '23842548820110548' # We attempted to set a time at which our ads would be broadcast, but this # required a lifetime budget rather than a daily budget. ''' # Attempt 1: AdSet.Field.pacing_type: ['day_parting'], AdSet.Field.adset_schedule: { 'start_minute': 60, 'end_minute': 540, 'days': [0, 1, 2, 3, 4, 5, 6], } # Attempt 2: AdSet.Field.start_time: str(datetime.datetime(year=2017, month=3, day=6, hour=1, minute=36)),
### Get first account connected to the user my_account = me.get_ad_account() ### Create a Campaign campaign = AdCampaign(parent_id=my_account.get_id_assured()) campaign.update({ AdCampaign.Field.name: 'Seattle Ad Campaign', AdCampaign.Field.objective: AdCampaign.Objective.website_clicks, AdCampaign.Field.status: AdCampaign.Status.paused, }) campaign.remote_create() print("**** DONE: Campaign created:") pp.pprint(campaign) ### Create an Ad Set ad_set = AdSet(parent_id=my_account.get_id_assured()) ad_set.update({ AdSet.Field.name: 'Puget Sound AdSet', AdSet.Field.status: AdSet.Status.paused, AdSet.Field.bid_type: AdSet.BidType.cpm, # Bidding for impressions AdSet.Field.bid_info: { AdSet.Field.BidInfo.impressions: 500, # $5 per 1000 impression }, AdSet.Field.daily_budget: 3600, # $36.00 AdSet.Field.start_time: int(time.time()) + 15, # 15 seconds from now AdSet.Field.campaign_group_id: campaign.get_id_assured(), AdSet.Field.targeting: { TargetingSpecsField.geo_locations: { 'countries': [ 'US', ],
# DEALINGS IN THE SOFTWARE. from examples.docs import fixtures from facebookads import test_config ad_account_id = test_config.account_id campaign_id = fixtures.create_campaign().get_id() product_set_id = fixtures.create_product_set().get_id() dynamic_audience_id = fixtures.create_product_audience(product_set_id).get_id() # _DOC open [ADSET_CREATE_PRODUCT_CATALOG_SALES_VIEWED_DAYS_RETENTION] # _DOC vars [ad_account_id:s, dynamic_audience_id, campaign_id, product_set_id] from facebookads.objects import AdSet, TargetingSpecsField adset = AdSet(parent_id=ad_account_id) adset[AdSet.Field.name] = 'Product Catalog Sales Adset' adset[AdSet.Field.bid_amount] = 3000 adset[AdSet.Field.billing_event] = AdSet.BillingEvent.link_clicks adset[AdSet.Field.optimization_goal] = AdSet.OptimizationGoal.link_clicks adset[AdSet.Field.daily_budget] = 15000 adset[AdSet.Field.campaign_id] = campaign_id adset[AdSet.Field.targeting] = { TargetingSpecsField.geo_locations: { TargetingSpecsField.countries: ['US'], }, TargetingSpecsField.product_audience_specs: [ { 'product_set_id': product_set_id, 'inclusions': [ {
campaign_group_id = homepage_campaign.get_id() # _DOC open [ADSET_CREATE_HOMEPAGE] # _DOC vars [ad_account_id:s, campaign_group_id] from facebookads.objects import AdAccount, AdSet ad_account = AdAccount(ad_account_id) rate_cards = ad_account.get_rate_cards() country = rate_cards[0][RateCard.Field.country] rate = rate_cards[0][RateCard.Field.rate] impressions = 5000 lifetime_budget = str(rate * 5000) end_date = int(time.time() + 12 * 3600) ad_set = AdSet(parent_id=ad_account_id) ad_set.update({ AdSet.Field.name: 'Adset Homepage Ads', AdSet.Field.campaign_group_id: campaign_group_id, AdSet.Field.lifetime_budget: lifetime_budget, AdSet.Field.lifetime_imps: impressions, AdSet.Field.bid_type: AdSet.BidType.multi_premium, AdSet.Field.bid_info: { AdSet.Field.BidInfo.clicks: 20, AdSet.Field.BidInfo.social: 40, AdSet.Field.BidInfo.impressions: 40 }, AdSet.Field.targeting: { TargetingSpecsField.page_types: ['home'], TargetingSpecsField.geo_locations: { 'countries': [country],
from examples.docs import fixtures from facebookads import test_config import time ad_account_id = test_config.account_id start_time = int(time.time()) end_time = start_time + 3600 * 24 * 7 campaign_id = fixtures.create_campaign().get_id() # _DOC oncall [pruno] # _DOC open [ADSET_CREATE_ADS_MANAGEMENT_UI] # _DOC vars [ad_account_id:s, start_time, end_time, campaign_id] from facebookads.objects import AdSet, TargetingSpecsField ad_set = AdSet(parent_id=ad_account_id) ad_set.update({ AdSet.Field.name: 'My First AdSet', AdSet.Field.lifetime_budget: 20000, AdSet.Field.start_time: start_time, AdSet.Field.end_time: end_time, AdSet.Field.campaign_id: campaign_id, AdSet.Field.bid_amount: 500, AdSet.Field.billing_event: AdSet.BillingEvent.impressions, AdSet.Field.optimization_goal: AdSet.OptimizationGoal.post_engagement, AdSet.Field.targeting: { TargetingSpecsField.geo_locations: { 'countries': ['JP'], }, TargetingSpecsField.genders: [1], TargetingSpecsField.age_min: 20,
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)
# DEALINGS IN THE SOFTWARE. from examples.docs import fixtures from facebookads import test_config ad_account_id = test_config.account_id campaign_id = fixtures.create_campaign().get_id_assured() custom_audience = fixtures.create_custom_audience() custom_audience_id = custom_audience['id'] audience_name = custom_audience['name'] # _DOC open [ADSET_CREATE_CUSTOM_AUDIENCE_PARTNER_CATEGORIES_TARGETING] # _DOC vars [ad_account_id:s, campaign_id, custom_audience_id, audience_name] from facebookads.objects import AdSet adset = AdSet(parent_id=ad_account_id) adset.update({ AdSet.Field.name: 'My AdSet', AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach, AdSet.Field.billing_event: AdSet.BillingEvent.impressions, AdSet.Field.bid_amount: 150, AdSet.Field.daily_budget: 2000, AdSet.Field.campaign_id: campaign_id, AdSet.Field.targeting: { 'geo_locations': { 'countries': ['US'], }, 'custom_audiences': [ { 'id': custom_audience_id, 'name': audience_name,
from facebookads import test_config from facebookads.objects import Campaign ad_account_id = test_config.account_id page_id = test_config.page_id params = { Campaign.Field.objective: Campaign.Objective.page_likes, } campaign_id = fixtures.create_campaign(params=params).get_id_assured() # _DOC open [ADSET_CREATE_CPC_PROMOTING_PAGE] # _DOC vars [ad_account_id:s, page_id:s, campaign_id:s] import time from facebookads.objects import AdSet adset = AdSet(parent_id=ad_account_id) adset.update({ AdSet.Field.name: 'My Ad Set', AdSet.Field.daily_budget: 10000, AdSet.Field.optimization_goal: AdSet.OptimizationGoal.page_likes, AdSet.Field.billing_event: AdSet.BillingEvent.page_likes, AdSet.Field.bid_amount: 1500, AdSet.Field.promoted_object: {'page_id': page_id}, AdSet.Field.targeting: { 'geo_locations': { 'countries': ['US'], } }, AdSet.Field.start_time: int(time.time()), AdSet.Field.campaign_id: campaign_id, })
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. from examples.docs import fixtures from facebookads import test_config ad_account_id = test_config.account_id campaign_id = fixtures.create_campaign().get_id_assured() page_id = test_config.page_id # _DOC oncall [paulbain] # _DOC open [ADSET_CREATE_BEHAVIORAL_TARGETING] # _DOC vars [ad_account_id:s, campaign_id, page_id] from facebookads.objects import AdSet, TargetingSpecsField adset = AdSet(parent_id=ad_account_id) adset.update({ AdSet.Field.name: 'My AdSet', AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach, AdSet.Field.billing_event: AdSet.BillingEvent.impressions, AdSet.Field.bid_amount: 150, AdSet.Field.daily_budget: 2000, AdSet.Field.campaign_id: campaign_id, AdSet.Field.promoted_object: {'page_id': page_id}, AdSet.Field.targeting: { TargetingSpecsField.geo_locations: { 'countries': ['JP'], 'regions': [ {'key': '3886'}, ], 'cities': [
def create_multiple_website_clicks_ads( account, name, country, titles, bodies, urls, image_paths, bid_type, bid_info, daily_budget=None, lifetime_budget=None, start_time=None, end_time=None, age_min=None, age_max=None, genders=None, campaign=None, paused=False, ): # 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.') # Create campaign if not campaign: campaign = AdCampaign(parent_id=account.get_id_assured()) campaign[AdCampaign.Field.name] = name + ' Campaign' campaign[AdCampaign.Field.objective] = \ AdCampaign.Objective.website_clicks campaign[AdCampaign.Field.status] = \ AdCampaign.Status.active if not paused \ else AdCampaign.Status.paused campaign.remote_create() # Create ad set ad_set = AdSet(parent_id=account.get_id_assured()) ad_set[AdSet.Field.campaign_group_id] = campaign.get_id_assured() ad_set[AdSet.Field.name] = name + ' AdSet' ad_set[AdSet.Field.bid_type] = bid_type ad_set[AdSet.Field.bid_info] = bid_info 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 targeting = {} targeting[TargetingSpecsField.geo_locations] = {'countries': [country]} if age_max: targeting[TargetingSpecsField.age_max] = age_max if age_min: targeting[TargetingSpecsField.age_min] = age_min if genders: targeting[TargetingSpecsField.genders] = genders ad_set[AdSet.Field.targeting] = targeting ad_set.remote_create() # Upload the images first one by one image_hashes = [] for image_path in image_paths: img = AdImage(parent_id=account.get_id_assured()) img[AdImage.Field.filename] = image_path img.remote_create() image_hashes.append(img.get_hash()) ADGROUP_BATCH_CREATE_LIMIT = 10 ad_groups_created = [] def callback_failure(response): raise response.error() # For each creative permutation for creative_info_batch in generate_batches( itertools.product(titles, bodies, urls, image_hashes), ADGROUP_BATCH_CREATE_LIMIT): api_batch = account.get_api_assured().new_batch() for title, body, url, image_hash in creative_info_batch: # Create the ad ad = AdGroup(parent_id=account.get_id_assured()) ad[AdGroup.Field.name] = name + ' Ad' ad[AdGroup.Field.campaign_id] = ad_set.get_id_assured() ad[AdGroup.Field.creative] = { AdCreative.Field.title: title, AdCreative.Field.body: body, AdCreative.Field.object_url: url, AdCreative.Field.image_hash: image_hash, } ad.remote_create(batch=api_batch, failure=callback_failure) ad_groups_created.append(ad) api_batch.execute() return ad_groups_created
# 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 examples.docs import fixtures ad_set_id = fixtures.create_adset().get_id_assured() # !_DOC [duliomatos] # _DOC open [ADSET_READ_DATA_FORMAT] # _DOC vars [ad_set_id] from facebookads.objects import AdSet adset = AdSet(fbid=ad_set_id) fields = [ AdSet.Field.start_time, AdSet.Field.end_time, AdSet.Field.configured_status, AdSet.Field.effective_status, AdSet.Field.campaign_id, ] params = { 'date_format': 'U', } adset.remote_read(fields=fields, params=params) print(adset[AdSet.Field.effective_status]) # _DOC close [ADSET_READ_DATA_FORMAT]
campaign_id = fixtures.create_campaign(params).get_id() targeting = { TargetingSpecsField.page_types: ["desktopfeed", "mobilefeed", "mobileexternal"], TargetingSpecsField.geo_locations: {"countries": ["BR"]}, } optimization_goal = AdSet.OptimizationGoal.post_engagement start_time = int(time.time()) end_time = int(time.time() + 100000) bid_amount = 150 billing_event = AdSet.BillingEvent.post_engagement # _DOC open [ADSET_CREATE_LIFETIME_BUDGET_200_DOLLARS_DURATION_10_DAYS] # _DOC vars [ad_account_id:s, page_id:s, campaign_id, targeting, bid_amount, billing_event, start_time:s, end_time:s] from facebookads.objects import AdSet adset = AdSet(parent_id=ad_account_id) adset[AdSet.Field.name] = "My First AdSet" adset[AdSet.Field.daily_budget] = 20000 adset[AdSet.Field.start_time] = start_time adset[AdSet.Field.end_time] = end_time adset[AdSet.Field.campaign_id] = campaign_id adset[AdSet.Field.bid_amount] = bid_amount adset[AdSet.Field.billing_event] = billing_event adset[AdSet.Field.optimization_goal] = optimization_goal adset[AdSet.Field.targeting] = targeting adset.remote_create(params={"status": AdSet.Status.paused}) # _DOC close [ADSET_CREATE_LIFETIME_BUDGET_200_DOLLARS_DURATION_10_DAYS] adset.remote_delete()
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]
from facebookads import test_config from facebookads.objects import AdCampaign ad_account_id = test_config.account_id page_id = test_config.page_id connections_id = page_id campaign_group_id = fixtures.create_adcampaign().get_id_assured() ad_set_id = fixtures.create_adset().get_id_assured() product_catalog_id = test_config.product_catalog_id product_set_id = test_config.product_set_id # _DOC open [ADSET_CREATE] # _DOC vars [ad_account_id:s, campaign_group_id] from facebookads.objects import AdSet, TargetingSpecsField adset = AdSet(parent_id=ad_account_id) adset.update({ AdSet.Field.name: 'My Ad Set', AdSet.Field.campaign_group_id: campaign_group_id, AdSet.Field.daily_budget: 1000, AdSet.Field.billing_event: AdSet.BillingEvent.impressions, AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach, AdSet.Field.bid_amount: 2, AdSet.Field.targeting: { TargetingSpecsField.geo_locations: { 'countries': ['US'], }, }, AdSet.Field.status: AdSet.Status.paused, })
# 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 examples.docs import fixtures ad_set_id = fixtures.create_adset().get_id() # _DOC open [ADSET_GET_INSIGHTS_LEVEL_ADGROUP] # _DOC vars [ad_set_id] from facebookads.objects import AdSet, Insights adset = AdSet(fbid=ad_set_id) params = { 'level': Insights.Level.ad } stats = adset.get_insights(params=params) print(stats) # _DOC close [ADSET_GET_INSIGHTS_LEVEL_ADGROUP]
# 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 examples.docs import fixtures from facebookads import test_config ad_account_id = test_config.account_id connections_id = test_config.page_id campaign_id = fixtures.create_campaign().get_id_assured() # _DOC open [ADSET_CREATE_APP_CONNECTIONS_TARGETING] # _DOC vars [ad_account_id:s, campaign_id, connections_id] from facebookads.objects import AdSet, TargetingSpecsField ad_set = AdSet(parent_id=ad_account_id) ad_set.update({ AdSet.Field.name: 'Android Connections Targeting - Ad Set', AdSet.Field.campaign_id: campaign_id, AdSet.Field.optimization_goal: AdSet.OptimizationGoal.post_engagement, AdSet.Field.billing_event: AdSet.BillingEvent.post_engagement, AdSet.Field.bid_amount: 1500, AdSet.Field.daily_budget: 10000, AdSet.Field.targeting: { TargetingSpecsField.geo_locations: { 'countries': ['US'], }, TargetingSpecsField.connections: [connections_id], TargetingSpecsField.user_os: ['Android'], }, })
# 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 examples.docs import fixtures from facebookads import test_config ad_account_id = test_config.account_id campaign_id = fixtures.create_campaign().get_id_assured() # _DOC open [ADSET_CREATE_LOCATION_DEMOGRAPHIC_INTERESTS_TARGETING] # _DOC vars [ad_account_id:s, campaign_id] from facebookads.objects import AdSet adset = AdSet(parent_id=ad_account_id) adset.update({ AdSet.Field.name: 'My AdSet', AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach, AdSet.Field.billing_event: AdSet.BillingEvent.impressions, AdSet.Field.bid_amount: 150, AdSet.Field.daily_budget: 2000, AdSet.Field.campaign_id: campaign_id, AdSet.Field.targeting: { 'geo_locations': { 'regions': [{ 'key': '3847' }], 'cities': [ { 'key': '2430536',
ad_account_id = test_config.account_id product_catalog_id = fixtures.create_product_catalog().get_id() product_set_id = fixtures.create_product_set(product_catalog_id).get_id() params = { Campaign.Field.objective: Campaign.Objective.product_catalog_sales, Campaign.Field.promoted_object: {'product_catalog_id': product_catalog_id}, } campaign_id = fixtures.create_campaign(params).get_id_assured() # _DOC open [ADSET_CREATE_DYNAMIC_PROSPECTIING] # _DOC vars [ad_account_id:s, product_set_id, campaign_id] from facebookads.objects import AdSet, TargetingSpecsField adset = AdSet(parent_id=ad_account_id) adset[AdSet.Field.name] = 'Case 1 Adset' adset[AdSet.Field.bid_amount] = 3000 adset[AdSet.Field.billing_event] = AdSet.BillingEvent.link_clicks adset[AdSet.Field.optimization_goal] = AdSet.OptimizationGoal.link_clicks adset[AdSet.Field.daily_budget] = 15000 adset[AdSet.Field.campaign_id] = campaign_id adset[AdSet.Field.targeting] = { TargetingSpecsField.geo_locations: { TargetingSpecsField.countries: ['US'], }, TargetingSpecsField.interests: [{ 'id': 6003397425735, 'name': 'Tennis', }], }
# 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 examples.docs import fixtures from facebookads import test_config ad_account_id = test_config.account_id campaign_id = fixtures.create_campaign().get_id_assured() # _DOC open [ADSET_CREATE_FLEXIBLE_TARGETING] # _DOC vars [ad_account_id:s, campaign_id] from facebookads.objects import AdSet adset = AdSet(parent_id=ad_account_id) adset.update({ AdSet.Field.name: 'My AdSet', AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach, AdSet.Field.billing_event: AdSet.BillingEvent.impressions, AdSet.Field.bid_amount: 150, AdSet.Field.daily_budget: 2000, AdSet.Field.campaign_id: campaign_id, AdSet.Field.targeting: { 'geo_locations': { 'countries': ['US'], }, 'age_min': 18, 'age_max': 43, 'flexible_spec': [ {
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'], }
targeting = { TargetingSpecsField.geo_locations: { TargetingSpecsField.countries: ['US'], }, } # _DOC open [ADSET_CREATE_TARGETING_DATE_RANGE] # _DOC vars [ad_account_id:s, campaign_id, targeting] import datetime from facebookads.objects import AdSet today = datetime.date.today() start_time = str(today + datetime.timedelta(weeks=1)) end_time = str(today + datetime.timedelta(weeks=2)) adset = AdSet(parent_id=ad_account_id) adset.update({ AdSet.Field.name: 'My Ad Set', AdSet.Field.campaign_id: campaign_id, AdSet.Field.daily_budget: 1000, AdSet.Field.billing_event: AdSet.BillingEvent.impressions, AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach, AdSet.Field.bid_amount: 2, AdSet.Field.targeting: targeting, AdSet.Field.start_time: start_time, AdSet.Field.end_time: end_time, }) adset.remote_create(params={ 'status': AdSet.Status.paused, })
# 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 examples.docs import fixtures from facebookads import test_config ad_account_id = test_config.account_id campaign_id = fixtures.create_campaign().get_id_assured() # _DOC open [ADSET_CREATE_PLACEMENT_TARGETING] # _DOC vars [ad_account_id:s, campaign_id] from facebookads.objects import AdSet adset = AdSet(parent_id=ad_account_id) adset.update({ AdSet.Field.name: 'My AdSet', AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach, AdSet.Field.billing_event: AdSet.BillingEvent.impressions, AdSet.Field.bid_amount: 150, AdSet.Field.daily_budget: 2000, AdSet.Field.campaign_id: campaign_id, AdSet.Field.targeting: { 'geo_locations': { 'countries': ['US'], }, 'page_types': [ 'desktopfeed', 'rightcolumn', 'mobilefeed',
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