def image_upload(image_path):
    files = list()
    image_path = unidecode(image_path)
    print(image_path)
    if not os.path.isfile(f'samples/images/{image_path}.png'):
        for file in os.listdir('samples/images/'):
            if file.startswith(image_path.split('_')[0]):
                files.append(file)
        for file in os.listdir('samples/images/'):
            if file.startswith(image_path[0:3]):
                files.append(file)
        if not files:
            for file in os.listdir('samples/images/'):
                if file.startswith(image_path[0]):
                    files.append(file)
        # pprint(files)
        # image_path = input('Set valid path: ')
        image_path = files[0]

    FacebookAdsApi.init(access_token=my_access_token)
    image = AdImage(parent_id=f'act_{ad_account}')
    if image_path.endswith('.png'):
        image[AdImage.Field.filename] = f'samples/images/{image_path}'
    else:
        image[AdImage.Field.filename] = f'samples/images/{image_path}.png'
    image.remote_create()
    image_hash = image[AdImage.Field.hash]
    return image_hash
 def upload_ad_image(self, accountid, imagefilepath):
     """
     Step 1: upload an ad image. See
     [Ad Image](https://developers.facebook.com/docs/marketing-api/adimage)
     for further details on the API used here.
     """
     image = AdImage(parent_id=accountid)
     image[AdImage.Field.filename] = imagefilepath
     image.remote_create()
     return image[AdImage.Field.hash]
Beispiel #3
0
 def s1_upload_ad_images(self, accountid, imagefilepaths):
     """
     Step 1: upload an images for the carousel. See
     [Ad Image](https://developers.facebook.com/docs/marketing-api/adimage)
     for further details on the API used here.
     """
     result = []
     for imagefilepath in imagefilepaths:
         image = AdImage(parent_id=accountid)
         image[AdImage.Field.filename] = imagefilepath
         image.remote_create()
         result.append(image[AdImage.Field.hash])
     return result
Beispiel #4
0
    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
Beispiel #5
0
def create_image_hash(my_app_id=dict1['my_app_id'],
                      my_app_secret=dict1['my_app_secret'],
                      my_access_token=dict1['my_access_token'],
                      account_id=dict1['account_id'],
                      Image_path=dict1['image_path']):

    FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)

    account = AdAccount(account_id)
    image = AdImage()
    image2 = AdImage(parent_id=None)
    image[AdImage.Field.filename] = Image_path
    image.remote_create()

    # Output image Hash
    print(image[AdImage.Field.hash])
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 hashedImage():
  image = AdImage(parent_id=my_account_id)
  image[AdImage.Field.filename] = 'Oxford_neu.jpg'
  image.remote_create()
  hashed = image[AdImage.Field.hash]
  return   hashed
Beispiel #8
0
    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 = {
                Targeting.Field.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
Beispiel #9
0
    'bid_amount': 10,
    'targeting': {
        'geo_locations': {
            'countries': {'TR'}
        },
        'publisher_platforms': 'facebook'
    },
    'start_time': 'ENTER START DATE HERE',
    'end_time': 'ENTER END DATE HERE',
})
adset.remote_create(params={'status': 'ACTIVE'})

# upload image
image = AdImage(parent_id=ad_account_id)
image[AdImage.Field.filename] = 'ENTER AD IMAGE PATH HERE'
image.remote_create()
image_hash = image[AdImage.Field.hash]

# create ad creative
fields = []
params = {
    'name': 'ENTER CREATIVE NAME HERE',
    'object_story_spec': {
        'page_id': page_id,
        'link_data': {
            'image_hash': image_hash,
            'link': 'ENTER FACEBOOK PAGE LINK-PAGE_ID HERE',
            'message': 'ENTER AD MESSAGE HERE'
        }
    },
}
Beispiel #10
0
def createImageHash(my_app_id,my_app_secret,account_id,my_access_token):
    image = AdImage(parent_id=dict1['account_id'])
    image[AdImage.Field.filename] = 'test.jpg'
    image.remote_create()
    # Output image Hash
    print(image[AdImage.Field.hash])
Beispiel #11
0
 def createImageFromResources(self, image_path):
     img = AdImage(parent_id=self.account_id)
     img[AdImage.Field.filename] = image_path
     img.remote_create()
     return img
Beispiel #12
0
    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]
Beispiel #13
0
def create_adset(adset_name, publisher_platform, ad_name, camp_id):
    today = datetime.date.today()
    start_time = str(today)
    end_time = str(today + datetime.timedelta(weeks=1))

    adset = AdSet(parent_id=RC.AD_ACCOUNT_ID)
    adset.update({
        'name': adset_name,
        'campaign_id': camp_id,
        'daily_budget': 20978,
        'billing_event': 'IMPRESSIONS',
        'optimization_goal': 'REACH',
        'bid_amount': 10,
        'targeting': {
            'geo_locations': {
                'countries': 'TR'
            }
        },
        'publisher_platforms': publisher_platform,
        'start_time': start_time,
        'end_time': end_time,
    })

    adset.remote_create(params={'status': 'PAUSED'})

    image = AdImage(parent_id=RC.AD_ACCOUNT_ID)
    image[AdImage.Field.
          filename] = '/Users/geofe/Pictures/Wallpapers/Be_original.jpg'
    image.remote_create()

    image_hash = image[AdImage.Field.hash]
    print(image_hash)
    fields = []
    params = {
        'name': 'Test image',
        'object_story_spec': {
            'page_id': RC.PAGE_ID,
            'link_data': {
                'image_hash': image_hash,
                'link':
                'https://www.facebook.com/API-Chop-Shop-for-Botty-106905097700335/',
                'message': 'Test '
            }
        },
    }
    adcreative = AdAccount(RC.AD_ACCOUNT_ID).create_ad_creative(fields=fields,
                                                                params=params)

    print(adcreative)
    fields = []
    params = {
        'name': ad_name,
        'adset_id': adset['id'],
        'creative': {
            'creative_id': adcreative['id']
        },
        'status': 'PAUSED'
    }

    print(AdAccount(RC.AD_ACCOUNT_ID).create_ad(fields=fields, params=params))
    print(
        "---------------------------------------AdSet-{} created Successfull !---------------------------------------"
        .format(adset['id']))
    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'],
        }
Beispiel #16
0
def index():

    if request.method == 'POST':
        '''
        store data from the HTML form into Flask's request

        Docs: https://flask.palletsprojects.com/en/1.1.x/api/#flask.Request
        '''

        campaign_name = request.form['campaign_name']
        location = request.form['location']
        demographics_age_min = request.form['age_max']
        demographics_age_max = request.form['age_min']
        adset_name = request.form['adset_name']
        image_path = 'image_path'
        image_link = 'ENTER THE URL FOR THE FACEBOOK PAGE THAT IS POPULATING ADS'
        creative_name = request.form['creative_name']
        ad_name = request.form['ad_name']
        gender = request.form['gender']

        print(campaign_name)
        print(location)
        '''
        mysql query to populate db. (had to create the db with fields first using MySQL workbench)

        '''
        mycursor.execute(
            "INSERT INTO adsData (campaign_name, location, age_min, age_max, ad_name, Gender) VALUES (%s, %s, %s, %s, %s, %s)",
            (campaign_name, location, demographics_age_min,
             demographics_age_max, ad_name, gender))
        mydb.commit()
        '''
        Enter private Facebook app info. Facebook app should be public, not development mode, so as to create ads.
        
        '''
        access_token = 'REPLACE WITH ACCESS TOKEN'
        app_secret = 'REPLACE WITH APP SECRET'
        app_id = 'REPLACE WITH APP ID'
        ad_account_id = 'REPLACE WITH APP ID ACCOUNT'
        page_id = 'REPLACE WITH APP PAGE ID'

        FacebookAdsApi.init(access_token=access_token)

        params = {
            'name': campaign_name,
            'objective': 'POST_ENGAGEMENT',
            'status': 'ACTIVE',
            'special_ad_category': 'NONE',
        }

        #Create a new campaign with the class Campaign
        campaign_result = AdAccount(ad_account_id).create_campaign(
            params=params)
        print(campaign_result)
        '''
        Facebook ad creation prototype. Reference : https://developers.facebook.com/docs/marketing-api/buying-api
        '''
        today = datetime.date.today()
        start_time = str(today)
        end_time = str(today + datetime.timedelta(weeks=1))

        #Define Adset Targeting, Budget, Billing, Optimization, and Duration
        adset = AdSet(parent_id=ad_account_id)
        adset.update({
            'name': adset_name,
            'campaign_id': campaign_result["id"],
            'daily_budget': 150,
            'billing_event': 'IMPRESSIONS',
            'optimization_goal': 'REACH',
            'bid_amount': 10,
            'targeting': {
                'geo_locations': {
                    'countries': location
                },
                "age_min": demographics_age_min,
                "age_max": demographics_age_max,
                'publisher_platforms': 'facebook'
            },
            'start_time': start_time,
            'end_time': end_time,
        })
        fields = []

        adset.remote_create(params={
            'status': AdSet.Status.paused,
        })

        print(adset)
        image = AdImage(parent_id=ad_account_id)
        image[AdImage.Field.filename] = image_path
        image.remote_create()

        image_hash = image[AdImage.Field.hash]
        print(image)

        fields = []
        params = {
            'name': creative_name,
            'object_story_spec': {
                'page_id': page_id,
                'link_data': {
                    'image_hash': image_hash,
                    'link': image_link
                }
            },
        }

        #Provide Ad Creative
        adcreative = AdAccount(ad_account_id).create_ad_creative(fields=fields,
                                                                 params=params)

        fields = []

        params = {
            'name': ad_name,
            'adset_id': adset['id'],
            'creative': {
                'creative_id': adcreative['creative_id']
            },
            'status': 'ACTIVE'
        }
        '''
        create your Facebook ad with Ad. With an Ad you link your AdCreative and AdSet to a new object representing your ad.
        '''
        ad = AdAccount(ad_account_id).create_ad(fields=fields, params=params)

        return render_template('index.html')

    else:

        #return campaign_name, location, demographics_age_min, demographics_age_max, adset_name, image_path, creative_name, ad_name, gender

        return render_template('index.html')