def get_adsets_from_adaccount(account_id): account = AdAccount(account_id) fields = [ AdSet.Field.name, ] adsets = account.get_ad_sets(fields=fields) return adsets
def getCustomAudiences(my_account): ad_account = AdAccount("{AD_ACCOUNT_ID}".format(AD_ACCOUNT_ID = my_account['id'])) custom_audiences = ad_account.get_custom_audiences(fields=[CustomAudience.Field.name]) # audiences = my_account.get_custom_audiences(fields=[ # CustomAudience.Field.name, # CustomAudience.Field.description]) return custom_audiences
def create_ads_pixel(): account = AdAccount(test_config.account_id) pixel = account.get_ads_pixels([AdsPixel.Field.code]) if pixel is None: pixel = AdsPixel(parent_id=test_config.account_id) pixel[AdsPixel.Field.name] = unique_name('Test Pixel') pixel.remote_create() return pixel
def get_ads_insight( self, account_id, ): """ Pull insights from the Insight edge and return an array of insight report Params: * `account_id` is fb AdAccount id """ ad_account = AdAccount(fbid = account_id) insights = ad_account.get_insights() return insights
def get_promotable_ios_app(app_id=None): account = AdAccount(test_config.account_id) for connection_object in account.get_connection_objects(): if connection_object[ConnectionObject.Field.type] == 2 \ and ( app_id is None or int( connection_object[ConnectionObject.Field.id], ) is int(app_id) ): if 'object_store_urls' in connection_object \ and 'itunes' in connection_object['object_store_urls']: return ( connection_object[ConnectionObject.Field.id], connection_object['object_store_urls']['itunes'] ) raise Exception('No iOS promotable App available')
def get_ad_set(self): account = AdAccount(self.act_id) adsets = account.get_ad_sets( fields=[ AdSet.Field.name, AdSet.Field.status, AdSet.Field.campaign_group_id ], params={ 'campaign_status': ['ACTIVE'], 'limit': 100 } ) campaigns = account.get_ad_campaigns( fields=[ AdCampaign.Field.name, AdCampaign.Field.status ], params={ 'campaign_group_status': ['ACTIVE'] } ) ads = [] for adset in adsets: for i in range(0, len(campaigns)): campaign = campaigns[i] if adset['campaign_group_id'] == campaign['id']: ads.append({ 'id': adset['id'], 'name': adset['name'], 'campaign_name': campaign['name'] }) break return sorted(ads, key=lambda ad: ad['campaign_name'] + ad['name'])
from facebookads.objects import AdAccount, AsyncJob from facebookads.api import FacebookAdsApi import time import os import json this_dir = os.path.dirname(__file__) config_filename = os.path.join(this_dir, 'config.json') config_file = open(config_filename) config = json.load(config_file) config_file.close() api = FacebookAdsApi.init(access_token=config['access_token']) account_id = config['act_id'] account = AdAccount(account_id) # Both Insights and Reportstats i_async_job = account.get_insights(params={'level': 'ad'}, async=True) # Insights while True: job = i_async_job.remote_read() print("Percent done: " + str(job[AsyncJob.Field.async_percent_completion])) time.sleep(1) if job: # print "Done!" break print(i_async_job.get_result())
import os import configparser config = configparser.RawConfigParser() this_dir = os.path.dirname(__file__) config_filename = os.path.join(this_dir, 'my_app_session.cfg') with open(config_filename) as config_file: config.readfp(config_file) FacebookAdsApi.init( config.get('Authentication', 'app_id'), config.get('Authentication', 'app_secret'), config.get('Authentication', 'access_token'), ) if __name__ == '__main__': my_account = AdAccount(config.get('Defaults', 'ad_account')) # create video object video = AdVideo(parent_id=my_account.get_id_assured()) # set video fields video[AdVideo.Field.filepath] = os.path.join(this_dir, 'test_video.mp4') # remove create video.remote_create() video.waitUntilEncodingReady() print(video)
# 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_label_id = fixtures.create_adlabel().get_id() # _DOC oncall [pruno] # _DOC open [ADACCOUNT_GET_ADGROUPS_FILTERING_ADLABELS] # _DOC vars [ad_account_id:s, ad_label_id] from facebookads.objects import AdAccount, Ad params = { 'filtering': [ { 'field': 'adlabels', 'operator': 'ANY', 'value': ['for testing'], }, ], } ad_account = AdAccount(ad_account_id) ads = ad_account.get_ads(fields=[Ad.Field.name], params=params) # _DOC close [ADACCOUNT_GET_ADGROUPS_FILTERING_ADLABELS]
# 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 facebookads import test_config ad_account_id = test_config.account_id # _DOC open [ADACCOUNT_UPDATE_SPEND_CAP] # _DOC vars [ad_account_id:s] from facebookads.objects import AdAccount account = AdAccount(ad_account_id) account[AdAccount.Field.spend_cap] = 10000 account.remote_update() # _DOC close [ADACCOUNT_UPDATE_SPEND_CAP]
# 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 facebookads.objects import AdLabel from examples.docs import fixtures ad_account_id = test_config.account_id # _DOC open [ADACCOUNT_READ] # _DOC vars [ad_account_id:s] from facebookads.objects import AdAccount account = AdAccount(ad_account_id) account.remote_read(fields=[ AdAccount.Field.name, AdAccount.Field.balance ]) print(account[AdAccount.Field.name]) print(account[AdAccount.Field.balance]) # _DOC close [ADACCOUNT_READ] # _DOC open [ADACCOUNT_READ_TOS_ACCEPTED] # _DOC vars [ad_account_id:s] from facebookads.objects import AdAccount account = AdAccount(ad_account_id)
# 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 [ADACCOUNT_GET_ADGROUPS_WITH_STATUS] # _DOC vars [ad_account_id:s] from facebookads.objects import AdAccount account = AdAccount(ad_account_id) params = { 'effective_status': ['ACTIVE', 'ADSET_PAUSED', 'CAMPAIGN_PAUSED', 'PENDING_REVIEW', 'DISAPPROVED', 'PREAPPROVED', 'PENDING_BILLING_INFO', 'ARCHIVED', ] } ads = account.get_ads(params=params) for ad in ads: print(ad) # _DOC close [ADACCOUNT_GET_ADGROUPS_WITH_STATUS]
# 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 [ADACCOUNT_GET_TARGETING_DESCRIPTION] # _DOC vars [ad_account_id:s] from facebookads.objects import AdAccount, TargetingSpecsField account = AdAccount(ad_account_id) params = { 'targeting_spec': { TargetingSpecsField.geo_locations: { TargetingSpecsField.countries: ['US', 'JP'], }, TargetingSpecsField.genders: [1], TargetingSpecsField.age_min: 20, TargetingSpecsField.age_max: 24, } } targeting_description = account.get_targeting_description(params=params) # Output the targeting description for description in targeting_description['targetingsentencelines']:
config_file.close() ### Setup session and api objects session = FacebookSession( config['app_id'], config['app_secret'], config['access_token'], ) api = FacebookAdsApi(session) if __name__ == '__main__': FacebookAdsApi.set_default_api(api) # Get my account (first account associated with the user associated with the # session of the default api) my_account = AdAccount.get_my_account() print('**** Creating ad...') # Create my ad my_ad = ad_creation_utils.create_website_clicks_ad( account=my_account, name="Visit Seattle", country='US', title="Visit Seattle", # How it looks body="Beautiful Puget Sound.", url="http://www.seattle.gov/visiting/", image_path=os.path.join(this_dir, 'test.png'), bid_type=AdSet.BidType.cpm, bid_info={AdSet.Field.BidInfo.impressions: 53}, # $0.53 / thousand daily_budget=1000, # $10.00 per day
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]
pp = pprint.pprint this_dir = os.path.dirname(__file__) config_filename = os.path.join(this_dir, 'config.json') ### Setup session and api objects config_file = open(config_filename) config = json.load(config_file) config_file.close() auth_info = (config['app_id'], config['app_secret'], config['access_token']) FacebookAdsApi.init(*auth_info) ### Get account from config file my_account = AdAccount(config['act_id']) def ListCustomAudiences(**kwargs): audiences = my_account.get_custom_audiences( fields=[CustomAudience.Field.name, CustomAudience.Field.description]) if (audiences): print(">>> Account") print(my_account[CustomAudience.Field.id]) print(">>> Audiences") for audience in audiences: print(audience[CustomAudience.Field.id] + ': ' + audience[CustomAudience.Field.name])
item.Spend = cp_insight["spend"] item.StartDate = cp_insight["date_start"] item.EndDate = cp_insight["date_stop"] item.Actived = True item.UserCreated = 1 listaIns.append(item) if mes: FBInsights().SalvarMensalLista(listaIns) else: FBInsights().SalvarLista(listaIns) for config in listaConfig: acc = AdAccount('act_{}'.format(config.MarcaConta.FBContaId)) options = { 1: ReportDiario, 2: ReportMenosXDias, 3: ReportIntervaloDiaADia, 4: ReportIntervaloTotal, 5: ReportIntervaloMensal } data_ini_config = config.StartDate data_fim_config = config.EndDate hoje = datetime.datetime.now().date() for campaign in acc.get_campaigns(fields=[ Campaign.Field.name, Campaign.Field.start_time,
import configparser import os config = configparser.RawConfigParser() this_dir = os.path.dirname(__file__) config_filename = os.path.join(this_dir, 'my_app_session.cfg') with open(config_filename) as config_file: config.readfp(config_file) FacebookAdsApi.init( config.get('Authentication', 'app_id'), config.get('Authentication', 'app_secret'), config.get('Authentication', 'access_token'), ) if __name__ == '__main__': my_account = AdAccount('act_<AD_ACCOUNT_ID>') # create video object video = AdVideo(parent_id=my_account.get_id_assured()) # set video fields video[AdVideo.Field.filepath] = os.path.join(this_dir, 'test_video.mp4') # remove create video.remote_create() video.waitUntilEncodingReady() print(video)
# from facebook_business.api import FacebookAdsApi # from facebook_business.adobjects.adaccount import AdAccount # my_app_id = '1696381387180237' # my_app_secret = '2e8c4e640bd999f94838ab90d904fa79' # my_access_token = 'EAAYG2ZAH8iM0BAEszmfOaZAQ5qr6FW2JyUe2biPyCq02PUHsZAYrOGS1TFH4W1CV8ZBxqY2ENLSqL0tMWsffSU0FNPU7BJZCVG4A50BNyebI0bulWk3oX3GCDL4ZBKnw38qdt7cjXbqq2ZAg7tMuv3fIzCl7Fqnw6nB2uYemLRoHRzuwEgXycVW9422PMGhX99wVCZBpqA0dsz8x2dsCC58K' # FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token) # my_account = AdAccount('act_642303109628222') # campaigns = my_account.get_campaigns() # print(campaigns) from facebookads.objects import AdAccount, Ad account_id = 'act_1696381387180237' ad_account = AdAccount(account_id) ad_iter = ad_account.get_ads(fields=[Ad.Field.name]) for ad in ad_iter: print(ad[Ad.Field.name])
# 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 ad_account_id = test_config.account_id # _DOC oncall [duliomatos] # _DOC open [ADACCOUNT_GET_REACHESTIMATE] # _DOC vars [ad_account_id:s] from facebookads.objects import AdAccount, AdSet account = AdAccount(ad_account_id) targeting_spec = {"geo_locations": {"countries": ["US"]}, "age_min": 20, "age_max": 40} params = { "currency": "USD", "optimize_for": AdSet.OptimizationGoal.offsite_conversions, "targeting_spec": targeting_spec, } reach_estimate = account.get_reach_estimate(params=params) print(reach_estimate) # _DOC close [ADACCOUNT_GET_REACHESTIMATE]
from facebookads.objects import AdAccount, AsyncJob from facebookads.api import FacebookAdsApi import time import os import json this_dir = os.path.dirname(__file__) config_filename = os.path.join(this_dir, 'config.json') config_file = open(config_filename) config = json.load(config_file) config_file.close() api = FacebookAdsApi.init(access_token=config['access_token']) account_id = config['act_id'] account = AdAccount(account_id) # Both Insights and Reportstats i_async_job = account.get_insights(params={'level': 'adgroup'}, async=True) r_async_job = account.get_report_stats( params={ 'data_columns': ['adgroup_id'], 'date_preset': 'last_30_days' }, async=True ) # Insights while True: job = i_async_job.remote_read() print("Percent done: " + str(job[AsyncJob.Field.async_percent_completion]))
# 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 from facebookads import test_config ad_account_id = test_config.account_id ad_label_id = fixtures.create_adlabel().get_id() # _DOC oncall [ritu] # _DOC open [ADACCOUNT_GET_ADCAMPAIGNS_ADLABEL] # _DOC vars [ad_account_id:s, ad_label_id] from facebookads.objects import AdAccount account = AdAccount(ad_account_id) campaigns = account.get_campaigns_by_labels(params={ 'ad_label_ids': [ad_label_id], }) # _DOC close [ADACCOUNT_GET_ADCAMPAIGNS_ADLABEL]
# 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 [ADACCOUNT_GET_INSIGHTS_DYNAMIC_PRODUCT_ADS] # _DOC vars [ad_account_id:s] from facebookads.objects import AdAccount, Insights account = AdAccount(ad_account_id) fields = [ Insights.Field.account_name, Insights.Field.impressions, Insights.Field.actions, Insights.Field.product_id, ] params = { 'date_preset': 'last_week', 'actions_group_by': ['action_type'], } stats = account.get_insights(fields=fields, params=params) # _DOC close [ADACCOUNT_GET_INSIGHTS_DYNAMIC_PRODUCT_ADS]
# _DOC vars [ad_account_id:s] from facebookads.objects import AdsPixel pixel = AdsPixel(parent_id=ad_account_id) pixel[AdsPixel.Field.name] = 'My new Pixel' pixel.remote_create() # _DOC close [ADSPIXEL_CREATE] pixel_id = pixel.get_id() # _DOC open [ADSPIXEL_READ_PIXEL_CODE] # _DOC vars [ad_account_id:s] from facebookads.objects import AdsPixel, AdAccount account = AdAccount(ad_account_id) account.get_ads_pixels(fields=[AdsPixel.Field.code]) # _DOC close [ADSPIXEL_READ_PIXEL_CODE] destination_account_id = config.secondary_account_id business_id = config.business_id # _DOC open [ADSPIXEL_SHARE_ADACCOUNT] # _DOC vars [business_id:s, destination_account_id:s, pixel_id] from facebookads.objects import AdsPixel pixel = AdsPixel(pixel_id) response = pixel.share_pixel(business_id, destination_account_id) print(response.body()) # _DOC close [ADSPIXEL_SHARE_ADACCOUNT]
from __future__ import unicode_literals ''' This is a template for DocSmith samples in Python. This file will throw an exception. This is used to test facebookads/docs_runner/doc_runner.py when something breaks ''' import sys import os this_dir = os.path.dirname(__file__) repo_dir = os.path.join(this_dir, os.pardir, os.pardir) sys.path.insert(1, repo_dir) from facebookads import bootstrap bootstrap.auth() ''' Example tha intentionally throws an exception to be used as a test for DocExampleTest ''' from facebookads.objects import AdAccount if __name__ == '__main__': ad_account_id = 'invalid_id_1111' print('**** READ AD ACCOUNT ****') ad_account = AdAccount(fbid=ad_account_id) ad_account.remote_read() print(ad_account.remote_read())
from facebookads.objects import AdAccount, AsyncJob from facebookads.api import FacebookAdsApi import time import os import json this_dir = os.path.dirname(__file__) config_filename = os.path.join(this_dir, 'config.json') config_file = open(config_filename) config = json.load(config_file) config_file.close() api = FacebookAdsApi.init(access_token=config['access_token']) account_id = config['act_id'] account = AdAccount(account_id) # Both Insights and Reportstats i_async_job = account.get_insights(params={'level': 'adgroup'}, async=True) r_async_job = account.get_report_stats(params={ 'data_columns': ['adgroup_id'], 'date_preset': 'last_30_days' }, async=True) # Insights while True: job = i_async_job.remote_read() print("Percent done: " + str(job[AsyncJob.Field.async_percent_completion])) time.sleep(1) if job:
config_file = open('./examples/docs/config.json') config = json.load(config_file) config_file.close() account_id = config['account_id'] access_token = config['access_token'] app_id = config['app_id'] app_secret = config['app_secret'] FacebookAdsApi.init(app_id, app_secret, access_token) # _DOC open [ADACCOUNT_READ] # _DOC vars [account_id:s] from facebookads.objects import AdAccount account = AdAccount(account_id) account.remote_read(fields=[ AdAccount.Field.name, AdAccount.Field.balance ]) print(account[AdAccount.Field.name]) print(account[AdAccount.Field.balance]) # _DOC close [ADACCOUNT_READ] # _DOC vars [account_id:s] from facebookads.objects import AdAccount account = AdAccount(account_id) account.remote_read(fields=[AdAccount.Field.name]) old_name = account[AdAccount.Field.name]
# 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 facebookads import test_config ad_account_id = test_config.account_id # _DOC oncall [pruno] # _DOC open [ADACCOUNT_GET_CUSTOMAUDIENCES_DATA_SOURCE_SUBTYPE] # _DOC vars [ad_account_id:s] from facebookads.objects import AdAccount, CustomAudience ad_account = AdAccount(ad_account_id) custom_audiences = ad_account.get_custom_audiences(fields=[ CustomAudience.Field.data_source, CustomAudience.Field.subtype, ]) # _DOC close [ADACCOUNT_GET_CUSTOMAUDIENCES_DATA_SOURCE_SUBTYPE]
# 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 facebookads import test_config from facebookads.objects import AdAccount ad_account_id = test_config.account_id account = AdAccount(ad_account_id) # _DOC open [ADACCOUNT_GET_CONNECTIONOBJECTS_ID_NAME_TYPE] from facebookads.objects import ConnectionObject account.get_connection_objects([ ConnectionObject.Field.id, ConnectionObject.Field.name, ConnectionObject.Field.type, ]) # _DOC close [ADACCOUNT_GET_CONNECTIONOBJECTS_ID_NAME_TYPE]
# 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 facebookads import test_config ad_account_id = test_config.account_id # _DOC open [ADACCOUNT_GET_ADCAMPAIGNS] # _DOC vars [ad_account_id:s] from facebookads.objects import AdAccount, Campaign account = AdAccount(ad_account_id) campaigns = account.get_campaigns(fields=[Campaign.Field.name]) for campaign in campaigns: print(campaign[Campaign.Field.name]) # _DOC close [ADACCOUNT_GET_ADCAMPAIGNS]
# 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 [ADACCOUNT_GET_INSIGHTS_FILTERING_BREAKDOWN] # _DOC vars [ad_account_id:s] from facebookads.objects import AdAccount, Insights ad_account = AdAccount(ad_account_id) params = { 'breakdowns': [ Insights.Breakdown.age, Insights.Breakdown.gender ], 'filtering': [{ 'field': 'campaign.name', 'operator': 'CONTAIN', 'value': '18-25' }] } stats = ad_account.get_insights(params=params) print(stats) # _DOC close [ADACCOUNT_GET_INSIGHTS_FILTERING_BREAKDOWN]
# 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 from facebookads.objects import AdPreview ad_account_id = test_config.account_id post_id = fixtures.create_post()['id'] format = AdPreview.AdFormat.desktop_feed_standard # _DOC open [ADACCOUNT_GET_PREVIEWS_WITH_OBJECT_STORY_ID] # _DOC vars [ad_account_id:s, post_id:s, format:s] from facebookads.objects import AdAccount, AdPreview, AdCreative account = AdAccount(ad_account_id) params = { AdPreview.Field.creative: { AdCreative.Field.object_story_id: post_id, }, AdPreview.Field.ad_format: format, } account.get_ad_preview(params=params) # _DOC close [ADACCOUNT_GET_PREVIEWS_WITH_OBJECT_STORY_ID]
# 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_label_id = fixtures.create_adlabel().get_id() # _DOC oncall [pruno] # _DOC open [ADACCOUNT_GET_ADCAMPAIGNS_ADS_MANAGEMENT_UI] # _DOC vars [ad_account_id:s] from facebookads.objects import AdAccount, Campaign fields = { Campaign.Field.name, Campaign.Field.objective, } params = { Campaign.Field.effective_status: [ 'ACTIVE', 'PAUSED', ], } account = AdAccount(ad_account_id) campaigns = account.get_campaigns(fields=fields, params=params) # _DOC close [ADACCOUNT_GET_ADCAMPAIGNS_ADS_MANAGEMENT_UI]
# 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. ''' 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 facebookads repo folder must be added to PYTHONPATH in order to run Comments on style: - IDs should be defined outside of _DOC blocks so they don't appear into the docs ''' from facebookads import test_config as config ad_account_id = config.account_id #! _DOC open [READ_ADACCOUNT] # _DOC vars [ad_account_id] from facebookads.objects import AdAccount ad_account = AdAccount(fbid=ad_account_id) ad_account.remote_read() print(ad_account) #! _DOC close [READ_ADACCOUNT]
config.readfp(config_file) ### Setup session and api objects session = FacebookSession( config.get('Authentication', 'app_id'), config.get('Authentication', 'app_secret'), config.get('Authentication', 'access_token'), ) api = FacebookAdsApi(session) if __name__ == '__main__': FacebookAdsApi.set_default_api(api) # Get my account (first account associated with the user associated with the # session of the default api) my_account = AdAccount.get_my_account() print('**** Creating ad...') # Create my ad my_ad = ad_creation_utils.create_website_clicks_ad( account=my_account, name="Visit Seattle", country='US', title="Visit Seattle", # How it looks body="Beautiful Puget Sound.", url="http://www.seattle.gov/visiting/", image_path=os.path.join(this_dir, 'test.png'),
images = AdImage.remote_create_from_zip( filename=image_zip_path, parent_id=ad_account_id ) # Output image hashes. for image in images: print(image[AdImage.Field.hash]) # _DOC close [ADIMAGE_CREATE_ZIP] image_1_hash = images[0][AdImage.Field.hash] image_2_hash = images[1][AdImage.Field.hash] # _DOC open [ADIMAGE_READ_MULTI_WITH_HASH] # _DOC vars [ad_account_id:s, image_1_hash, image_2_hash] from facebookads.objects import AdAccount account = AdAccount(ad_account_id) params = { 'hashes': [ image_1_hash, image_2_hash, ], } images = account.get_ad_images(params=params) # _DOC close [ADIMAGE_READ_MULTI_WITH_HASH] for _image in images: image = AdImage(_image[AdImage.Field.id], ad_account_id) image.remote_delete(params={AdImage.Field.hash: _image[AdImage.Field.hash]})
# 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 facebookads import test_config ad_account_id = test_config.account_id # _DOC open [ADACCOUNT_GET_RATECARDS] # _DOC vars [ad_account_id:s] from facebookads.objects import AdAccount ad_account = AdAccount(ad_account_id) rate_cards = ad_account.get_rate_cards() print(rate_cards) # _DOC close [ADACCOUNT_GET_RATECARDS]
images = AdImage.remote_create_from_zip( filename=image_zip_path, parent_id=ad_account_id ) # Output image hashes. for image in images: print(image[AdImage.Field.hash]) # _DOC close [ADIMAGE_CREATE_ZIP] image_1_hash = images[0][AdImage.Field.hash] image_2_hash = images[1][AdImage.Field.hash] # _DOC open [ADIMAGE_READ_MULTI_WITH_HASH] # _DOC vars [ad_account_id:s, image_1_hash, image_2_hash] from facebookads.objects import AdAccount account = AdAccount(ad_account_id) params = { 'hashes': [ image_1_hash, image_2_hash, ], } images = account.get_ad_images(params=params) # _DOC close [ADIMAGE_READ_MULTI_WITH_HASH] for _image in images: image = AdImage(_image[AdImage.Field.id], ad_account_id) image.remote_delete(params={AdImage.Field.hash: image_hash})
# 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 facebookads import test_config ad_account_id = test_config.account_id # _DOC open [ADACCOUNT_READ_TOS_ACCEPTED] # _DOC vars [ad_account_id:s] from facebookads.objects import AdAccount account = AdAccount(ad_account_id) account.remote_read(fields=[AdAccount.Field.tos_accepted]) for tos in account[AdAccount.Field.tos_accepted]: print(tos) # _DOC close [ADACCOUNT_READ_TOS_ACCEPTED]
this_dir = os.path.dirname(__file__) config_filename = os.path.join(this_dir, 'my_app_session.cfg') ### Setup session and api objects with open(config_filename) as config_file: config.readfp(config_file) auth_info = ( config.get('Authentication', 'app_id'), config.get('Authentication', 'app_secret'), config.get('Authentication', 'access_token')) FacebookAdsApi.init(*auth_info) ### Get account from config file my_account = AdAccount('act_' + config.get('Defaults', 'ad_account')) def ListCustomAudiences(**kwargs): audiences = my_account.get_custom_audiences(fields=[ CustomAudience.Field.name, CustomAudience.Field.description]) if(audiences): print(">>> Account") print(my_account[CustomAudience.Field.id]) print(">>> Audiences") for audience in audiences: print(audience[CustomAudience.Field.id] + ': ' + audience[CustomAudience.Field.name])