Esempio n. 1
0
	def create_ads(self, fb_account_id, fb_adset_id, fb_creative_id, logger):
		""" create multi ads in one adset with one creative"""
		error_reasons = []
		ad_infos = []
		ad_error_infos = []
		try:
			api_batch = self.api.new_batch()

			def callback_success(response, ad_info = []):
				''' nothing to do for success'''
				pass

			def callback_failure(response, ad_info = [], error_reasons = [], ad_error_infos = []):
				''' add ad_id to fail_list'''
				error_info_dict = {}
				response_error = response.error()
				error_info_dict['body']= response_error.body()
				try:
					error_user_msg = error_info_dict['body']['error']['error_user_msg']
				except Exception as e:
					error_reasons.append(error_info_dict)
				else:
					error_reasons.append(error_user_msg)
				ad_error_infos.append(ad_info)

			count = 0
			MAX_ADSET_NUM_PER_BATCH = 25
			for i in range(100):
				
				callback_failure = partial(
					callback_failure,
					ad_info = ad_info,
					error_reasons = error_reasons,
					ad_error_infos = ad_error_infos,
				)
				callback_success = partial(
					callback_success,
					ad_info = ad_info,
				)

				ad = Ad(parent_id='act_' + str(fb_account_id))
				ad.update({
					Ad.Field.name: 'test_ad',
					Ad.Field.status: Ad.Status.active,
					Ad.Field.ad_id: fb_ad_id,
					Ad.Field.creative: {
						Ad.Field.Creative.creative_id: fb_creative_id,
					},
				})
				ad.remote_create(batch=api_batch, success=callback_success, failure=callback_failure,)

				count = count + 1
				if count > MAX_ADSET_NUM_PER_BATCH:
					api_batch.execute()
					api_batch = self.api.new_batch()
					count = 0
			api_batch.execute()

		except Exception as e:
			logger.exception(e)
Esempio n. 2
0
    def s5_create_ad(self, accountid, name, adsetid, creativeid, appinfo):
        """
        Step 5: finally create the ad within our campaign, ad set and creative.
        See
        [Ad Group](https://developers.facebook.com/docs/marketing-api/adgroup)
        for further details on the API used here.
        """
        ad = Ad(parent_id=accountid)
        ad[Ad.Field.name] = name
        ad[Ad.Field.adset_id] = adsetid
        ad[Ad.Field.creative] = {'creative_id': str(creativeid)}

        tracking_specs = [
            {'action.type': ['mobile_app_install'],
             'application': [appinfo['fbapplication_id']]},
            {'action.type': ['app_custom_event'],
             'application': [appinfo['fbapplication_id']]}
        ]

        ad[Ad.Field.tracking_specs] = tracking_specs

        ad.remote_create(params={
            'status': Ad.Status.paused
        })
        return ad[Ad.Field.id]
Esempio n. 3
0
	def delete_ad(self, fb_ad_id, logger):
		""" delete ad"""
		try:
			logger.debug('delete fb_ad_id %d' % fb_ad_id)
			if fb_ad_id > 0:
				ad = Ad(str(fb_ad_id))
				ad.remote_delete()

		except Exception as e:
			logger.exception(e)
Esempio n. 4
0
 def gen_ad_preview(self,
                    ad_id,
                    ad_format='MOBILE_FEED_STANDARD'):  # ?string
     if not ad_id:
         return None
     if ad_format is None:
         ad_format = 'MOBILE_FEED_STANDARD'
     ad = Ad(ad_id)
     params = {'ad_format': ad_format}
     preview = ad.get_ad_preview(None, params)
     return preview.get_html()
Esempio n. 5
0
 def createAd(self, name, adset, adcrea, status):
     ad = Ad()
     params = {
         Ad.Field.name: name,
         Ad.Field.adset_id: adset.get_id_assured(),
         Ad.Field.creative: adcrea,
         Ad.Field.redownload: True,
         Ad.Field.status: status
     }
     ad.api_create(parent_id=self.get_id_assured(), params=params)
     return ad
def get_ad_insights(ad):
    ad = Ad(ad)
    params = {
        'time_range': {
            'since': '2015-04-01',
            'until': '2015-04-03',
        },
        'time_increment': 1,
    }
    insights = ad.get_insights(params=params)
    return insights
def get_ad_info(ad):
    ad = Ad(ad)
    fields = [
        Ad.Field.id,
        Ad.Field.adset_id,
        Ad.Field.creative,
        Ad.Field.name,
        Ad.Field.conversion_specs,
        Ad.Field.created_time,
    ]
    ad.remote_read(fields=fields)
    return ad
Esempio n. 8
0
	def create_ad(self, fb_account_id, fb_adset_id, fb_creative_id, logger):
		""" create ad"""
		try:
			ad = Ad(parent_id='act_' + str(fb_account_id))
			ad.update({
				Ad.Field.name: 'test_ad',
				Ad.Field.status: Ad.Status.active,
				Ad.Field.adset_id: fb_adset_id,
				Ad.Field.creative: {
					Ad.Field.Creative.creative_id: fb_creative_id,
				},
			})
			ad.remote_create()

		except Exception as e:
			logger.exception(e)
Esempio n. 9
0
def create_ad(ad_set=None, creative=None):
    if ad_set is None:
        ad_set = create_adset()

    if creative is None:
        creative = create_creative()

    ad = Ad(parent_id=test_config.account_id)
    ad[Ad.Field.name] = unique_name('My Ad')
    ad[Ad.Field.adset_id] = ad_set.get_id_assured()
    ad['status'] = Ad.Status.paused
    ad[Ad.Field.creative] = {
        'creative_id': creative.get_id_assured(),
    }
    ad.remote_create()

    atexit.register(remote_delete, ad)

    return ad
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.

# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from examples.docs import fixtures

ad_id = fixtures.create_ad().get_id()

# _DOC open [ADGROUP_READ_CONVERSION_BID]
# _DOC vars [ad_id]
from facebookads.objects import Ad

ad = Ad(ad_id)
ad.remote_read(fields=[Ad.Field.conversion_specs, 'bid_type'])
# _DOC close [ADGROUP_READ_CONVERSION_BID]
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.

# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from examples.docs import fixtures

ad_id = fixtures.create_ad().get_id()

# _DOC open [ADGROUP_UPDATE_STATUS]
# _DOC vars [ad_id]
from facebookads.objects import Ad

ad = Ad(ad_id)
ad.remote_update(params={
    'status': Ad.Status.paused,
})
# _DOC close [ADGROUP_UPDATE_STATUS]
Esempio n. 12
0
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.

# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from examples.docs import fixtures

ad_id = fixtures.create_ad().get_id()

# _DOC open [ADGROUP_READ]
# _DOC vars [ad_id]
from facebookads.objects import Ad

ad = Ad(ad_id)
ad.remote_read(fields=[Ad.Field.name])
# _DOC close [ADGROUP_READ]
# DEALINGS IN THE SOFTWARE.

from examples.docs import fixtures
from facebookads import test_config

ad_account_id = test_config.account_id
ad_set_id = fixtures.create_adset().get_id()
creative_id = fixtures.create_creative().get_id()
pixel_id = fixtures.create_ad_conversion_pixel().get_id()

# !_DOC [pruno]
# _DOC open [ADGROUP_CREATE_TRACKING_ADCONVERSIONPIXELS]
# _DOC vars [ad_account_id:s, ad_set_id, creative_id, pixel_id]
from facebookads.objects import Ad

ad = Ad(parent_id=ad_account_id)
ad.update({
    Ad.Field.name: 'test',
    Ad.Field.adset_id: ad_set_id,
    Ad.Field.creative: {
        'creative_id': creative_id,
    },
    Ad.Field.tracking_specs: {
        'action.type': 'offsite_conversion',
        'offsite_pixel': pixel_id,
    },
})
ad.remote_create()
# _DOC close [ADGROUP_CREATE_TRACKING_ADCONVERSIONPIXELS]

ad.remote_delete()
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.

# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from examples.docs import fixtures

ad_id = fixtures.create_ad().get_id()

# _DOC open [ADGROUP_READ_ADLABELS]
# _DOC vars [ad_id]
from facebookads.objects import Ad

ad = Ad(ad_id)
ad.remote_read(fields=[Ad.Field.adlabels])
# _DOC close [ADGROUP_READ_ADLABELS]
# 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_id = fixtures.create_ad().get_id()

# _DOC oncall [pruno]
# _DOC open [ADGROUP_GET_INSIGHTS_PLACE_PAGE_ID]
# _DOC vars [ad_id]
from facebookads.objects import Ad, Insights

fields = [
    Insights.Field.impressions,
    Insights.Field.call_to_action_clicks,
]

params = {
    'breakdowns': Insights.Breakdown.place_page_id,
}

ad = Ad(ad_id)
insights = ad.get_insights(fields, params)
# _DOC close [ADGROUP_GET_INSIGHTS_PLACE_PAGE_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)
# 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
from facebookads.objects import AdLabel

ad_label_id = fixtures.create_adlabel().get_id()
ad_label_name = fixtures.create_adlabel()[AdLabel.Field.name]
ad_id = fixtures.create_ad().get_id()

# _DOC oncall [ritu]
# _DOC open [ADGROUP_UPDATE_LABELS]
# _DOC vars [ad_id, ad_label_id, ad_label_name:s]
from facebookads.objects import Ad, AdLabel

ad = Ad(ad_id)
ad[Ad.Field.adlabels] = [
    {AdLabel.Field.id: ad_label_id},
    {AdLabel.Field.name: ad_label_name},
]
ad.remote_update()
# _DOC close [ADGROUP_UPDATE_LABELS]
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.

# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from examples.docs import fixtures

ad_id = fixtures.create_ad().get_id()

# _DOC open [ADGROUP_GET_PREVIEW_MOBILE_INTERSTITIAL]
# _DOC vars [ad_id]
from facebookads.objects import Ad, AdPreview

ad = Ad(ad_id)
ad.get_ad_preview(params={
    'ad_format': AdPreview.AdFormat.mobile_interstitial,
})
# _DOC close [ADGROUP_GET_PREVIEW_MOBILE_INTERSTITIAL]
# 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_id = fixtures.create_ad().get_id()

# _DOC oncall [raven]
# _DOC open [ADGROUP_GET_LEADS_FILTER]
# _DOC vars [ad_id]
from facebookads.objects import Ad
import datetime

yesterday = datetime.date.today() - datetime.timedelta(1)
timestamp = yesterday.strftime("%s")

ad = Ad(ad_id)
leads = ad.get_leads(params={"filtering": [{"field": "time_created", "operator": "GREATER_THAN", "value": timestamp}]})
# _DOC close [ADGROUP_GET_LEADS_FILTER]
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.

# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from examples.docs import fixtures

ad_id = fixtures.create_ad().get_id()

# _DOC open [ADGROUP_ARCHIVE]
# _DOC vars [ad_group_id]
from facebookads.objects import Ad

ad = Ad(ad_id)
ad.remote_archive()
# _DOC close [ADGROUP_ARCHIVE]
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.

# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from examples.docs import fixtures

ad_id = fixtures.create_ad().get_id()

# _DOC open [ADGROUP_GET_PREVIEW_MOBILE_BANNER]
# _DOC vars [ad_id]
from facebookads.objects import Ad, AdPreview

ad = Ad(ad_id)
ad.get_ad_preview(params={
    'ad_format': AdPreview.AdFormat.mobile_banner,
})
# _DOC close [ADGROUP_GET_PREVIEW_MOBILE_BANNER]
Esempio n. 22
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]
# 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 facebookads import test_config
from examples.docs import fixtures

ad_account_id = test_config.account_id
test_ad = fixtures.create_ad()
ad_id = test_ad.get_id_assured()

# _DOC oncall [duliomatos]
# _DOC open [ADGROUP_GET_REACHESTIMATE]
# _DOC vars [ad_id]
from facebookads.objects import Ad

ad = Ad(ad_id)
reach_estimate = ad.get_reach_estimate()
print(reach_estimate)
# _DOC close [ADGROUP_GET_REACHESTIMATE]
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.

# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from examples.docs import fixtures

ad_id = fixtures.create_ad().get_id()

# _DOC open [ADGROUP_DELETE]
# _DOC vars [ad_id]
from facebookads.objects import Ad

ad = Ad(ad_id)
ad.remote_delete()
# _DOC close [ADGROUP_DELETE]
# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from examples.docs import fixtures

ad_id = fixtures.create_ad().get_id()

# _DOC open [ADGROUP_GET_TARGETING_DESCRIPTION]
# _DOC vars [ad_id]
from facebookads.objects import Ad

ad = Ad(ad_id)
targeting_description = ad.get_targeting_description()

# Output the targeting description
for description in targeting_description['targetingsentencelines']:
    print(description['content'])
    for child in description['children']:
        print("\t" + child)
# _DOC close [ADGROUP_GET_TARGETING_DESCRIPTION]
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.

# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from examples.docs import fixtures

ad_id = fixtures.create_ad().get_id()
ad_label_id = fixtures.create_adlabel().get_id()

# _DOC open [ADGROUP_REMOVE_LABELS]
# _DOC vars [ad_id, ad_label_id]
from facebookads.objects import Ad

ad = Ad(ad_id)
adlabels = [ad_label_id]
ad.remove_labels(adlabels)
# _DOC close [ADGROUP_REMOVE_LABELS]
    print("**** DONE: Image uploaded:")
    pp.pprint(img)  # The image hash can be found using img[AdImage.Field.hash]

    ### Create a creative.
    creative = AdCreative(parent_id=my_account.get_id_assured())
    creative.update({
        AdCreative.Field.title: 'Visit Seattle',
        AdCreative.Field.body: 'Beautiful Puget Sound!',
        AdCreative.Field.object_url: 'http://www.seattle.gov/visiting/',
        AdCreative.Field.image_hash: img.get_hash(),
    })
    creative.remote_create()
    print("**** DONE: Creative created:")
    pp.pprint(creative)

    ### Get excited, we are finally creating an ad!!!
    ad = Ad(parent_id=my_account.get_id_assured())
    ad.update({
        Ad.Field.name: 'Puget Sound impression ad',
        Ad.Field.adset_id: ad_set.get_id_assured(),
        Ad.Field.creative: {
            Ad.Field.Creative.creative_id: creative.get_id_assured(),
        },
    })
    ad.remote_create(params={
                        'status': AdSet.Status.paused,
                    })
    print("**** DONE: Ad created:")
    pp.pprint(ad)

from facebookads.objects import Ad
from facebookads.adobjects.campaign import Campaign
import header
import create_adset
import dynamic_cards

choice = raw_input(
    "Please enter yes to create a new Adset or enter no to choose existing one.\n"
).lower()
if 'yes' in choice:
    adset_id = create_adset.create_adset()
else:
    adset_id = raw_input("Please enter adset id.\n")
dynamic_cards.create_creative()
ad = Ad(parent_id=header.my_account['id'])
ad[Ad.Field.name] = 'My Ad'
ad[Ad.Field.adset_id] = adset_id
ad[Ad.Field.status] = Campaign.Status.paused
ad[Ad.Field.creative] = {'creative_id': str(dynamic_cards.creative['id'])}
ad.remote_create()
print ad[Ad.Field.success]
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.

# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from examples.docs import fixtures

ad_id = fixtures.create_ad().get_id()
ad_label_id = fixtures.create_adlabel().get_id()

# _DOC open [ADGROUP_ADD_LABELS]
# _DOC vars [ad_group_id, ad_label_id]
from facebookads.objects import Ad

ad = Ad(ad_id)
adlabels = [ad_label_id]
ad.add_labels(adlabels)
# _DOC close [ADGROUP_ADD_LABELS]
# 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
from facebookads import test_config

ad_account_id = test_config.account_id
ad_set_id = fixtures.create_adset().get_id()
creative_id = fixtures.create_creative().get_id()

# _DOC open [ADGROUP_CREATE_REDOWNLOAD]
# _DOC vars [ad_set_id, creative_id, ad_account_id:s]
from facebookads.objects import Ad

ad = Ad(parent_id=ad_account_id)
ad[Ad.Field.name] = 'My Ad'
ad[Ad.Field.adset_id] = ad_set_id
ad[Ad.Field.creative] = {'creative_id': creative_id}
ad[Ad.Field.redownload] = True
ad.remote_create(params={
    'status': Ad.Status.paused,
})
# _DOC close [ADGROUP_CREATE_REDOWNLOAD]

ad.remote_delete()
# 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
ad_set_id = fixtures.create_adset().get_id()
creative_id = fixtures.create_creative().get_id()
pixel_id = fixtures.create_ads_pixel().get_id()

# _DOC open [ADGROUP_CREATE_OFFSITE_CONVERSION_TRACKING]
# _DOC vars [ad_account_id:s, ad_set_id, creative_id, pixel_id]
from facebookads.objects import Ad

ad = Ad(parent_id=ad_account_id)
ad.update({
    Ad.Field.adset_id: ad_set_id,
    Ad.Field.name: 'Offsite Conversions Ad',
    Ad.Field.creative: {
        'creative_id': creative_id,
    },
    Ad.Field.tracking_specs: [
        {
            'action.type': 'offsite_conversion',
            'fb_pixel': pixel_id,
        },
    ],
})
ad.remote_create(params={
    'status': Ad.Status.paused,
def create_carousel_ad(caption, adset_id, ad_name, times, design_list,
                       account_id, land_on_design, url, campaign_tag):
    logger = logging.getLogger('testlogger')
    logger.debug("In create carousel")
    conn = None
    simple_list = []
    account_medium_list = {
        "act_940036526039709": "fb_ocpc",
        "act_938286879548007": "acpm",
        "act_1010404049002956": "acpm",
        "act_1385041538425866": "acpm",
        "act_1128744890502204": "jcpc",
        "act_10152414205523137": "int",
        "act_972844956092199": "exp"
    }
    utm_medium = account_medium_list[account_id]
    try:
        urlparse.uses_netloc.append("postgres")
        database_url = urlparse.urlparse(constants.database_url)
        conn = psycopg2.connect(database=database_url.path[1:],
                                user=database_url.username,
                                password=database_url.password,
                                host=database_url.hostname,
                                port=database_url.port)
        curr = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        for i in xrange(times):
            design_id = design_list[i]
            curr.execute(
                'SELECT discount_percent,designer_id from designs where id=' +
                str(design_id))
            row = curr.fetchone()
            curr.execute(
                'SELECT id,photo_file_name FROM images where design_id = ' +
                str(design_id))
            rows = curr.fetchone()
            curr.execute(
                'SELECT name FROM "categories" INNER JOIN "categories_designs" ON "categories"."id" = "categories_designs"."category_id" WHERE design_id ='
                + str(design_id))
            category_name = curr.fetchone()
            image_link = image_hash.get_image_link(rows['photo_file_name'],
                                                   rows['id'])
            if row['discount_percent'] is None:
                row['discount_percent'] = 0
            product1 = AdCreativeLinkDataChildAttachment()
            if land_on_design:
                product1[
                    AdCreativeLinkDataChildAttachment.Field.
                    link] = 'www.mirraw.com/designers/' + str(
                        row['designer_id']
                    ) + '/designs/' + str(
                        design_id
                    ) + '?utm_source=facebook-auto&utm_medium=' + utm_medium + '&utm_campaign=' + campaign_tag
            else:
                product1[
                    AdCreativeLinkDataChildAttachment.Field.
                    link] = url + '?pid=' + str(
                        design_id
                    ) + '&utm_source=facebook&utm_medium=' + utm_medium + '&utm_campaign=' + campaign_tag
            product1[AdCreativeLinkDataChildAttachment.Field.
                     name] = category_name['name']
            action = AdCreativeLinkDataCallToAction()
            link_value = AdCreativeLinkDataCallToActionValue()
            link_value[AdCreativeLinkDataCallToActionValue.Field.
                       link_title] = 'Discount ' + str(
                           row['discount_percent']) + '%'
            action[AdCreativeLinkDataCallToAction.Field.
                   type] = AdCreativeLinkDataCallToAction.Type.shop_now
            action[AdCreativeLinkDataCallToAction.Field.value] = link_value
            product1[AdCreativeLinkDataChildAttachment.Field.
                     call_to_action] = action
            product1[AdCreativeLinkDataChildAttachment.Field.
                     description] = 'Discount ' + str(
                         row['discount_percent']) + '%'
            product1[AdCreativeLinkDataChildAttachment.Field.
                     image_hash] = image_hash.get_image_hash(
                         image_link, rows[1], account_id)
            sleep(0.5)
            simple_list.append(product1)

        link = AdCreativeLinkData()
        link[
            link.Field.
            link] = url + '&utm_source=facebook&utm_medium=' + utm_medium + '&utm_campaign=' + campaign_tag
        link[link.Field.child_attachments] = simple_list
        link[
            link.Field.
            caption] = url + '&utm_source=facebook&utm_medium=' + utm_medium + '&utm_campaign=' + campaign_tag
        call_to_action_button = AdCreativeLinkDataCallToAction()
        call_to_action_button[
            AdCreativeLinkDataCallToAction.Field.
            type] = AdCreativeLinkDataCallToAction.Type.shop_now
        link[link.Field.call_to_action] = call_to_action_button
        link[link.Field.message] = caption

        logger.info(link)
        story = AdCreativeObjectStorySpec()
        story[story.Field.page_id] = constants.page_id
        story[story.Field.link_data] = link

        creative = AdCreative(parent_id=account_id)
        creative[AdCreative.Field.name] = 'MPA Creative'
        creative[AdCreative.Field.object_story_spec] = story
        creative.remote_create()
        creative = json.loads(str(creative).replace('<AdCreative> ', ''))

        logger.info(creative)
        ad = Ad(parent_id=account_id)
        ad[Ad.Field.name] = ad_name
        ad[Ad.Field.adset_id] = adset_id
        ad[Ad.Field.status] = Campaign.Status.paused
        ad[Ad.Field.creative] = {'creative_id': str(creative['id'])}
        logger.info('Creating Ad')
        ad.remote_create()
        logger.info(ad)

    except psycopg2.DatabaseError, e:
        logger.error('Error %s' % e)
        return False
Esempio n. 33
0
def create_carousel_ad(caption, adset_id, ad_name, design_list, land_on_design,
                       url, campaign_tag, country_code):
    FORMAT = '%(name)s:%(levelname)s:%(asctime)-15s:%(message)s'
    logging.basicConfig(filename='%s-facebook-automated.log' % date.today(),
                        format=FORMAT,
                        level=logging.DEBUG)
    logging.getLogger('create_carousel')
    logging.info('In create carousel')
    connection = None
    simple_list = []
    utm_medium = 'exp'
    try:
        connection = header.create_connection(
            os.environ['FB_APP_DATABASE_URL'])
        cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
        for design_id in design_list:
            cursor.execute(
                'SELECT designer_id,discount_price from designs where id=' +
                str(design_id[0]))
            row = cursor.fetchone()
            cursor.execute(
                'SELECT id,photo_file_name FROM images where design_id = ' +
                str(design_id[0]))
            rows = cursor.fetchone()
            cursor.execute(
                'SELECT name FROM "categories" INNER JOIN "categories_designs" ON "categories"."id" = "categories_designs"."category_id" WHERE design_id ='
                + str(design_id[0]))
            category_name = cursor.fetchone()
            cursor.execute(
                "SELECT rate FROM currency_converts WHERE country_code = '" +
                country_code + "'")
            rate = cursor.fetchone()
            image_link = image_hash.get_image_link(rows['photo_file_name'],
                                                   rows['id'])
            product1 = AdCreativeLinkDataChildAttachment()
            if land_on_design:
                product1[
                    AdCreativeLinkDataChildAttachment.Field.
                    link] = 'www.mirraw.com/designers/' + str(
                        row['designer_id']
                    ) + '/designs/' + str(
                        design_id[0]
                    ) + '?utm_source=facebook-auto&utm_medium=' + utm_medium + '&utm_campaign=' + campaign_tag
            else:
                product1[
                    AdCreativeLinkDataChildAttachment.Field.
                    link] = url + '?pid=' + str(
                        design_id
                    ) + '&utm_source=facebook&utm_medium=' + utm_medium + '&utm_campaign=' + campaign_tag
            product1[AdCreativeLinkDataChildAttachment.Field.
                     name] = category_name['name']
            price = (row['discount_price'] * 1.0 / rate['rate'])
            product1[AdCreativeLinkDataChildAttachment.Field.
                     description] = 'Price: $' + str(round(price, 2))
            logging.info(image_link)
            logging.info(rows['photo_file_name'])
            product1[AdCreativeLinkDataChildAttachment.Field.
                     image_hash] = image_hash.get_image_hash(
                         image_link, rows['photo_file_name'])
            sleep(10)
            simple_list.append(product1)

        link = AdCreativeLinkData()
        link[link.Field.link] = 'www.mirraw.com'
        link[link.Field.child_attachments] = simple_list
        link[link.Field.caption] = caption

        story = AdCreativeObjectStorySpec()
        story[story.Field.page_id] = header.page_id
        story[story.Field.link_data] = link

        creative = AdCreative(parent_id=header.my_account['id'])
        creative[AdCreative.Field.name] = 'MPA Creative'
        creative[AdCreative.Field.object_story_spec] = story
        creative.remote_create()
        creative = json.loads(str(creative).replace('<AdCreative> ', ''))

        ad = Ad(parent_id=header.my_account['id'])
        ad[Ad.Field.name] = ad_name
        ad[Ad.Field.adset_id] = adset_id
        ad[Ad.Field.status] = Campaign.Status.paused
        ad[Ad.Field.creative] = {'creative_id': str(creative['id'])}
        logging.info('Creating Ad')
        ad.remote_create()
        logging.info(ad)

    except psycopg2.DatabaseError, e:
        logging.error('Error %s' % e)
        return False
Esempio n. 34
0
    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'],
        }
    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
# 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
ad_set_id = fixtures.create_adset().get_id()
creative_id = fixtures.create_creative().get_id()

# _DOC open [ADGROUP_CREATE_TRACKING_LIKE_MENTIONS]
# _DOC vars [ad_account_id:s, ad_set_id, creative_id, post_id, page_id]
from facebookads.objects import Ad

ad = Ad(parent_id=ad_account_id)
ad[Ad.Field.name] = 'test'
ad[Ad.Field.adset_id] = ad_set_id
ad[Ad.Field.creative] = {
    'creative_id': creative_id
}
ad[Ad.Field.tracking_specs] = {
    'action.type': ['like', 'mention'],
    'page': page_id
}
ad.remote_create()
# _DOC close [ADGROUP_CREATE_TRACKING_LIKE_MENTIONS]

ad.remote_delete()
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.

# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from examples.docs import fixtures

ad_id = fixtures.create_ad().get_id()

# _DOC oncall [pruno]
# _DOC open [ADGROUP_GET_LEADS]
# _DOC vars [ad_id]
from facebookads.objects import Ad

ad = Ad(ad_id)
leads = ad.get_leads()
# _DOC close [ADGROUP_GET_LEADS]