def test_normal(self):
        images = self.images[-3:]  # Only three images needed
        linktitles = ['Title 1', 'Title 2', 'Title 3']
        deeplinks = None

        optimization_goal = 'APP_INSTALLS'
        billing_event = 'IMPRESSIONS'
        bid_amount = 100

        result = self.cmaia_sample.carousel_app_ad_create(
            self.account_id,
            "CMAIA test",  # basename
            "Try my app!",  # message
            images,
            linktitles,
            deeplinks,
            "1000",  # dailybudget,
            self.app_info,
            optimization_goal,
            billing_event,
            bid_amount,
            self.mobile_targeting,
        )

        self.assertIn('campaignid', result)
        self.assertIn('adsetid', result)
        self.assertIn('creativeid', result)
        self.assertIn('adid', result)

        self.campaign = Campaign()
        self.campaign[Campaign.Field.id] = result['campaignid']
        self.campaign.remote_read()
        self.assertEqual(self.campaign.get_id(), result['campaignid'])
	def get_adsets_under_campaign(self, fb_campaign_id, logger):
		""" read all adset under campaign"""
		total_adsets = []
		try:
			campaign = Campaign(str(fb_campaign_id))

			related_adsets_iterator = campaign.get_ad_sets(
				fields=[
					AdSet.Field.id,
					AdSet.Field.status,
					AdSet.Field.name,
					AdSet.Field.bid_amount,
					AdSet.Field.targeting,
				],
			)
			ADSET_BATCH_LIMIT = 25

			# Iterate over batches of active AdCampaign's
			count = 0
			for adsets in self.generate_batches(
				related_adsets_iterator,
				ADSET_BATCH_LIMIT,
			):
				api_batch = self.api.new_batch()
				total_adsets.extend(adsets)

				if len(total_adsets) >= 4 * ADSET_BATCH_LIMIT: # only fetch most 100 adsets
					break

			return total_adsets

		except Exception as e:
			logger.exception(e)
    def test_normal(self):
        optimization_goal = 'APP_INSTALLS'
        billing_event = 'IMPRESSIONS'
        bid_amount = 100
        result = self.maia_sample.create_app_install_ad(
            self.account_id,
            "MAIA Test",  # basename
            "Try my app!",  # message
            self.images[0],
            "1000",  # dailybudget,
            self.page_id,
            optimization_goal,
            billing_event,
            bid_amount,
            self.mobile_targeting,
            self.app_info['fbapplication_id'],
            self.app_info['app_name'],
            self.app_info['appstore_link'],
            self.app_info['app_deep_link'],
        )

        self.assertIn('campaign_id', result)
        self.assertIn('adset_id', result)
        self.assertIn('creative_id', result)
        self.assertIn('ad_id', result)

        self.campaign = Campaign()
        self.campaign[Campaign.Field.id] = result['campaign_id']
        self.campaign.remote_read()
        self.assertEqual(self.campaign.get_id(), result['campaign_id'])
Beispiel #4
0
    def test_normal(self):

        optimization_goal = 'LINK_CLICKS'
        billing_event = 'LINK_CLICKS'
        bid_amount = '100'  # stands for $1.00

        result = self.appengagement_sample.app_engagement_ad_create(
            self.account_id,
            "appengagement_test",  # basename
            "Try my app! Only 8 clicks you are done!",  # message
            self.images[0],
            "500",  # dailybudget stands for $5.00,
            self.app_info,
            optimization_goal,
            billing_event,
            bid_amount,
            self.mobile_targeting)

        self.assertIn('campaignid', result)
        self.assertIn('adsetid', result)
        self.assertIn('creativeid', result)
        self.assertIn('adid', result)

        self.campaign = Campaign()
        self.campaign[Campaign.Field.id] = result['campaignid']
        self.campaign.remote_read()
        self.assertEqual(self.campaign.get_id(), result['campaignid'])
Beispiel #5
0
def campaigns_with_insights(start, end):
    response = []
    try:
        my_session = FacebookSession(my_app_id, my_app_secret, my_access_token)
        my_api = FacebookAdsApi(my_session)
        FacebookAdsApi.set_default_api(my_api)
        me = objects.AdUser(fbid='me')
        my_accounts = list(me.get_ad_accounts())
        my_account = my_accounts[0]
        fields = [
            AdsInsights.Field.clicks, AdsInsights.Field.spend,
            AdsInsights.Field.impressions, AdsInsights.Field.unique_clicks,
            AdsInsights.Field.cost_per_unique_click,
            AdsInsights.Field.cost_per_inline_link_click
        ]

        params = {
            'time_range': {
                'since': start,
                'until': end
            },
            'effective_status': ["ACTIVE"]
        }
        campaigns = my_account.get_campaigns(
            params=params, fields=[Campaign.Field.name, Campaign.Field.status])
        headers = [
            "Name",
            'Cost',
            "Impressions",
            "Clicks",
            "Unique Clicks",
            "Cost per unique click",
        ]
        for i in campaigns:
            try:
                campaign = Campaign(i['id'])
                campaign_data = campaign.get_insights(params=params,
                                                      fields=fields)
                campaign_dict = {
                    'id':
                    i['id'],
                    'name':
                    i['name'],
                    'Cost':
                    campaign_data[0]['spend'],
                    "Clicks":
                    campaign_data[0]['clicks'],
                    "Unique_Clicks":
                    campaign_data[0]['unique_clicks'],
                    "Cost_per_unique_click":
                    campaign_data[0]['cost_per_unique_click'],
                    "Impressions":
                    campaign_data[0]['impressions']
                }
                response.append(campaign_dict)
            except:
                pass
    except:
        pass
    return {'headers': headers, 'rows': response}
Beispiel #6
0
    def test_normal(self):
        result = self.sample.create_lead_ad(
            account_id=self.account_id,
            name="My Awesome Lead Ad",
            page_id=self.page_id,
            form_id=self.form_id,
            optimization_goal='LEAD_GENERATION',
            billing_event='IMPRESSIONS',
            bid_amount=100,
            daily_budget=1000,
            targeting=self.mobile_targeting,
            image_path=self.images[0],
            message="My message",
            link="fb.me/fmd",
            caption="My Caption",
            description="My description",
            cta_type="SIGN_UP")

        self.assertIn('image_hash', result)
        self.assertIn('campaign_id', result)
        self.assertIn('adset_id', result)
        self.assertIn('creative_id', result)
        self.assertIn('ad_id', result)

        self.campaign = Campaign()
        self.campaign[Campaign.Field.id] = result['campaign_id']
        self.campaign.remote_read()
        self.assertEqual(self.campaign.get_id(), result['campaign_id'])
Beispiel #7
0
 def tearDown(self):
     super(TieredLookalikeTestCase, self).tearDown()
     if hasattr(self, 'results'):
         campaign_id = str(self.results['adsets'][0]['campaign_id'])
         campaign = Campaign(campaign_id)
         campaign.remote_delete()
     if hasattr(self, 'tiered_lookalikes'):
         for lookalike in self.tiered_lookalikes:
             lookalike.remote_delete()
def get_adsets_under_campaign(campaign_id):
    campaign = Campaign(campaign_id)
    fields = [
        AdSet.Field.id,
        AdSet.Field.account_id,
        AdSet.Field.name,
    ]
    adsets = campaign.get_ad_sets(fields=fields)
    return adsets
def campaign_lookup(campaign_id):
    campaign = Campaign(campaign_id)
    fields = [
        Campaign.Field.name,
        Campaign.Field.effective_status,
        Campaign.Field.objective,
        Campaign.Field.account_id,
    ]
    campaign.remote_read(fields=fields)
    return campaign
def get_ads_under_campaign(campaign_id):
    campaign = Campaign(campaign_id)
    fields = [
        Ad.Field.id,
        Ad.Field.created_time,
        Ad.Field.name,
        Ad.Field.account_id,
    ]
    ads = campaign.get_ads(fields=fields)
    return ads
def get_campaign_insights(campaign_id):
    campaign = Campaign(campaign_id)
    insights = campaign.get_insights(fields=[
        Insights.Field.cpm,
        Insights.Field.spend,
        Insights.Field.campaign_name,
        Insights.Field.account_name,
        Insights.Field.ad_name,
        Insights.Field.adset_name,
    ])
    return insights
	def delete_campaign(self, fb_campaign_id, logger):
		""" delte fb campaign"""
		try:
			if fb_campaign_id > 0:
				campaign = Campaign(str(fb_campaign_id))
				campaign.remote_delete()
				logger.warning('fb_cpid[%d] deleted' % fb_campaign_id)
			else:
				logger.warning('fb_cpid[%d] invalid for fb delete' % fb_campaign_id)

		except Exception as e:
			logger.exception(e)
 def create_campaign(self, account_id, name):
     """
     Step 2: create a campaign. See [Campaign][1] for further details on
     the API used here.
     [1]: https://developers.facebook.com/docs/marketing-api/adcampaign
     """
     campaign = Campaign(parent_id=account_id)
     campaign[Campaign.Field.name] = name
     campaign[Campaign.Field.objective] = (
         Campaign.Objective.mobile_app_installs)
     campaign.remote_create(params={'status': Campaign.Status.paused})
     return campaign[Campaign.Field.id]
 def create_campaign(self, account_id, name):
     """
     create a campaign
     """
     campaign = Campaign(parent_id=account_id)
     campaign.update({
         Campaign.Field.name: name,
         Campaign.Field.objective: 'APP_INSTALLS',
         })
     campaign.remote_create(params={
         'status': Campaign.Status.paused
     })
     return campaign
Beispiel #15
0
 def get_campaign_stats(campaign):
     campaign = Campaign(campaign)
     params = {
         'data_preset': 'lifetime',
         'fields': [
             Insights.Field.impressions,
             Insights.Field.unique_clicks,
             Insights.Field.reach,
             Insights.Field.cpm,
             Insights.Field.spend,
         ]
     }
     data_set = campaign.get_insights(params=params)
     return data_set[0]
Beispiel #16
0
 def get_campaign_stats(campaign):
     campaign = Campaign(campaign)
     params = {
         'data_preset':
         'lifetime',
         'fields': [
             Insights.Field.impressions,
             Insights.Field.unique_clicks,
             Insights.Field.reach,
             Insights.Field.cpm,
             Insights.Field.spend,
         ]
     }
     data_set = campaign.get_insights(params=params)
     return data_set[0]
def create_campaign(params=None):
    if params is None:
        params = {}

    campaign = Campaign(parent_id=test_config.account_id)
    campaign[Campaign.Field.name] = unique_name('Test Campaign')
    campaign[Campaign.Field.buying_type] = Campaign.BuyingType.auction
    campaign[Campaign.Field.objective] = Campaign.Objective.link_clicks
    campaign['status'] = Campaign.Status.paused

    campaign.update(params)
    campaign.remote_create()

    atexit.register(remote_delete, campaign)

    return campaign
	def read_campaign(self, fb_campaign_id, logger):
		""" read fb campaign"""
		try:
			campaign = Campaign(str(fb_campaign_id))
			campaign.remote_read(fields=[
				Campaign.Field.id,
				Campaign.Field.name,
				Campaign.Field.status,
			])
			# You could only visit fields you ased in remote_read
			print 'campaign info'
			print campaign[Campaign.Field.id]
			print campaign[Campaign.Field.name]
			print campaign[Campaign.Field.status]

		except Exception as e:
			logger.exception(e)
	def create_campaign(self, fb_account_id, logger):
		""" You must create campaign under one fb_account"""
		try:
			campaign = Campaign(parent_id='act_' + str(fb_account_id))
			campaign.update({
				Campaign.Field.name: 'my_test_campaign',
				# for mobile app install ads
				Campaign.Field.objective: Campaign.Objective.mobile_app_installs,
				## for website conversion ads
				#Campaign.Field.objective: Campaign.Objective.website_clicks,
				Campaign.Field.status: Campaign.Status.paused,
				Campaign.Field.buying_type: Campaign.BuyingType.auction,
			})
			campaign.remote_create()
			return int(campaign[Campaign.Field.id])

		except Exception as e:
			logger.exception(e)
    def get_ad_campaign(self, cache, campaign_id):
        """
        Get the ad campaign. As some ad sets being analyzed belong to the
        same ad campaign, a caching is used to reduce the API calls.

        Params:

        * `cache` ad campaigns obtained already.
        * `campaign_id` the id of the ad campaign to be queried out.
        """

        if (cache.get(campaign_id) is None):
            campaign = Campaign(fbid=campaign_id)
            campaign.remote_read(fields=[
                Campaign.Field.name,
                Campaign.Field.configured_status,
                Campaign.Field.objective,
            ])
            cache[campaign_id] = campaign
        return cache.get(campaign_id)
 def generate_record(self):
     my_app_id = '881513028613192'
     my_app_secret = '4252ecaa9b6b11ed5d72ddb8fc2528db'
     my_access_token = 'CAAMhuz7vdEgBAPSuWuBSoCjsV0P45Y3KrqU7y5blqHVyM3XshUN9Dr3ZBNJWZCGJljogD6ZC2XSbqXT4D7I6PVH7isy4EBDqb1U3lB005yIM65ov4fCYUKz3J42kxMfwZBpVZABqBM5vOjZApE6ZC9PvOkRnc7mwZBMFZBnVXBiy37LgJJP2RQrZACpTac2s9INasZD'
     FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
     
     campaign = Campaign('6029907036952')
     campaign.remote_read(fields=[
         Campaign.Field.name,
         Campaign.Field.effective_status,
         Campaign.Field.objective,
     ])
     params = {
         'date_preset': 'last_30_days',
     }
     insights = campaign.get_insights(params=params)
     
     self.write({'name': campaign['name']})
     self.write({'result': insights[0]['actions'][0]['value']})
     self.write({'reach': insights[0]['reach']})
     self.write({'cost': insights[0]['cost_per_total_action']})
     self.write({'amount_spent': insights[0]['spend']})
Beispiel #22
0
class AppEngagementTestCase(SampleTestCase):
    def setUp(self):
        super(AppEngagementTestCase, self).setUp()
        self.appengagement_sample = AppEngagementSample()

    def test_normal(self):

        optimization_goal = 'LINK_CLICKS'
        billing_event = 'LINK_CLICKS'
        bid_amount = '100'  # stands for $1.00

        result = self.appengagement_sample.app_engagement_ad_create(
            self.account_id,
            "appengagement_test",  # basename
            "Try my app! Only 8 clicks you are done!",  # message
            self.images[0],
            "500",  # dailybudget stands for $5.00,
            self.app_info,
            optimization_goal,
            billing_event,
            bid_amount,
            self.mobile_targeting)

        self.assertIn('campaignid', result)
        self.assertIn('adsetid', result)
        self.assertIn('creativeid', result)
        self.assertIn('adid', result)

        self.campaign = Campaign()
        self.campaign[Campaign.Field.id] = result['campaignid']
        self.campaign.remote_read()
        self.assertEqual(self.campaign.get_id(), result['campaignid'])

    def tearDown(self):
        super(AppEngagementTestCase, self).tearDown()
        if hasattr(self, 'campaign'):
            self.campaign['adsets'] = None
            self.campaign.remote_delete()
def campaign_stats_time_range(campaign_id):
    today = datetime.date.today()
    start_time = str(today - datetime.timedelta(weeks=1))
    end_time = str(today)
    campaign = Campaign(campaign_id)
    params = {
        'time_range': {
            'since': start_time,
            'until': end_time,
        },
        'fields': [
            Insights.Field.impressions,
            Insights.Field.unique_clicks,
            Insights.Field.reach,
            Insights.Field.account_name,
            Insights.Field.account_id,
            Insights.Field.cpm,
            Insights.Field.spend,
            Insights.Field.campaign_id,
            Insights.Field.campaign_name
        ],
    }
    insights = campaign.get_insights(params=params)
    return insights
	def update_campaign_name(self, fb_campaign_id, new_campaign_name, logger):
		""" Update fb campaign"""
		try:
			campaign = Campaign(str(fb_campaign_id))

			# You may read campaign field first, not necessary
			campaign.remote_read(fields=[
				Campaign.Field.id,
				Campaign.Field.status,
			])
			if campaign[Campaign.Field.status] == 'ARCHIVED':
				logger.error('cpid[%d] in ARCHIVED status, no update' % fb_campaign_id)
				return

			campaign.update({
				Campaign.Field.name: new_campaign_name,
			})
			campaign.remote_update()

		except Exception as e:
			logger.exception(e)
# 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

ad_account_id = test_config.account_id

# _DOC open [ADCAMPAIGN_CREATE_VIDEO_VIEWS]
# _DOC vars [ad_account_id:s]
from facebookads.objects import Campaign

campaign = Campaign(parent_id=ad_account_id)
campaign.update({
    Campaign.Field.name: 'Video Views Campaign',
    Campaign.Field.objective: Campaign.Objective.video_views,
})

campaign.remote_create(params={
    'status': Campaign.Status.paused,
})
print(campaign)
# _DOC close [ADCAMPAIGN_CREATE_VIDEO_VIEWS]

campaign.remote_delete()
    def retrieve_eligible_adsets_for_an(
        self,
        accountid,
        includepaused=False,
    ):
        """
        This method returns all eligible ad sets that can have audience
        networked turned on for a given ad account id.

        Args:
            accountid: The ad account id (should be of the form act_<act_id>)
                for which you are running this exercise.
            inlcudepaused: Boolen parameter to make your method consider ad
                sets with paused states (PAUSED & CAMPAIGN_PAUSED). Checks
                only ACTIVE by default.

        Returns:
            List of ad set objects (if found satisfying the conditions) or
            an empty list.

        """
        # use accountid to retrieve all active adsets
        account = AdAccount(accountid)
        adsetfields = [
            AdSet.Field.id,
            AdSet.Field.name,
            AdSet.Field.campaign_id,
            AdSet.Field.targeting,
            AdSet.Field.effective_status,
        ]
        adsets = list(account.get_ad_sets(fields=adsetfields))

        # Filter ad sets received by desired status and placement types.
        # Further filter by campaign objectives listed in the criteria below.
        #
        # Ref: https://developers.facebook.com/docs/
        #               marketing-api/audience-network/v2.5

        desired_campaign_status = set(['ACTIVE'])

        # mostly useful in testing when you don't have active campaigns
        if includepaused is True:
            desired_campaign_status.update({'PAUSED', 'CAMPAIGN_PAUSED'})

        desired_campaign_objectives = set([
            'MOBILE_APP_INSTALLS',
            'MOBILE_APP_ENGAGEMENT',
            'LINK_CLICKS',
            'CONVERSIONS',
            'PRODUCT_CATALOG_SALES',
        ])

        # Hold the result set
        eligible_adsets = []

        for adset in adsets:
            if adset[AdSet.Field.effective_status] in desired_campaign_status:
                """
                'devide_platforms', 'publisher_platforms' and
                'facebook_positions' could be absent for the default of 'ALL'
                """
                device_platforms = None
                if TargetingSpecsField.device_platforms in \
                        adset[AdSet.Field.targeting]:
                    device_platforms = set(adset[AdSet.Field.targeting][
                        TargetingSpecsField.device_platforms])

                publisher_platforms = None
                if TargetingSpecsField.publisher_platforms in \
                        adset[AdSet.Field.targeting]:
                    publisher_platforms = set(adset[AdSet.Field.targeting][
                        TargetingSpecsField.publisher_platforms])

                facebook_positions = None
                if TargetingSpecsField.facebook_positions in \
                        adset[AdSet.Field.targeting]:
                    facebook_positions = set(adset[AdSet.Field.targeting][
                        TargetingSpecsField.facebook_positions])

                if ((facebook_positions is None
                     or 'feed' in facebook_positions)
                        and (device_platforms is None
                             or 'mobile' in device_platforms)):

                    if (publisher_platforms is None
                            or 'audience_network' in publisher_platforms):
                        # audience network already enabled, so just pass
                        continue
                    else:
                        campaign = Campaign(adset[AdSet.Field.campaign_id])
                        campaignfields = [
                            Campaign.Field.id,
                            Campaign.Field.name,
                            Campaign.Field.effective_status,
                            Campaign.Field.objective,
                        ]
                        campaign = campaign.remote_read(fields=campaignfields)
                        if (campaign[Campaign.Field.objective]
                                in desired_campaign_objectives):
                            eligible_adsets.append(adset)

        return eligible_adsets
# 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

campaign_id = fixtures.create_campaign().get_id()

# _DOC oncall [pruno]
# _DOC open [ADCAMPAIGN_GET_ADSETS_ADS_MANAGEMENT_UI]
# _DOC vars [campaign_id]
from facebookads.objects import Campaign, AdSet

campaign = Campaign(campaign_id)
ads = campaign.get_ad_sets(
    fields=[
        AdSet.Field.name,
        AdSet.Field.start_time,
        AdSet.Field.end_time,
        AdSet.Field.daily_budget,
        AdSet.Field.lifetime_budget,
    ]
)
# _DOC close [ADCAMPAIGN_GET_ADSETS_ADS_MANAGEMENT_UI]
# 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

campaign_id = fixtures.create_campaign().get_id()

# _DOC open [ADCAMPAIGN_GET_INSIGHTS_TIME_RANGES]
# _DOC vars [campaign_id]
from facebookads.objects import Campaign, Insights
import datetime

today = datetime.date.today()
start_time = str(today - datetime.timedelta(weeks=1))
end_time = str(today)

campaign = Campaign(campaign_id)
params = {
    "time_range": {"since": start_time, "until": end_time},
    "fields": [Insights.Field.impressions, Insights.Field.unique_clicks, Insights.Field.reach],
}
insights = campaign.get_insights(params=params)
print(insights)
# _DOC close [ADCAMPAIGN_GET_INSIGHTS_TIME_RANGES]
# 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

ad_account_id = test_config.account_id

# _DOC oncall [pruno]
# _DOC open [ADCAMPAIGN_CREATE_CONVERSIONS]
# _DOC vars [ad_account_id:s]
from facebookads.objects import Campaign

campaign = Campaign(parent_id=ad_account_id)
campaign.update({
    Campaign.Field.name: 'Conversions Campaign',
    Campaign.Field.objective: Campaign.Objective.conversions,
})

campaign.remote_create(params={
    'status': Campaign.Status.paused,
})
# _DOC close [ADCAMPAIGN_CREATE_CONVERSIONS]

campaign.remote_delete()
# 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

campaign_id = fixtures.create_campaign().get_id()

# _DOC open [ADCAMPAIGN_UPDATE]
# _DOC vars [campaign_id]
from facebookads.objects import Campaign

campaign = Campaign(campaign_id)

campaign[Campaign.Field.name] = 'New Name'
campaign.remote_update()
# _DOC close [ADCAMPAIGN_UPDATE]

campaign.remote_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

campaign_id = fixtures.create_campaign().get_id()

# _DOC open [ADCAMPAIGN_READ]
# _DOC vars [campaign_id]
from facebookads.objects import Campaign

campaign = Campaign(campaign_id)
campaign.remote_read(fields=[
    Campaign.Field.name,
    Campaign.Field.effective_status,
    Campaign.Field.objective,
])

print(campaign)
# _DOC close [ADCAMPAIGN_READ]
# 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

ad_account_id = test_config.account_id

# _DOC oncall [pruno]
# _DOC open [ADCAMPAIGN_CREATE_MAIA]
# _DOC vars [ad_account_id:s]
from facebookads.objects import Campaign

campaign = Campaign(parent_id=ad_account_id)
campaign.update({
    Campaign.Field.name: 'Mobile App Installs Campaign',
    Campaign.Field.objective: Campaign.Objective.mobile_app_installs,
})

campaign.remote_create(params={
    'status': Campaign.Status.paused,
})
# _DOC close [ADCAMPAIGN_CREATE_MAIA]

campaign.remote_delete()
from facebookads.api import FacebookAdsApi
from facebookads.objects import AdUser, Campaign, Insights
from facebookads import FacebookSession, FacebookAdsApi, objects
import os
import time

my_app_id = os.environ['APP_ID']
my_app_secret = os.environ['APP_SECRET']
my_access_token = 'CAAVLUoRrZBPUBAE9o9MSwetl6nH6jarPQdK7miXganZBmh2CX23vlNFQ4pzvCX8FnmqKuBD4pQCDxkkae2FqZCaxbuwI8qC97Vvqc2nFPsT93AKTYYc65D0NRZB1ywyiPcZBuf1xaMPWwfaaMy99pGSbONl1XDXKePPFcxkWqTckB5eNm5FtAkP4j3JUBSqSPXVUXOwVju8t1hetLzbZCe' #Your user access token
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)



campaign = Campaign('6039958653409')
params = {
    'level': Insights.Level.campaign,
}
async_job = campaign.get_insights(params=params, async=True)

async_job.remote_read()

while async_job['async_percent_completion'] < 100:
    time.sleep(1)
    async_job.remote_read()

print(async_job.get_result())

"""
returns this:

[<Insights> {
# 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

campaign_id = fixtures.create_campaign().get_id()

# _DOC open [ADCAMPAIGN_GET_ADGROUPS_WITH_STATUS_ARCHIVED]
# _DOC vars [campaign_id]
from facebookads.objects import Ad, Campaign

campaign = Campaign(campaign_id)
params = {
    Ad.Field.effective_status: [Ad.Status.archived],
}
ads = campaign.get_ads(
    fields=[Ad.Field.name],
    params=params,
)

for ad in ads:
    print(ad[Ad.Field.name])
# _DOC close [ADCAMPAIGN_GET_ADGROUPS_WITH_STATUS_ARCHIVED]
'''
    This is a template for DocSmith samples in Python. Copy it and create yours

    Code should follow guidelines at
    https://our.intern.facebook.com/intern/wiki/Solutions_Engineering/DocSmith

    Each example should be run using facebookads/docs_runner/doc_runner.py

    Comments on style:
    - IDs should be defined outside of _DOC blocks so they don't appear into the
    docs
    - Dependencies, like campaigns, should be generated in the fixtures module
'''

from examples.docs import fixtures

campaign_id = fixtures.create_campaign().get_id_assured()


#! _DOC open [TEMPLATE]
#! _DOC vars [campaign_id]
from facebookads.objects import Campaign, Ad

campaign = Campaign(campaign_id)
ads = campaign.get_ads(fields=[Ad.Field.name])

for ad in ads:
    print(ad[Ad.Field.name])
#! _DOC close [TEMPLATE]
# 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 = fixtures.get_page_with_locations_id_assured()

# _DOC oncall [pruno]
# _DOC open [ADCAMPAIGN_CREATE_DLA]
# _DOC vars [ad_account_id:s, page_id]
from facebookads.objects import Campaign

campaign = Campaign(parent_id=ad_account_id)
campaign.update({
    Campaign.Field.name: 'Local Awareness Campaign',
    Campaign.Field.objective: Campaign.Objective.local_awareness,
    Campaign.Field.promoted_object: {
        'page_id': page_id,
    },
})

campaign.remote_create(params={
    'status': Campaign.Status.paused,
})
# _DOC close [ADCAMPAIGN_CREATE_DLA]

campaign.remote_delete()
Beispiel #37
0
def get_report(request):
	
	Campaign.objects.all().delete()
	Account.objects.all().delete()
	
	#check if user is authenticated
	if not request.user.is_authenticated():
		return render(request, 'account/login.html')	

	#setting the user information
	my_app_id = '1604519246476149'
	my_app_secret = '5a93aee73f1d2856dd542f53e268e483'
	current_user = SocialAccount.objects.get(user=request.user, provider='facebook')
	current_token = SocialToken.objects.get(account=current_user)
	my_access_token = current_token.token
  
	FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
	me = objects.AdUser(fbid='me')
	my_accounts = list(me.get_ad_accounts())
  
	if len(my_accounts) == 0:
		return HttpResponse("no Ad Accounts Exist")
	index = 0
  	
	for current_account in my_accounts:
		if index == 5:
			break
		index = index + 1
		
		current_account.remote_read(fields=[
				AdAccount.Field.account_id,
				AdAccount.Field.name,
				AdAccount.Field.amount_spent,
		])
		
		account_model = Account()
		account_model.account_name = str(current_account[AdAccount.Field.name])
		account_model.account_id = str(current_account[AdAccount.Field.account_id])
		account_model.account_cost = str(float(current_account[AdAccount.Field.amount_spent])/100)
		account_model.save()
		
		ad_campaigns = current_account.get_ad_campaigns()
				
		for current_campaign in ad_campaigns:
		
			current_campaign.remote_read(fields=[
			AdCampaign.Field.name,
    			AdCampaign.Field.status,
    			AdCampaign.Field.id,
    		])
			fields = {    			
    			'impressions',
    			'clicks',
    			'cpc'
    		}
			data = str(current_campaign.get_insights(fields=fields))
			data = '['+data[12:]
			try:
				ast.literal_eval(data)
				json_string = json.dumps(data)
				parsed_data = json.loads(data)				
			except:
				continue
			
			campaign_model = Campaign()
			campaign_model.name = str(current_campaign[AdCampaign.Field.name])
			campaign_model.campaign_id = str(current_campaign[AdCampaign.Field.id])
			campaign_model.status = str(current_campaign[AdCampaign.Field.status])
			campaign_model.clicks = int(parsed_data[0]['clicks'])
			campaign_model.cpc = float(parsed_data[0]['cpc'])
			campaign_model.impressions = int(parsed_data[0]['impressions'])
			campaign_model.account = account_model
			campaign_model.save()
	
	return HttpResponse("Good Humes")
# 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

campaign_id = fixtures.create_campaign().get_id()

# _DOC oncall [duliomatos]
# _DOC open [ADCAMPAIGN_GET_ADSETS]
# _DOC vars [campaign_id]
from facebookads.objects import Campaign, AdSet

campaign = Campaign(campaign_id)
fields = [
    AdSet.Field.name,
    AdSet.Field.configured_status,
    AdSet.Field.effective_status,
]
adsets = campaign.get_ad_sets(fields=fields)
for adset in adsets:
    print(adset[AdSet.Field.name])
# _DOC close [ADCAMPAIGN_GET_ADSETS]
    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
# 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

ad_account_id = test_config.account_id

# _DOC open [ADCAMPAIGN_CREATE_WITH_ADVANCED_OBJECTIVE]
# _DOC vars [ad_account_id:s]
from facebookads.objects import Campaign

campaign = Campaign(parent_id=ad_account_id)
campaign.update({
    Campaign.Field.name: 'My First Campaign',
    Campaign.Field.objective: Campaign.Objective.post_engagement,
})

campaign.remote_create(params={
    'status': Campaign.Status.paused,
})
print(campaign)
# _DOC close [ADCAMPAIGN_CREATE_WITH_ADVANCED_OBJECTIVE]

campaign.remote_delete()
    config['access_token'],
)
api = FacebookAdsApi(session)

if __name__ == '__main__':
    FacebookAdsApi.set_default_api(api)

    print('\n\n\n********** Ad Creation example. **********\n')

    ### Setup user and read the object from the server
    me = AdUser(fbid='me')

    ### Get first account connected to the user
    my_account = me.get_ad_account()
    ### Create a Campaign
    campaign = Campaign(parent_id=my_account.get_id_assured())
    campaign.update({
        Campaign.Field.name: 'Seattle Ad Campaign',
        Campaign.Field.objective: 'LINK_CLICKS',
        Campaign.Field.effective_status: Campaign.Status.paused,
    })
    campaign.remote_create()
    print("**** DONE: Campaign created:")
    pp.pprint(campaign)

    ### Create an Ad Set
    ad_set = AdSet(parent_id=my_account.get_id_assured())
    ad_set.update({
        AdSet.Field.name: 'Puget Sound AdSet',
        AdSet.Field.effective_status: AdSet.Status.paused,
        AdSet.Field.daily_budget: 3600,  # $36.00
    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]
# 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
product_catalog_id = fixtures.create_product_catalog().get_id()

# _DOC open [ADCAMPAIGN_CREATE_OBJECTIVE_PRODUCT_CATELOG_SALES]
# _DOC vars [ad_account_id:s, product_catalog_id]
from facebookads.objects import Campaign

campaign = Campaign(parent_id=ad_account_id)
campaign[Campaign.Field.name] = 'Product Catalog Sales Campaign Group'
objective = Campaign.Objective.product_catalog_sales
campaign[Campaign.Field.objective] = objective
campaign[Campaign.Field.promoted_object] = {
    'product_catalog_id': product_catalog_id,
}

campaign.remote_create(params={
    'status': Campaign.Status.paused,
})
# _DOC close [ADCAMPAIGN_CREATE_OBJECTIVE_PRODUCT_CATELOG_SALES]

campaign.remote_delete()
Beispiel #44
0
def get_report(request):

    Campaign.objects.all().delete()
    Account.objects.all().delete()

    #check if user is authenticated
    if not request.user.is_authenticated():
        return render(request, 'account/login.html')

    #setting the user information
    my_app_id = '1604519246476149'
    my_app_secret = '5a93aee73f1d2856dd542f53e268e483'
    current_user = SocialAccount.objects.get(user=request.user,
                                             provider='facebook')
    current_token = SocialToken.objects.get(account=current_user)
    my_access_token = current_token.token

    FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
    me = objects.AdUser(fbid='me')
    my_accounts = list(me.get_ad_accounts())

    if len(my_accounts) == 0:
        return HttpResponse("no Ad Accounts Exist")
    index = 0

    for current_account in my_accounts:
        if index == 5:
            break
        index = index + 1

        current_account.remote_read(fields=[
            AdAccount.Field.account_id,
            AdAccount.Field.name,
            AdAccount.Field.amount_spent,
        ])

        account_model = Account()
        account_model.account_name = str(current_account[AdAccount.Field.name])
        account_model.account_id = str(
            current_account[AdAccount.Field.account_id])
        account_model.account_cost = str(
            float(current_account[AdAccount.Field.amount_spent]) / 100)
        account_model.save()

        ad_campaigns = current_account.get_ad_campaigns()

        for current_campaign in ad_campaigns:

            current_campaign.remote_read(fields=[
                AdCampaign.Field.name,
                AdCampaign.Field.status,
                AdCampaign.Field.id,
            ])
            fields = {'impressions', 'clicks', 'cpc'}
            data = str(current_campaign.get_insights(fields=fields))
            data = '[' + data[12:]
            try:
                ast.literal_eval(data)
                json_string = json.dumps(data)
                parsed_data = json.loads(data)
            except:
                continue

            campaign_model = Campaign()
            campaign_model.name = str(current_campaign[AdCampaign.Field.name])
            campaign_model.campaign_id = str(
                current_campaign[AdCampaign.Field.id])
            campaign_model.status = str(
                current_campaign[AdCampaign.Field.status])
            campaign_model.clicks = int(parsed_data[0]['clicks'])
            campaign_model.cpc = float(parsed_data[0]['cpc'])
            campaign_model.impressions = int(parsed_data[0]['impressions'])
            campaign_model.account = account_model
            campaign_model.save()

    return HttpResponse("Good Humes")
    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_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)