def create_creative(self, accountid, name, imagehash, message, appinfo): """ Step 4: create ad creative with call to action type to be 'USE_MOBILE_APP'. See [Ad Creative](https://developers.facebook.com/docs/marketing-api/adcreative) for further details on the API used here. """ link_data = LinkData() link_data[LinkData.Field.name] = appinfo['app_name'] link_data[LinkData.Field.link] = appinfo['appstore_link'] link_data[LinkData.Field.message] = message link_data[LinkData.Field.image_hash] = imagehash call_to_action = {'type': 'USE_MOBILE_APP'} call_to_action['value'] = { 'link': appinfo['appstore_link'], 'app_link': appinfo['app_deep_link'], 'application': appinfo['fbapplication_id'] } link_data[LinkData.Field.call_to_action] = call_to_action object_story_spec = ObjectStorySpec() object_story_spec[ObjectStorySpec.Field.page_id] = appinfo['fbpage_id'] object_story_spec[ObjectStorySpec.Field.link_data] = link_data creative = AdCreative(parent_id=accountid) creative[AdCreative.Field.name] = name creative[AdCreative.Field.object_story_spec] = object_story_spec creative.remote_create() return creative[AdCreative.Field.id]
def create_creative(self, account_id, name, image_hash, message, page_id, app_name, app_store_link, deferred_app_link): """ Step 4: create ad creative with call to action type to be 'INSTALL_MOBILE_APP'. See [Ad Creative][1] for further details on the API used here. [1]: https://developers.facebook.com/docs/marketing-api/adcreative """ link_data = LinkData() link_data[LinkData.Field.name] = app_name link_data[LinkData.Field.link] = app_store_link link_data[LinkData.Field.message] = message link_data[LinkData.Field.image_hash] = image_hash call_to_action = {'type': 'INSTALL_MOBILE_APP'} call_to_action['value'] = {'link': app_store_link} if deferred_app_link: call_to_action['value']['app_link'] = deferred_app_link link_data[LinkData.Field.call_to_action] = call_to_action 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[AdCreative.Field.object_story_spec] = object_story_spec creative.remote_create() return creative[AdCreative.Field.id]
def get_ad_data_or_sleep(self, ad): """ Get needed data for ads or sleep :param ad: :return: """ while True: ad_data = {'ad_id': ad} try: ad = Ad(ad) creative = AdCreative( ad.api_get(fields=[Ad.Field.creative])['creative']['id']) fields = [ AdCreative.Field.call_to_action_type, AdCreative.Field.object_story_spec ] creative.api_get(fields=fields) creative = dict(creative) try: call_to_action = creative['object_story_spec'][ 'video_data']['call_to_action'] try: print(creative['object_story_spec']['photo_data']) except KeyError: pass ad_data['website_url'] = call_to_action['value']['link'] ad_data['call_to_action_type'] = call_to_action['type'] ad_data['headline'] = creative['object_story_spec'][ 'video_data']['title'] ad_data['description'] = creative['object_story_spec'][ 'video_data']['message'] video = AdVideo(creative['object_story_spec']['video_data'] ['video_id']) ad_data['video_name'] = video.api_get( fields=[AdVideo.Field.title])['title'] except KeyError: pass self.current_ads.append(ad_data) except FacebookRequestError as e: print(type(e.api_error_code())) if e.api_error_code() == 803: break print('Sleeping right now for ads') time.sleep(600) else: break return ad_data
def create_creative(message, link, image_hash): link_data = AdCreativeLinkData() link_data[AdCreativeLinkData.Field.message] = message link_data[AdCreativeLinkData.Field.link] = link link_data[AdCreativeLinkData.Field.image_hash] = image_hash object_story_spec = AdCreativeObjectStorySpec() object_story_spec[ AdCreativeObjectStorySpec.Field.page_id] = '102142938001931' object_story_spec[AdCreativeObjectStorySpec.Field.link_data] = link_data creative = AdCreative(parent_id='act_171349487548919') creative[AdCreative.Field.name] = 'AdCreative for Link Ad' creative[AdCreative.Field.object_story_spec] = object_story_spec creative.remote_create() return creative
def test_get_previews(self): with warnings.catch_warnings(record=True) as warning: self.mock_response.status_code = StatusCode.SUCCESS self.mock_response._content = ('{' '"' + str(FieldName.BODY) + '":"' + str(TestValue.BODY) + '"' '}') self.mock_request.return_value = self.mock_response fields = [] params = { FieldName.AD_FORMAT: TestValue.AD_FORMAT, FieldName.DYNAMIC_ASSET_LABEL: TestValue.DYNAMIC_ASSET_LABEL, FieldName.DYNAMIC_CREATIVE_SPEC: json.loads(TestValue.DYNAMIC_CREATIVE_SPEC), FieldName.HEIGHT: TestValue.HEIGHT, FieldName.WIDTH: TestValue.WIDTH, FieldName.RENDER_TYPE: TestValue.RENDER_TYPE, } previews = AdCreative(TestValue.CREATIVE_ID).get_previews( fields=fields, params=params, ) self.assertEqual(len(warning), 0) self.assertTrue(isinstance(previews[0], AdPreview)) self.assertEqual(previews[0][FieldName.BODY], TestValue.BODY)
def create_creative(self, stratum: Stratum, config: CreativeConf) -> AdCreative: ref = make_ref(config, stratum) msg = make_welcome_message(config.welcome_message, config.button_text, ref) oss = { AdCreativeObjectStorySpec.Field.link_data: { AdCreativeLinkData.Field.call_to_action: { "type": "MESSAGE_PAGE", "value": { "app_destination": "MESSENGER" }, }, AdCreativeLinkData.Field.image_hash: config.image_hash, AdCreativeLinkData.Field.message: config.body, AdCreativeLinkData.Field.name: config.link_text, AdCreativeLinkData.Field.page_welcome_message: msg, }, AdCreativeObjectStorySpec.Field.page_id: self.cnf["PAGE_ID"], } if self.cnf["INSTA_ID"]: oss[AdCreativeObjectStorySpec.Field. instagram_actor_id] = self.cnf["INSTA_ID"] c = AdCreative() c[AdCreative.Field.name] = config.name c[AdCreative.Field.url_tags] = f"ref={ref}" c[AdCreative.Field.actor_id] = self.cnf["PAGE_ID"] c[AdCreative.Field.object_story_spec] = oss return c
def create_adcreative(_img=None, _name=None, _message=None, _link='https://relaygo.com/relay', _link_title=None, _link_desc=None, _keyvalue=None, _page_id = page_id, _instagram_id = instagram_id, _ad_account=ad_account_id): from facebook_business.adobjects.adimage import AdImage from facebook_business.adobjects.adcreative import AdCreative from facebook_business.adobjects.adcreativelinkdata import AdCreativeLinkData from facebook_business.adobjects.adcreativeobjectstoryspec import AdCreativeObjectStorySpec if _img is None: _img = '/Users/smalone/Desktop/Images/RelayAd_1a.png' if _name is None: _name = 'API Test AdCreative Name - DELETE' if _message is None: _message = 'Programmatic API Message' if _link_title is None: _link_title = "Relay is really awesome" if _link_desc is None: _link_desc = 'You should buy it' image = AdImage(parent_id=_ad_account) image[AdImage.Field.filename] = _img image.remote_create() image_hash = image[AdImage.Field.hash] link_data = AdCreativeLinkData() link_data[AdCreativeLinkData.Field.message] = _message link_data[AdCreativeLinkData.Field.link] = _link link_data[AdCreativeLinkData.Field.image_hash] = image_hash # link_data[AdCreativeLinkData.Field.format_option] = 'single_image' #carousel_images_multi_items, carousel_images_single_item, carousel_slideshows link_data[AdCreativeLinkData.Field.name] = _link_title link_data[AdCreativeLinkData.Field.caption] = 'relaygo.com' link_data[AdCreativeLinkData.Field.description] = _link_desc link_data[AdCreativeLinkData.Field.call_to_action] = {"type":"LEARN_MORE", "value": {"link":_link,}} object_story_spec = AdCreativeObjectStorySpec() object_story_spec[AdCreativeObjectStorySpec.Field.page_id] = _page_id object_story_spec[AdCreativeObjectStorySpec.Field.instagram_actor_id] = _instagram_id object_story_spec[AdCreativeObjectStorySpec.Field.link_data] = link_data creative = AdCreative(parent_id=_ad_account) creative[AdCreative.Field.name] = _name creative[AdCreative.Field.object_story_spec] = object_story_spec if _keyvalue != None: creative[AdCreative.Field.url_tags] = _keyvalue creative.remote_create() return creative
def create_video_creation(video_id, image_url, page_id): FacebookAdsApi.init(access_token=my_access_token) video_data = AdCreativeVideoData() # video_data[AdCreativeVideoData.Field.description] = 'Hi World' video_data[AdCreativeVideoData.Field.video_id] = video_id video_data[AdCreativeVideoData.Field.image_url] = image_url video_data[AdCreativeVideoData.Field.call_to_action] = { 'type': 'LIKE_PAGE', 'value': { 'page': page_id, }, } object_story_spec = AdCreativeObjectStorySpec() object_story_spec[AdCreativeObjectStorySpec.Field.page_id] = page_id object_story_spec[AdCreativeObjectStorySpec.Field.video_data] = video_data creative = AdCreative(parent_id=f'act_{ad_account}') creative[AdCreative.Field.name] = 'Video Ad Creative-0' creative[AdCreative.Field.object_story_spec] = object_story_spec return creative.remote_create()
def s4_create_creative(self, accountid, name, imagehashes, linktitles, deeplinks, message, appinfo): """ Step 4: create ad creative with call to action type to be 'INSTALL_MOBILE_APP'. See [Ad Creative]( https://developers.facebook.com/docs/marketing-api/adcreative) for further details on the API used here. """ attachments = [] for index, imagehash in enumerate(imagehashes): attachment = AttachmentData() attachment[AttachmentData.Field.name] = linktitles[index] attachment[AttachmentData.Field.link] = appinfo['appstore_link'] attachment[AttachmentData.Field.image_hash] = imagehash call_to_action = { 'type': 'INSTALL_MOBILE_APP', } if deeplinks and index in deeplinks: call_to_action['value']['app_link'] = deeplinks[index] attachment[AttachmentData.Field.call_to_action] = call_to_action attachments.append(attachment) link_data = LinkData() link_data[LinkData.Field.link] = appinfo['appstore_link'] link_data[LinkData.Field.message] = message link_data[LinkData.Field.child_attachments] = attachments object_story_spec = ObjectStorySpec() object_story_spec[ObjectStorySpec.Field.page_id] = appinfo['fbpage_id'] object_story_spec[ObjectStorySpec.Field.link_data] = link_data creative = AdCreative(parent_id=accountid) creative[AdCreative.Field.name] = name creative[AdCreative.Field.object_story_spec] = object_story_spec creative.remote_create() return creative[AdCreative.Field.id]
def createAd(self, name): print("Creating Image Hash...") img_path = 'Icon-1024.png' image = AdImage() image['_parent_id'] = id image[AdImage.Field.filename] = img_path image.remote_create() print("**Image Hash...**") # Output image Hash image_hash = image[AdImage.Field.hash] ##image_hash = "5c2f70590d5a1381f1871a5e3731ecb1" print("**Image Hash : {}**".format(image_hash)) print("** Creating Ad Creative...**") website_url = "www.example.com" page_id = '181951488809425' link_data = AdCreativeLinkData() link_data[AdCreativeLinkData.Field.name] = 'main text 001' link_data[AdCreativeLinkData.Field.message] = 'title 001' link_data[AdCreativeLinkData.Field.link] = website_url link_data[AdCreativeLinkData.Field.image_hash] = image_hash object_story_spec = AdCreativeObjectStorySpec() object_story_spec[AdCreativeObjectStorySpec.Field.page_id] = page_id object_story_spec[ AdCreativeObjectStorySpec.Field.link_data] = link_data creative = AdCreative() creative['_parent_id'] = id creative[AdCreative.Field.object_story_spec] = object_story_spec creative[AdCreative.Field.title] = 'Main text 001' creative[AdCreative.Field.body] = 'Title 001' creative[AdCreative.Field.actor_id] = page_id creative[AdCreative.Field.link_url] = website_url creative[AdCreative.Field.object_type] = AdCreative.ObjectType.domain creative[AdCreative.Field.image_hash] = image_hash print("Ad Creative created successfully!") print("***Ad...*") ad = Ad() ad['_parent_id'] = self.id ad[Ad.Field.name] = name ad[Ad.Field.adset_id] = self.adset_id ad[Ad.Field.creative] = creative ad.remote_create(params={ 'status': Ad.Status.paused, }) self.ad_id = str(ad[Ad.Field.id]) print("**Ad ID: {}**".format(self.ad_id)) return ad
def create_video_creation(video_id, destination_url, description, adgroup, page_id): FacebookAdsApi.init(access_token=my_access_token) video_data = AdCreativeVideoData() # video_data[AdCreativeVideoData.Field.description] = description video_data[AdCreativeVideoData.Field.video_id] = video_id image_hash = image_upload(adgroup) video_data[AdCreativeVideoData.Field.image_hash] = image_hash video_data[AdCreativeVideoData.Field.call_to_action] = { 'type': 'LIKE_PAGE', 'value': { 'page': page_id, }, } object_story_spec = AdCreativeObjectStorySpec() object_story_spec[AdCreativeObjectStorySpec.Field.page_id] = page_id object_story_spec[AdCreativeObjectStorySpec.Field.video_data] = video_data creative = AdCreative(parent_id=f'act_{ad_account}') creative[AdCreative.Field.name] = f'Video {adgroup}' creative[AdCreative.Field.object_story_spec] = object_story_spec creative[AdCreative.Field.url_tags] = destination_url return creative.remote_create()['id']
def test_get_previews_with_wrong_params(self): with warnings.catch_warnings(record=True) as warning: self.mock_response.status_code = StatusCode.ERROR self.mock_request.return_value = self.mock_response fields = [] params = { 'render_type': 'wrong_type', } with self.assertRaises(FacebookRequestError): previews = AdCreative(TestValue.CREATIVE_ID).get_previews( fields=fields, params=params, ) self.assertEqual(len(warning), 1) self.assertTrue(issubclass(warning[0].category, UserWarning))
def index(): try: # select all ads for currently logged in user ads = db.execute("SELECT * FROM ads WHERE users_table_id = :id", id=session["id"]) print(ads) if ads: # get access token from server rows = db.execute("SELECT * FROM users WHERE id = :id", id=str(session["id"])) FacebookAdsApi.init(access_token=rows[0]["access_token"], api_version='v3.3') # get an array of MOST RECENT iframes, up to 3 list = [] small = min(3, len(ads)) print(small) for i in range( len(ads), len(ads) - small, -1): # given a list of 10, i'd want 10, 9, 8 in that order print(i) fields = [] params = { 'ad_format': 'MOBILE_FEED_STANDARD', } data = AdCreative(ads[i - 1]['creative_id']).get_previews( fields=fields, params=params, ) soup = BeautifulSoup(data[0]['body'], 'html5lib') iframe = soup.find_all('iframe')[0]['src'] list.append(iframe) print(list) return render_template("index.html", iframes=list, count=small) #return render_template("index.html", count=1, iframe=iframe) return redirect('/lead_ad_generator') except FacebookError as e: if e.body(): error = e.body() error_code = error['error']['code'] #if error_code is 190: # render_template("fblogin.html", app_id=FB_APP_ID) return render_template("fblogin.html", app_id=FB_APP_ID)
def test_get_ad_creative_with_wrong_fields(self): with warnings.catch_warnings(record=True) as warning: self.mock_response.status_code = StatusCode.ERROR self.mock_request.return_value = self.mock_response fields = [ 'unexist_field', ] params = {} with self.assertRaises(FacebookRequestError): creative = AdCreative(TestValue.CREATIVE_ID).api_get( fields=fields, params=params, ) self.assertEqual(len(warning), 1) self.assertTrue(issubclass(warning[0].category, UserWarning))
# duplicate adset asr = adsett.create_copy(params={'deep_copy': True}) adset = AdSet(asr._data['copied_adset_id']) adset.api_update(params={AdSet.Field.name: vname}) # rename adset # adset ads ads = adset.get_ads(fields=[Ad.Field.id, Ad.Field.name, Ad.Field.creative]) ad = ads[0] # should only be one ad ad[Ad.Field.name] = vname ad.api_update(params={Ad.Field.name: vname}) # rename ad adc = AdCreative(ad[Ad.Field.creative][AdCreative.Field.id]) adc = adc.api_get(fields=[AdCreative.Field.object_story_spec]) fields = [ AdCreative.Field.account_id, AdCreative.Field.actor_id, AdCreative.Field.adlabels, AdCreative.Field.applink_treatment, AdCreative.Field.asset_feed_spec, AdCreative.Field.authorization_category, AdCreative.Field.auto_update, AdCreative.Field.body, AdCreative.Field.branded_content_sponsor_page_id, AdCreative.Field.bundle_folder_id, AdCreative.Field.call_to_action_type, AdCreative.Field.categorization_criteria,
# 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.adcreative import AdCreative from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<AD_CREATIVE_ID>' FacebookAdsApi.init(access_token=access_token) fields = [ 'instagram_permalink_url', ] params = {} print AdCreative(id).get( fields=fields, params=params, )
AdSet.OptimizationGoal.link_clicks adset[AdSet.Field.daily_budget] = 1000 adset[AdSet.Field.campaign_id] = campaign[Campaign.Field.id] adset[AdSet.Field.targeting] = { Targeting.Field.geo_locations: { Targeting.Field.countries: ['NO'], }, } # adset[AdSet.Field.promoted_object] = { # 'product_set_id': '490354758419836', # } adset.remote_create() story = AdCreativeObjectStorySpec() story[story.Field.page_id] = 240295992766537 story[story.Field.template_data] = { 'message': 'Test {{product.name | titleize}}', 'link': 'http://instebo.one', 'name': 'Headline {{product.price}}', 'description': 'Description {{product.description}}', } creative = AdCreative(parent_id=act_cid) creative[AdCreative.Field.name] = 'Dynamic Ad Template Creative Sample' creative[AdCreative.Field.object_story_spec] = story creative[AdCreative.Field.product_set_id] = 490354758419836 creative.remote_create() else: print("no api found")
def test_get_adcreative(self): with warnings.catch_warnings(record=True) as warning: self.mock_response.status_code = StatusCode.SUCCESS self.mock_response._content = ( '{' '"' + str(FieldName.ACCOUNT_ID) + '":"' + str(TestValue.ACCOUNT_ID) + '",' '"' + str(FieldName.ACTOR_ID) + '":"' + str(TestValue.ACTOR_ID) + '",' '"' + str(FieldName.ADLABELS) + '":' + str(TestValue.AD_LABEL) + ',' '"' + str(FieldName.APPLINK_TREATMENT) + '":"' + str(TestValue.APPLINK_TREATMENT) + '",' '"' + str(FieldName.AUTHORIZATION_CATEGORY) + '":"' + str(TestValue.AUTHORIZATION_CATEGORY) + '",' '"' + str(FieldName.AUTO_UPDATE) + '":"' + str(TestValue.AUTO_UPDATE) + '",' '"' + str(FieldName.BODY) + '":"' + str(TestValue.BODY) + '",' '"' + str(FieldName.CALL_TO_ACTION_TYPE) + '":"' + str(TestValue.CALL_TO_ACTION_TYPE) + '",' '"' + str(FieldName.CATEGORIZATION_CRITERIA) + '":"' + str(TestValue.CATEGORIZATION_CRITERIA) + '",' '"' + str(FieldName.IMAGE_HASH) + '":"' + str(TestValue.IMAGE_HASH) + '",' '"' + str(FieldName.TITLE) + '":"' + str(TestValue.TITLE) + '",' '"' + str(FieldName.OBJECT_URL) + '":"' + str(TestValue.OBJECT_URL) + '",' '"' + str(FieldName.NAME) + '":"' + str(TestValue.NAME) + '"' '}') self.mock_request.return_value = self.mock_response fields = [ FieldName.ACCOUNT_ID, FieldName.ACTOR_ID, FieldName.ADLABELS, FieldName.APPLINK_TREATMENT, FieldName.AUTHORIZATION_CATEGORY, FieldName.AUTO_UPDATE, FieldName.BODY, FieldName.CALL_TO_ACTION_TYPE, FieldName.CATEGORIZATION_CRITERIA, FieldName.IMAGE_HASH, FieldName.TITLE, FieldName.OBJECT_URL, FieldName.NAME, ] params = {} creative = AdCreative(TestValue.CREATIVE_ID).api_get( fields=fields, params=params, ) self.assertEqual(len(warning), 0) self.assertTrue(isinstance(creative, AdCreative)) self.assertEqual(creative[FieldName.ACCOUNT_ID], TestValue.ACCOUNT_ID) self.assertEqual(creative[FieldName.ACTOR_ID], TestValue.ACTOR_ID) self.assertEqual(creative[FieldName.ADLABELS], [json.loads(TestValue.AD_LABEL)]) self.assertEqual(creative[FieldName.APPLINK_TREATMENT], TestValue.APPLINK_TREATMENT) self.assertEqual(creative[FieldName.AUTHORIZATION_CATEGORY], TestValue.AUTHORIZATION_CATEGORY) self.assertEqual(creative[FieldName.BODY], TestValue.BODY) self.assertEqual(creative[FieldName.CALL_TO_ACTION_TYPE], TestValue.CALL_TO_ACTION_TYPE) self.assertEqual(creative[FieldName.CATEGORIZATION_CRITERIA], TestValue.CATEGORIZATION_CRITERIA) self.assertEqual(creative[FieldName.IMAGE_HASH], TestValue.IMAGE_HASH) self.assertEqual(creative[FieldName.TITLE], TestValue.TITLE) self.assertEqual(creative[FieldName.OBJECT_URL], TestValue.OBJECT_URL) self.assertEqual(creative[FieldName.NAME], TestValue.NAME)
# 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.adcreative import AdCreative from facebook_business.adobjects.adcreativeinsights import AdCreativeInsights from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<CREATIVE_ID>' FacebookAdsApi.init(access_token=access_token) fields = [ 'creative_compass_scores', ] params = {} print AdCreative(id).get_creative_insights( fields=fields, params=params, )
access_token = "EAAHsrmgrz0YBAA9W2ffy3UsB0UgAzkdPaZANA7VYMNHVKZCD80y4CVSGEB33ZCfn367SNB4ogJdLmwwbZAkcyZCpqyubToEUp3QnsZA7Av9rLfhrVFnQqgO9uL6EJQPbTDZA58oqBFjZB2oqVSsECKQP7KnQzlZAdJ1QU4yJVgePz4ZCfK7gvHw5Ay" account_id = 'act_414637205659315' page_id = 238251770344039 # access_token = 'EAAHsrmgrz0YBAAG1qQZCIZBeZApR6jbqZCdwGNoEWUebVquFpNDPKaLa0o7SPPFlhaZBsMaUyWeKPqgjGGEhZAwVwfOJuuu7mZA1OfNVZA0ni4sus7PRQrZAus8sUPluhFE8IOLKq9hIAclz0NAJDlT5VvrZBWGqLeTzaNr3FgI53Gj96YtLrUtwDk1ejsbCDMjrgKcO7MUq78MtBaMB0pZC19kXwWMAXGm1VIZD' # account_id = 'act_100311700797020' api = FacebookAdsApi.init(access_token=access_token) account = AdAccount(account_id) image = AdImage(parent_id=account_id, api=api) image[AdImage.Field.filename] = '3373_ho_00_p_2048x1536.jpg' image["object_story_spec"] = {"page_id": page_id} image.remote_create() # Then, use the image hash returned from above creative = AdCreative(parent_id=account_id) creative[AdCreative.Field.title] = 'hotel alchemy' creative[AdCreative.Field.body] = 'Best buy' creative[AdCreative.Field.object_url] = 'https://gale.agency' creative[AdCreative.Field.image_hash] = image['hash'] # Finally, create your ad along with ad creative. # Please note that the ad creative is not created independently, rather its # data structure is appended to the ad group ad = Ad(parent_id=account_id) ad[Ad.Field.name] = 'My Ad' ad[Ad.Field.adset_id] = 23843011472840629 ad[Ad.Field.creative] = creative ad.remote_create(params={ 'status': Ad.Status.paused, })
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)
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.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'], }
# 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.adcreative import AdCreative from facebook_business.adobjects.adpreview import AdPreview from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<AD_CREATIVE_ID>' FacebookAdsApi.init(access_token=access_token) fields = [] params = { 'ad_format': 'DESKTOP_FEED_STANDARD', 'product_item_ids': ['<productItemID>'], 'dynamic_customization': { 'language': 'fr_XX', 'country': 'FR' }, } print AdCreative(id).get_previews( fields=fields, params=params, )
dict1['page_id'] = '1357440557629733' dict1['Image_hash'] = '8bf45e74d7155516987488fb74bd0d01' dict1['Image_hash_id'] = '373503683609460:8bf45e74d7155516987488fb74bd0d01' dict1[ 'url'] = "https://scontent.fixc2-1.fna.fbcdn.net/v/t45.1600-4/106421921_120330000452704003_663442688879659474_n.jpg?_nc_cat=103&_nc_sid=2aac32&_nc_ohc=p467-ZOxvxsAX9ldzSc&_nc_ht=scontent.fixc2-1.fna&oh=aa9117fe9cc3f03ac857dc880843588c&oe=5F1E5CEC" from facebook_business.api import FacebookAdsApi from facebook_business.adobjects.ad import Ad from facebook_business.adobjects.adcreative import AdCreative from facebook_business.adobjects.adcreative import AdCreative from facebook_business.adobjects.adcreativelinkdata import AdCreativeLinkData from facebook_business.adobjects.adcreativeobjectstoryspec import AdCreativeObjectStorySpec FacebookAdsApi.init(access_token=dict1['my_access_token']) link_data = AdCreativeLinkData() link_data[AdCreativeLinkData.Field.message] = 'try it out' link_data[AdCreativeLinkData.Field. link] = 'https://www.facebook.com/chdanimallovers/' link_data[AdCreativeLinkData.Field.image_hash] = dict1['Image_hash'] link_data[AdCreativeLinkData.Field. description] = 'https://www.facebook.com/chdanimallovers/' # link_data[AdCreativeLinkData.Field.call_to_action] = 'Like Page' object_story_spec = AdCreativeObjectStorySpec() object_story_spec[AdCreativeObjectStorySpec.Field.page_id] = dict1['page_id'] object_story_spec[AdCreativeObjectStorySpec.Field.link_data] = link_data creative = AdCreative(parent_id=dict1['account_id']) print(creative) creative[AdCreative.Field.name] = 'AdCreative for Link Ad' creative[AdCreative.Field.object_story_spec] = object_story_spec creative.remote_create() print(creative)