コード例 #1
0
def create_adset(account_id, campaign_id, targeting, name):
    import datetime
    from facebookads.adobjects.adset import AdSet

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

    adset = AdSet(parent_id=account_id)
    adset.update({
        AdSet.Field.name: name,
        AdSet.Field.campaign_id: campaign_id,
        AdSet.Field.daily_budget: 1000,
        AdSet.Field.billing_event: AdSet.BillingEvent.impressions,
        AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach,
        AdSet.Field.bid_amount: 2,
        AdSet.Field.targeting: targeting,
        AdSet.Field.start_time: start_time,
        AdSet.Field.end_time: end_time,
    })

    as_ = adset.remote_create(params={
        'status': AdSet.Status.paused,
    })
    return as_
コード例 #2
0
def get_ads(adset_id):
    fields = ["id", "name"]

    def decorate(n, x):
        return {"value": x["id"], "name": x.get("name", "Ad #%s" % n)}

    adset = AdSet(adset_id)
    return [decorate(n, x) for n, x in enumerate(adset.get_ads(fields))]
コード例 #3
0
def create_new_ad_set():
    """
    Creating a new ad set for the ad account

    You can use the adset.update method specified here:
    https://developers.facebook.com/docs/marketing-api/reference/ad-campaign
    """
    adset = AdSet(parent_id=my_ad_account_id)
    """
    UPDATE/CREATE ADSET HERE
    """
    adset[AdSet.Field.campaign_id] = my_campaign_id
    adset[AdSet.Field.name] = 'Toast_competition'
    adset[AdSet.Field.promoted_object] = {
        'page_id': my_page_id,
    }
    adset[AdSet.Field.billing_event] = "IMPRESSIONS"
    adset[AdSet.Field.daily_budget] = 200
    adset[AdSet.Field.is_autobid] = True

    adset[AdSet.Field.targeting] = {
        'geo_locations': {
            'countries': ['IN']
        },
        'genders': [0],
        'age_min': 18,
        'age_max': 40,
        'interests': []
    }

    adset.remote_create()

    image = AdImage(parent_id=my_ad_account_id)
    image[AdImage.Field.filename] = "dog_ads/3.jpg"
    image.remote_create()
    image_hash = image[AdImage.Field.hash]

    creative = AdCreative(parent_id=my_ad_account_id)
    creative[AdCreative.Field.title] = 'Puppy Love'
    creative[AdCreative.Field.
             body] = '"Like" to find ways to help man\'s best friend.'
    creative[AdCreative.Field.object_id] = my_page_id
    # creative[AdCreative.Field.object_url] = 'https://www.facebook.com/caltech.clickmaniac/'
    creative[AdCreative.Field.image_hash] = image_hash

    ad = Ad(parent_id=my_ad_account_id)
    ad[Ad.Field.name] = 'Pos'
    ad[Ad.Field.adset_id] = adset[AdSet.Field.id]
    ad[Ad.Field.creative] = creative

    ad.remote_create(params={
        'status': Ad.Status.active,
    })
    return adset
コード例 #4
0
 def get_ads_info_by_adset(self, adset_id):
     adset = AdSet('%s' % str(adset_id))
     ads = adset.get_ads(fields=[
         Ad.Field.id,
         Ad.Field.name,
         Ad.Field.adset_id,
         Ad.Field.campaign_id,
         Ad.Field.status,
     ])
     if ads: return ads
     return {}
コード例 #5
0
	def setTargetingDict(self, adset_id):
		adset = AdSet(adset_id)
		adset_read = adset.remote_read(fields=['targeting','promoted_object'])
		targeting = adset_read['targeting']
		age_max = targeting['age_max']
		age_min = targeting['age_min']
		user_os = targeting['user_os'][0]
		app_install_state = targeting['app_install_state']
		promoted_object = adset_read['promoted_object']
		store_url = promoted_object['object_store_url']
		app_id = promoted_object['application_id']
		app = fb_app_ids[app_id]
		
		if app_install_state == 'installed':
			marketing_type = 'Remarketing'
		
		if app_install_state == 'not_installed':
			marketing_type = 'UA'
		
		if 'itunes' in store_url:
			platform = 'iOS'
		
		if 'google' in store_url:
			platform = 'Android'
		
		placement = ''
		for row in targeting['publisher_platforms']:
			placement += row + '-'
		placement = placement[:-1]
		event_type = promoted_object.get('custom_event_type', 'Unspecified')
		try: 
			gender = targeting['genders'][0]
			if gender == 1:
				gender = 'M'
			if gender == 2:
				gender = 'F'
		except KeyError:
			gender = 'All'
		self.targeting_dict[adset_id] = \
			{
			'age_max': age_max, 
			'age_min': age_min,
			'gender': gender,
			'user_os': user_os,
			'app_install_state': app_install_state,
			'marketing_type': marketing_type,
			'event_type': event_type,
			'platform': platform,
			'placement': placement,
			'app': app
			}
コード例 #6
0
def create_new_ad_set():
    """
    Create a new adset
    """
    adset = AdSet(parent_id=my_ad_account_id)
    adset[AdSet.Field.name] = 'Mutegolf SDK Ad Set'
    adset[AdSet.Field.campaign_id] = my_campaign_id
    
    adset[AdSet.Field.optimization_goal] = AdSet.OptimizationGoal.page_likes
    adset[AdSet.Field.promoted_object] = {
            'page_id': my_page_id
        }
    
    adset[AdSet.Field.billing_event] = AdSet.BillingEvent.impressions
    #adset[AdSet.Field.end_time] = 1520517600 # UNIX 
    adset[AdSet.Field.daily_budget] = 200 # 200 cents
    adset[AdSet.Field.is_autobid] = True
    adset[AdSet.Field.targeting] = {
        Targeting.Field.geo_locations: {
            'countries': ['IN']
        }
    }

    ''',
    "flexible_spec": [
            {
                "interests": [
                  {
                    "id": "6003107902433", 
                    "name": "Association football (Soccer)"
                  }, 
                  {
                    "id": "6003139266461", 
                    "name": "Movies"
                  }
                ]
            }
        ]
        Targeting.Field.genders: {
            'genders': [2]
        }'''
    
    adset[AdSet.Field.status] = AdSet.Status.active

    adset.remote_create()
    #adset[AdSet.Field.bid_amount] = 
    #remote_adset

    return adset
コード例 #7
0
ファイル: skeleton.py プロジェクト: dnguyen123/clickmaniac
def create_new_ad_set():
    """
    Create a new adset
    """
    adset = AdSet(parent_id=my_ad_account_id)

    pass
コード例 #8
0
ファイル: main.py プロジェクト: taurijuhkam/facebook_ads_api
def create_ad_set(campaign_data, account, campaign_id):
    """Creates an ad set and targeting for the campaign.
    
    Args:
        campaign_data (dict): A dict with campaign data, parsed from JSON
        account (str): Account where to upload the campaign
        campaign_id (str): Campaign id where to upload the Ad set
    """
    # Setup Ad set
    ad_set = AdSet(parent_id=account)
    ad_set[AdSet.Field.campaign_id] = campaign_id
    ad_set[AdSet.Field.name] = campaign_data.get('ad_set_name')
    ad_set[AdSet.Field.optimization_goal] = getattr(AdSet.OptimizationGoal,
                                                    campaign_data.get('optimization_goal'))
    ad_set[AdSet.Field.billing_event] = getattr(AdSet.BillingEvent,
                                                campaign_data.get('billing_event'))
    ad_set[AdSet.Field.is_autobid] = campaign_data.get('automatic_bidding')

    if campaign_data.get('daily_budget'):
        ad_set[AdSet.Field.daily_budget] = campaign_data.get('daily_budget')
    else:
        ad_set[AdSet.Field.lifetime_budget] = campaign_data.get('lifetime_budget')
    if campaign_data.get('end_time'):
        ad_set[AdSet.Field.end_time] = campaign_data.get('end_time')
    if campaign_data.get('start_time'):
        ad_set[AdSet.Field.start_time] = campaign_data.get('start_time')

    # Setup Targeting - maybe move to separate function
    # targeting is a dict!
    targeting = {}
    targeting[Targeting.Field.geo_locations] = {
        'countries': [campaign_data.get('country')]
    }
    if campaign_data.get('max_age'):
        targeting[Targeting.Field.age_max] = campaign_data.get('max_age')
    if campaign_data.get('min_age'):
        targeting[Targeting.Field.age_min] = campaign_data.get('min_age')

    # TODO: Language, region, Placements?
    #

    # Attach targeting to Ad set
    ad_set[AdSet.Field.targeting] = targeting

    ad_set.remote_create()
コード例 #9
0
 def get_adset_insights(self,
                        adset_id,
                        breakdown_attribute=None,
                        start_dt=None,
                        stop_dt=None):
     adsets = AdSet('%s' % (adset_id))
     params = {}
     if breakdown_attribute: params['breakdowns'] = breakdown_attribute
     if start_dt and stop_dt:
         params['time_range'] = {'since': start_dt, 'until': stop_dt}
     params['fields'] = [
         'account_id', 'account_name', 'campaign_id', 'campaign_name',
         'adset_id', 'adset_name', 'ad_id', 'ad_name', 'buying_type',
         'spend', 'clicks', 'impressions', 'cpc', 'cpm', 'cpp', 'ctr',
         'actions', 'frequency'
     ],
     params['level'] = 'adset'
     insights = adsets.get_insights(params=params)
     if insights: return insights
     return {}
コード例 #10
0
    def define_budget(self, campaign_id, targeting):

        start_time = time.mktime(
            datetime.datetime.strptime(self.post['from'],
                                       "%m/%d/%Y %H:%M:%S").timetuple())
        end_time = time.mktime(
            datetime.datetime.strptime(self.post['to'],
                                       "%m/%d/%Y %H:%M:%S").timetuple())
        adset = AdSet(parent_id=self.ad_account_id)

        adset_params = {
            AdSet.Field.name: self.post['name'] + ' Ad Set',
            AdSet.Field.campaign_id: campaign_id,
            AdSet.Field.billing_event: AdSet.BillingEvent.impressions,
            AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach,
            AdSet.Field.bid_amount: self.post['bid'],  # TODO:: What is this?
            AdSet.Field.targeting: targeting,
            AdSet.Field.start_time: start_time,
            AdSet.Field.end_time: end_time,
        }

        if self.post['budget_time'] == "Daily":
            adset_params[
                AdSet.Field.daily_budget] = self.post['total_budget'] * 100

        if self.post['budget_time'] == "Life Time":
            adset_params[
                AdSet.Field.lifetime_budget] = self.post['total_budget'] * 100

        error = None
        newAdset = None
        adset.update(adset_params)
        try:
            newAdset = adset.remote_create(
                params={'status': AdSet.Status.paused})
        except Exception as e:
            error = e

        return newAdset, error
コード例 #11
0
    def tearDown(self):
        if hasattr(self, 'campaign'):
            self.campaign.remote_delete()

        # rest the audience network flag on the ad set 6035543090685
        # so the the next test runs pass

        # read ad set info
        adset = AdSet(fbid="6035543090685")
        adsetobj = adset.remote_read(fields=[AdSet.Field.targeting])

        # edit targeting spec info for placements
        targetinginfo = copy.deepcopy(adsetobj[AdSet.Field.targeting])
        targetinginfo[TargetingSpecsField.publisher_platforms].remove(
            'audience_network')

        # update ad set info
        adset.update({AdSet.Field.targeting: targetinginfo})
        adset.remote_update()
コード例 #12
0
def create_adset(country_list, interest_list, age_min, age_max, adset_name,
                 campaign_id, daily_budget, bid_amount, start_time, end_time):
    try:
        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('adset')
        targeting = {
            Targeting.Field.geo_locations: {
                Targeting.Field.countries: country_list,
            },
            Targeting.Field.interests: interest_list,
            Targeting.Field.age_min: age_min,
            Targeting.Field.age_max: age_max,
        }
        adset = AdSet(parent_id=header.my_account['id'])
        adset.update({
            AdSet.Field.name: adset_name,
            AdSet.Field.campaign_id: campaign_id,
            AdSet.Field.daily_budget: daily_budget,
            AdSet.Field.billing_event: AdSet.BillingEvent.impressions,
            AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach,
            AdSet.Field.bid_amount: bid_amount,
            AdSet.Field.targeting: targeting,
            AdSet.Field.start_time: start_time,
            AdSet.Field.end_time: end_time,
        })
        adset.remote_create(params={
            'status': AdSet.Status.paused,
        })
        logging.info(adset)

    except exceptions.FacebookError, e:
        logging.error('Error %s' % e)
        return None
コード例 #13
0
def get_ad_set(campaign):
    adsets = campaign.get_ad_sets()
    adset = AdSet(fbid=adsets[0][AdSet.Field.id])
    print (adset)
    return adset
コード例 #14
0
def create_adset():
    choice = raw_input(
        "Please enter yes to create a new campaign and anything else to to enter id for existing campaign.\n"
    ).lower()
    print choice
    if 'yes' in choice:
        campaign_id = campaign.create_campaign()
    else:
        campaign_id = raw_input("Please enter campaign id.\n")
    query = raw_input("Enter query for targeting customer type.\n")
    params = {
        'q': query,
        'type': 'adinterest',
    }

    resp = TargetingSearch.search(params=params)
    print resp
    resp = json.loads(str(resp).replace('<TargetingSearch> ', ''))
    print(resp)

    number_of_interests = int(raw_input("Please enter number of interests.\n"))
    interest_list = []
    for i in xrange(number_of_interests):
        a = int(raw_input("Enter Interest Ids.\n"))
        interest_list.append(a)

    number_of_countries = int(
        raw_input("Please enter number of countries for targeting.\n"))
    country_list = []
    for i in xrange(number_of_countries):
        a = raw_input("Enter Country Codes.\n")
        country_list.append(a)
    age_min = raw_input("Please enter minimum targeting age.\n")
    age_max = raw_input("Please enter maximum targeting age.\n")
    targeting = {
        Targeting.Field.geo_locations: {
            Targeting.Field.countries: country_list,
        },
        Targeting.Field.interests: interest_list,
        Targeting.Field.age_min: age_min,
        Targeting.Field.age_max: age_max,
    }

    adset_name = raw_input("Please enter a name for the adset.\n")
    daily_budget = int(raw_input("Please enter daily_budget(in paise).\n"))
    bid_amount = int(raw_input("Please enter bid_amount(in paise).\n"))
    start_time = raw_input(
        "Please enter start date for AdSet format(YYYY-MM_DD).\n")
    end_time = raw_input(
        "Please enter end date for AdSet format(YYYY-MM_DD).\n")

    adset = AdSet(parent_id=header.my_account['id'])
    adset.update({
        AdSet.Field.name: adset_name,
        AdSet.Field.campaign_id: campaign_id,
        AdSet.Field.daily_budget: daily_budget,
        AdSet.Field.billing_event: AdSet.BillingEvent.impressions,
        AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach,
        AdSet.Field.bid_amount: bid_amount,
        AdSet.Field.targeting: targeting,
        AdSet.Field.start_time: start_time,
        AdSet.Field.end_time: end_time,
    })

    adset.remote_create(params={
        'status': AdSet.Status.paused,
    })
    adset = json.loads(str(adset).replace('<AdSet> ', ''))
    return adset['id']
コード例 #15
0
def get_adset_insights(id, fields, params):
    adset = AdSet(id)
    return list(adset.get_insights(params=params, fields=fields))
コード例 #16
0
print(resp)

# 생성한 관심사 기반으로 샘플 타게팅 사양 만듦
targeting = {
    Targeting.Field.geo_locations: {
        Targeting.Field.countries: ['KOR'],
    },
    Targeting.Field.interests: 'baseball',
}

# 3. 예산, 청구, 최적화 및 기간 정의
today = datetime.date.today()
start_time = str(today + datetime.timedelta(weeks=1))  # 광고실행기간
end_time = str(today + datetime.timedelta(weeks=2))

adset = AdSet(parent_id='act_306011116959172')
adset.update({
    AdSet.Field.name: 'My Ad Set',
    AdSet.Field.campaign_id: 453840891825593,
    AdSet.Field.daily_budget: 1000,  # 하루 지출하고자 하는 금액
    AdSet.Field.billing_event: AdSet.BillingEvent.impressions,  # 결제 기준
    AdSet.Field.optimization_goal:
    AdSet.OptimizationGoal.reach,  # 광고를 통해 달성하고자 하는 결과
    AdSet.Field.bid_amount: 2,  # 발생하는 최적화 이번트에 부여할 가치
    # AdSet.Field.targeting: <TARGETING>,
    AdSet.Field.start_time: start_time,
    AdSet.Field.end_time: end_time,
})

adset.remote_create(params={
    'status': AdSet.Status.paused,  # paused : 정지상태로 비용청구 방지
コード例 #17
0
from facebookads.adobjects.targeting import Targeting

my_app_id = '2004842166273835'
my_app_secret = 'b644afb62638fc43c44faf56bdf334ef'
my_access_token = 'EAAcfZALEmxysBAHyZALreV9q4O7YYydqM885ZAWocnEK1LuxwuQ1mJIKyA6rtdxnbmTlVwpWo2TmqemaxIA6d3ghLWQnEbSYZCRZAyOUF5aSRK0GTZCMwo6sFh8lnb2XFKv4vKxPqu3FYbhxhcCf3crquT6MJMZBuAphFlO853AMQZAlf6jgC0CvyznSdbsL5NUZD'
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
my_account = AdAccount('2004842166273835')
my_account = AdAccount('act_2004842166273835')

# campaigns = my_account.get_campaigns()

# print(campaigns)

# create add set

adset = AdSet(parent_id='act_2004842166273835')
adset.update({
    AdSet.Field.name: 'My Ad Set',
    AdSet.Field.campaign_id: 'Traffic',
    AdSet.Field.daily_budget: 1000,
    AdSet.Field.billing_event: AdSet.BillingEvent.impressions,
    AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach,
    AdSet.Field.bid_amount: 2,
    AdSet.Field.targeting: {
        Targeting.Field.geo_locations: {
            'countries': ['INDIA'],
        },
    },
})

adset.remote_create(params={
コード例 #18
0
from facebookads.adobjects.adset import AdSet

adset = AdSet(parent_id='act_<AD_ACCOUNT_ID>')
adset.update({
    AdSet.Field.name: 'My AdSet',
    AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach,
    AdSet.Field.billing_event: AdSet.BillingEvent.impressions,
    AdSet.Field.bid_amount: 150,
    AdSet.Field.daily_budget: 2000,
    AdSet.Field.campaign_id: <CAMPAIGN_ID>,
    AdSet.Field.targeting: {
        'geo_locations': {
            'regions': [{'key': '3847'}],
            'cities': [
                {
                    'key': '2430536',
                    'radius': '12',
                    'distance_unit': 'mile',
                },
            ],
        },
        'genders': [1],
        'relationship_statuses': [2, 3, 4],
        'age_min': 18,
        'age_max': 43,
        'interests': [
            {
                'id': 6003139266461,
                'name': 'Movies',
            },
        ],
コード例 #19
0
def create_multiple_website_clicks_ads(
    account,

    name,
    country,

    titles,
    bodies,
    urls,
    image_paths,

    optimization_goal,
    pixel_id,
    billing_event,
    bid_amount,
    daily_budget=None,
    lifetime_budget=None,
    start_time=None,
    end_time=None,

    age_min=None,
    age_max=None,
    genders=None,

    campaign=None,
    status=AdSet.Status.paused,
):
    # Check for bad specs
    if daily_budget is None:
        if lifetime_budget is None:
            raise TypeError(
                'One of daily_budget or lifetime_budget must be defined.'
            )
        elif end_time is None:
            raise TypeError(
                'If lifetime_budget is defined, end_time must be defined.'
            )

    # Create campaign
    if campaign:
        campaign = Campaign(fbid=campaign)[Campaign.Field.id]
    else:
        campaign = Campaign(parent_id=account)
        campaign[Campaign.Field.name] = name + ' Campaign'
        campaign[Campaign.Field.objective] = \
            Campaign.Objective.conversions
        campaign[Campaign.Field.status] = \
            Campaign.Status.active if not status \
            else Campaign.Status.paused
        campaign.remote_create()
        campaign = campaign[AdSet.Field.id]

    # Create ad set
    ad_set = AdSet(parent_id=account)
    ad_set[AdSet.Field.campaign_id] = campaign
    ad_set[AdSet.Field.name] = name + ' AdSet'
    ad_set[AdSet.Field.optimization_goal] = optimization_goal
    ad_set[AdSet.Field.promoted_object] = {
        'pixel_id': pixel_id,
        'custom_event_type': 'COMPLETE_REGISTRATION'

    }
    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
    targeting = {}
    targeting[Targeting.Field.geo_locations] = {
        'countries': [country]
    }
    if age_max:
        targeting[Targeting.Field.age_max] = age_max
    if age_min:
        targeting[Targeting.Field.age_min] = age_min
    if genders:
        targeting[Targeting.Field.genders] = genders
    ad_set[AdSet.Field.targeting] = targeting

    ad_set.remote_create()

    # Upload the images first one by one
    image_hashes = []
    for image_path in image_paths:
        img = AdImage(parent_id=account)
        img[AdImage.Field.filename] = image_path
        img.remote_create()
        image_hashes.append(img.get_hash())

    ADGROUP_BATCH_CREATE_LIMIT = 10
    ad_groups_created = []

    def callback_failure(response):
        raise response.error()

    # For each creative permutation
    for creative_info_batch in generate_batches(
        itertools.product(titles, bodies, urls, image_hashes),
        ADGROUP_BATCH_CREATE_LIMIT
    ):
        api_batch = api.new_batch()

        for title, body, url, image_hash in creative_info_batch:
            # Create the ad
            ad = Ad(parent_id=account)
            ad[Ad.Field.name] = name + ' Ad'
            ad[Ad.Field.adset_id] = ad_set[AdSet.Field.id]
            ad[Ad.Field.creative] = {
                AdCreative.Field.title: title,
                AdCreative.Field.body: body,
                AdCreative.Field.object_url: url,
                AdCreative.Field.image_hash: image_hash,
            }
            ad[Ad.Field.status] = status

            ad.remote_create(batch=api_batch, failure=callback_failure)
            ad_groups_created.append(ad)

        api_batch.execute()

    return ad_groups_created
コード例 #20
0
from facebookads.api import FacebookAdsApi

access_token = '<ACCESS_TOKEN>'
app_secret = '<APP_SECRET>'
app_id = '<APP_ID>'
id = '<ID>'
FacebookAdsApi.init(access_token=access_token)

fields = []
params = {
    'bid_adjustments': {
        'user_groups': {
            'user_bucket': {
                'event_sources': ['<pixelID>', '<appID>'],
                '1': 0.01,
                '2': 0.02,
                '3': 0.03,
                'default': {
                    'gender': {
                        'male': 0.9996,
                        'female': 0.0129
                    }
                }
            }
        }
    },
}
print AdSet(id).update(
    fields=fields,
    params=params,
)
コード例 #21
0
# 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.adobjects.adset import AdSet
from facebookads.api import FacebookAdsApi

access_token = '<ACCESS_TOKEN>'
app_secret = '<APP_SECRET>'
app_id = '<APP_ID>'
id = '<ID>'
FacebookAdsApi.init(access_token=access_token)

fields = [
  'created_time',
]
params = {
}
print AdSet(id).get(
  fields=fields,
  params=params,
)
# 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.adobjects.adset import AdSet
from facebookads.adobjects.adsinsights import AdsInsights
from facebookads.api import FacebookAdsApi

access_token = '<ACCESS_TOKEN>'
app_secret = '<APP_SECRET>'
app_id = '<APP_ID>'
id = '<ID>'
FacebookAdsApi.init(access_token=access_token)

fields = [
    'impressions',
]
params = {
    'breakdown': 'publisher_platform',
}
print AdSet(id).get_insights(
    fields=fields,
    params=params,
)
コード例 #23
0
    image_path = download_image_from_url(image_url)
    print(image_path)
except:
    image_path = input(
        "Entrez le path de l'image utilisée pour la publicité: ")

campaign = Campaign(parent_id=account_publicitaire)

campaign[Campaign.Field.name] = variable + " " + pays
campaign[Campaign.Field.configured_status] = Campaign.Status.active
campaign[Campaign.Field.objective] = Campaign.Objective.conversions

campaign.remote_create()
campaign = campaign[AdSet.Field.id]

ad_set = AdSet(parent_id=account_publicitaire)
ad_set[AdSet.Field.campaign_id] = campaign
ad_set[AdSet.Field.name] = variable + ' ' + target_location
ad_set[
    AdSet.Field.optimization_goal] = AdSet.OptimizationGoal.offsite_conversions
ad_set[AdSet.Field.destination_type] = "WEBSITE"
ad_set[AdSet.Field.promoted_object] = {
    'pixel_id': 'YOURPIXELID',
    'custom_event_type': 'PURCHASE',
}
ad_set[AdSet.Field.billing_event] = AdSet.BillingEvent.impressions
ad_set[AdSet.Field.is_autobid] = True
ad_set[AdSet.Field.daily_budget] = daily_budget
ad_set[AdSet.Field.start_time] = datetime.datetime.now()
targeting = {}