] oauth_response = subprocess.Popen(oauth_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] try: token = json.loads(oauth_response)['access_token'] return token except KeyError: print('Bad OAuth response: {}'.format(str(oauth_response))) token = get_fb_token(c['fb_app_id'], c['fb_app_secret']) FacebookAdsApi.init(c['fb_app_id'], c['fb_app_secret'], token) num_days = 5 my_account = AdAccount(c['fb_account']) fields = [ 'account_id', 'account_name', 'ad_id', 'adset_id', 'adset_name', 'campaign_id', 'campaign_name', 'cost_per_outbound_click', 'outbound_clicks', 'outbound_clicks_ctr', 'spend', 'relevance_score', 'actions' ] tf = '%Y-%m-%d' start = date.today() - timedelta(days=num_days) while start < date.today(): results = dd(dict)
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. from facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.adset import AdSet from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<AD_ACCOUNT_ID>' FacebookAdsApi.init(access_token=access_token) fields = [ ] params = { 'name': 'My First Adset', 'lifetime_budget': '20000', 'start_time': '2019-04-29T08:48:12-0700', 'end_time': '2019-05-09T08:48:12-0700', 'campaign_id': '<adCampaignLinkClicksID>', 'bid_amount': '100', 'billing_event': 'LINK_CLICKS', 'optimization_goal': 'LINK_CLICKS', 'targeting': {'facebook_positions':['feed'],'geo_locations':{'countries':['US']},'publisher_platforms':['facebook','audience_network']}, 'status': 'PAUSED', } print AdAccount(id).create_ad_set( fields=fields, params=params, )
from facebook_business.adobjects.ad import Ad from facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.adasyncrequest import AdAsyncRequest from facebook_business.adobjects.adasyncrequestset import AdAsyncRequestSet from facebook_business.api import FacebookAdsApi # access_token = "EAAHsrmgrz0YBAJpeJmtEWcwXbh6XrRw9OffbG677eAanGiEiueL2mbLsOJSGMZB1G65Yw53oGctc2yqZC08GZBZBIAw8cRfkhZB96cnycoEBfnjS4lslC2yL4mdPnZBGcURxd5VUnKNiAOHXdxyEsS840nBhjVuc3LakIB7NzdeyHW3NHKxzT2" # account_id = 'act_414637205659315' access_token = 'EAAHsrmgrz0YBAAG1qQZCIZBeZApR6jbqZCdwGNoEWUebVquFpNDPKaLa0o7SPPFlhaZBsMaUyWeKPqgjGGEhZAwVwfOJuuu7mZA1OfNVZA0ni4sus7PRQrZAus8sUPluhFE8IOLKq9hIAclz0NAJDlT5VvrZBWGqLeTzaNr3FgI53Gj96YtLrUtwDk1ejsbCDMjrgKcO7MUq78MtBaMB0pZC19kXwWMAXGm1VIZD' account_id = 'act_100311700797020' api = FacebookAdsApi.init(access_token=access_token) account = AdAccount(account_id) def get_ad_obj(adset_id): ad_name = 'hotel 50' return { "adset_id": adset_id, "creative": { "body": "Alchemy hotel", "title": "Hotel room", "object_story_spec": { "page_id": 238251770344039, "link_data":
# 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 facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.customaudience import CustomAudience from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<ID>' FacebookAdsApi.init(access_token=access_token) fields = [ 'id', ] params = {} print AdAccount(id).get_custom_audiences( fields=fields, params=params, )
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 Targeting.Field.device_platforms in \ adset[AdSet.Field.targeting]: device_platforms = set(adset[AdSet.Field.targeting][ Targeting.Field.device_platforms]) publisher_platforms = None if Targeting.Field.publisher_platforms in \ adset[AdSet.Field.targeting]: publisher_platforms = set(adset[AdSet.Field.targeting][ Targeting.Field.publisher_platforms]) facebook_positions = None if Targeting.Field.facebook_positions in \ adset[AdSet.Field.targeting]: facebook_positions = set(adset[AdSet.Field.targeting][ Targeting.Field.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
def __init__(self, app_id, app_secret, access_token, ad_account_id): FacebookAdsApi.init(app_id, app_secret, access_token) self.account = AdAccount(ad_account_id)
def getHashImage(): FacebookAdsApi.init(app_id=dict1['my_app_id'] ,app_secret= dict1['my_app_secret'], account_id=dict1['account_id'] ,access_token=dict1['my_access_token']) fields = [] account = AdAccount(dict1['account_id']) campaigns = account.get_ad_images() print(campaigns)
def getAccount(self): return AdAccount(fbid=self.account_id)
def listAllCampaigns(self): my_account = AdAccount(fbid=self.account_id) my_account.remote_read(fields=[Campaign.Field.id, Campaign.Field.name]) return my_account.get_campaigns()
def set_account(self, account_id): """ Sets account object """ self.account_id = account_id self.account = AdAccount('act_{}'.format(self.account_id)) logging.info("Initiated AdAccount object for account %s", self.account_id)
def campaign_insights(): today = datetime.date.today() fields1 = [ 'account_name', 'campaign_name', 'campaign_id', 'reach', 'unique_outbound_clicks_ctr:outbound_click', 'cost_per_action_type:offsite_conversion.custom.118660332158323', 'unique_actions:offsite_conversion', 'date_start', 'unique_actions:post_engagement', 'cost_per_action_type:post_reaction', 'cost_per_outbound_click:outbound_click', 'action:post_engagement', 'inline_link_clicks', 'cost_per_unique_action_type:page_engagement', 'unique_actions:landing_page_view', 'action:post', 'unique_actions:offsite_conversion.fb_pixel_add_to_cart', 'cost_per_action_type:link_click', 'outbound_clicks_ctr:outbound_click', 'frequency', 'engagement_rate_ranking', 'cost_per_action_type:omni_add_to_cart', 'unique_actions:omni_add_to_cart', 'inline_post_engagement', 'spend', 'unique_actions:page_engagement', 'unique_actions:omni_purchase', 'cost_per_unique_inline_link_click', 'action:omni_add_to_cart', 'inline_link_click_ctr', 'cost_per_inline_post_engagement', 'objective', 'unique_inline_link_click_ctr', 'instant_experience_outbound_clicks', 'cost_per_unique_click', 'cost_per_action_type:post', 'social_spend', 'cost_per_action_type:post_engagement', 'date_stop', 'cost_per_action_type:omni_purchase', 'cost_per_inline_link_click', 'unique_actions:link_click', 'action:landing_page_view', 'unique_actions:post_reaction', 'unique_ctr', 'instant_experience_clicks_to_open', 'action:offsite_conversion.custom.280669215754025', 'cost_per_action_type:offsite_conversion.custom.281094269070676', 'unique_actions:post', 'cost_per_unique_action_type:landing_page_view', 'cost_per_unique_action_type:post_engagement', 'action:post_reaction', 'cost_per_unique_outbound_click:outbound_click', 'cpc', 'cpm', 'impressions', 'cost_per_unique_action_type:link_click', 'cost_per_unique_action_type:omni_purchase', 'cpp', 'action:offsite_conversion.fb_pixel_purchase', 'conversion_rate_ranking', 'unique_actions:offsite_conversion.fb_pixel_purchase', 'ctr', 'cost_per_action_type:page_engagement', 'cost_per_action_type:offsite_conversion.fb_pixel_purchase', 'outbound_clicks:outbound_click', 'unique_clicks', 'unique_inline_link_clicks', 'action:omni_purchase', 'action:page_engagement', 'unique_link_clicks_ctr', 'action:offsite_conversion.custom.118660332158323', 'action:offsite_conversion.custom.281094269070676', 'clicks', 'cost_per_action_type:landing_page_view', 'unique_outbound_clicks:outbound_click', 'cost_per_unique_action_type:omni_add_to_cart', 'website_ctr:link_click', 'action:offsite_conversion.fb_pixel_add_to_cart', 'instant_experience_clicks_to_start', 'action:link_click', 'quality_ranking', 'cost_per_action_type:offsite_conversion.custom.280669215754025', 'cost_per_action_type:offsite_conversion.fb_pixel_add_to_cart' ] for x in range(1, 8): date1 = today - datetime.timedelta(days=x) date1 = str(date1) arr = date1.split("-") year = arr[0] month = arr[1] params = {'time_range': {'since': date1, 'until': date1}} fields = [ 'account_name', 'campaign_name', 'campaign_id', 'reach', 'frequency', 'impressions', 'clicks', 'cpm', 'ctr', 'spend', 'actions', 'canvas_avg_view_percent', 'canvas_avg_view_time', 'conversion_rate_ranking', 'conversion_values', 'conversions', 'cost_per_action_type', 'cost_per_conversion', 'cost_per_estimated_ad_recallers', 'cost_per_inline_link_click', 'cost_per_inline_post_engagement', 'cost_per_outbound_click', 'cost_per_thruplay', 'cost_per_unique_action_type', 'cost_per_unique_click', 'cost_per_unique_inline_link_click', 'cost_per_unique_outbound_click', 'cpc', 'cpp', 'engagement_rate_ranking', 'estimated_ad_recall_rate', 'estimated_ad_recallers', 'full_view_impressions', 'full_view_reach', 'inline_link_click_ctr', 'inline_link_clicks', 'inline_post_engagement', 'instant_experience_clicks_to_open', 'instant_experience_clicks_to_start', 'instant_experience_outbound_clicks', 'mobile_app_purchase_roas', 'objective', 'outbound_clicks', 'outbound_clicks_ctr', 'place_page_name', 'quality_ranking', 'social_spend', 'unique_actions', 'unique_clicks', 'unique_ctr', 'unique_inline_link_click_ctr', 'unique_inline_link_clicks', 'unique_link_clicks_ctr', 'unique_outbound_clicks', 'unique_outbound_clicks_ctr', 'video_30_sec_watched_actions', 'video_avg_time_watched_actions', 'video_p100_watched_actions', 'video_p25_watched_actions', 'video_p50_watched_actions', 'video_p75_watched_actions', 'video_p95_watched_actions', 'video_play_actions', 'video_play_curve_actions', 'video_thruplay_watched_actions', 'website_ctr', ] f = open("account_id", "r") #importing the account id from external file acc = f.read() my_account = AdAccount(acc) campaignids = my_account.get_campaigns() list_d = [] l = [] y = 0 for i in range(len(campaignids)): try: c_id = campaignids[i]["id"] campaign = Campaign(c_id) camp_insights = campaign.get_insights(fields=fields, params=params) j = 0 dic_camp = {} for item in camp_insights: #converting to dictionary dic_camp = dict(item) try: for each_action in dic_camp["actions"]: dic_camp[ "action:" + each_action['action_type']] = each_action['value'] del dic_camp["actions"] except KeyError: continue try: for each_action in dic_camp["cost_per_action_type"]: dic_camp[ "cost_per_action_type:" + each_action['action_type']] = each_action['value'] del dic_camp["cost_per_action_type"] except KeyError: continue try: for each_action in dic_camp["cost_per_outbound_click"]: dic_camp[ "cost_per_outbound_click:" + each_action['action_type']] = each_action['value'] del dic_camp["cost_per_outbound_click"] except KeyError: continue try: for each_action in dic_camp["cost_per_unique_action_type"]: dic_camp[ "cost_per_unique_action_type:" + each_action['action_type']] = each_action['value'] del dic_camp["cost_per_unique_action_type"] except KeyError: continue try: for each_action in dic_camp[ "cost_per_unique_outbound_click"]: dic_camp[ "cost_per_unique_outbound_click:" + each_action['action_type']] = each_action['value'] del dic_camp["cost_per_unique_outbound_click"] except KeyError: continue try: for each_action in dic_camp["outbound_clicks"]: dic_camp[ "outbound_clicks:" + each_action['action_type']] = each_action['value'] del dic_camp["outbound_clicks"] except KeyError: continue try: for each_action in dic_camp["outbound_clicks_ctr"]: dic_camp[ "outbound_clicks_ctr:" + each_action['action_type']] = each_action['value'] del dic_camp["outbound_clicks_ctr"] except KeyError: continue try: for each_action in dic_camp["unique_actions"]: dic_camp[ "unique_actions:" + each_action['action_type']] = each_action['value'] del dic_camp["unique_actions"] except KeyError: continue try: for each_action in dic_camp["unique_outbound_clicks"]: dic_camp[ "unique_outbound_clicks:" + each_action['action_type']] = each_action['value'] del dic_camp["unique_outbound_clicks"] except KeyError: continue try: for each_action in dic_camp["unique_outbound_clicks_ctr"]: dic_camp[ "unique_outbound_clicks_ctr:" + each_action['action_type']] = each_action['value'] del dic_camp["unique_outbound_clicks_ctr"] except KeyError: continue try: for each_action in dic_camp["website_ctr"]: dic_camp[ "website_ctr:" + each_action['action_type']] = each_action['value'] del dic_camp["website_ctr"] except KeyError: continue list_d.append(dic_camp) except IndexError: continue if list_d: filename1 = "FacebookAds/landing_campaign_insights/" + "campaign_insights_" + date1 + ".csv" filename2 = "FacebookAds/processing_campaign_insights/csv/" + year + "/" + month + "/" + "campaign_insights_" + date1 + ".csv" importtos3.write_to_s3(list_d, fields1, 'paragon-datalake', filename1, filename2) return list_d
ad_account_id = 'act_373503683609460' app_secret = '1cddcfaae9c2b852188bef2520b086c9' page_id = '1357440557629733' app_id = '878326592678297' FacebookAdsApi.init(access_token=access_token) fields = [] params = { 'name': 'Lets Talk Openly', 'buying_type': 'AUCTION', 'objective': 'LINK_CLICKS', 'status': 'PAUSED', 'special_ad_categories': 'None', } campaign = AdAccount(ad_account_id).create_campaign( fields=fields, params=params, ) print('campaign', campaign) campaign_id = campaign.get_id() print('campaign_id:', campaign_id, '\n') fields = [] params = { 'name': 'My AdSet', 'optimization_goal': 'LANDING_PAGE_VIEWS', 'billing_event': 'IMPRESSIONS', 'bid_amount': '10', 'promoted_object': { 'page_id': page_id },
'Test Product Audience', 'product_set_id': '<productSetID>', 'inclusions': [{ 'retention_seconds': 86400, 'rule': { 'event': { 'eq': 'AddToCart' } } }, { 'retention_seconds': 72000, 'rule': { 'event': { 'eq': 'ViewContent' } } }], 'exclusions': [{ 'retention_seconds': 172800, 'rule': { 'event': { 'eq': 'Purchase' } } }], } print AdAccount(id).create_product_audience( fields=fields, params=params, )
from facebook_business.api import FacebookAdsApi from facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.adset import AdSet import csv from matplotlib import pyplot as plt import json import os plt.rcParams.update({'figure.max_open_warning': 0}) import calendar import time my_app_id = '2725706687661342' my_app_secret = '259338521f39f49cacef7db0aae1ae5d' my_access_token = 'EAAmvBArhRR4BADniGjZCgCluOLCRF7TolKU5UriWVmrBH6OUlBypAQgnx0nyPf2wimk3R4bRRQuuLzCbsR82a3DWtYnFMp8ndYTJbdLZBZBHgQQesfC1WjPYeLAYc4T4WoLZBL70olMwpOZBtH7gU7DWclHfDa2xGaMDZAhFOlw4D1SQZCl43F0' FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token) my_account = AdAccount('act_2408768415887341') params = { 'level': 'campaign', 'date_preset': 'this_week_sun_today' # 'date_preset': 'this_week_sun_today' } fields = [ 'campaign_id', 'campaign_name', 'impressions', 'spend', 'impressions', 'date_start', 'date_stop', 'actions' ] campaigns = my_account.get_insights(fields=fields, params=params) # print(campaigns) ts = calendar.timegm(time.gmtime())
r'C:\Anaconda3\Lib\site-packages' ) # Replace this with the place you installed facebookads using pip sys.path.append( r'C:\Anaconda3\Lib\site-packages\facebook_business-3.0.0-py2.7.egg-info' ) # same as above from facebook_business.api import FacebookAdsApi from facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.adimage import AdImage my_app_id = '2317550648481540' my_app_secret = '4c1c34b9502793e4837a00f2a7b7f7aa' page_id = '601550560344776' my_access_token = 'EAAg7zM8m1wQBAO1qB31k7nrE3YpKZBuzobZA8ebzC2JNriCF5uKK6P8R6zc268N4CnZAdjHF88gUZCRLIyRwEqDZCAWA3GQw5Q8p0eQ4TpliBEsfZBZB1GLDpfXkSnDKZAYYiDXgZACp4IdrK6ZAUl9ieAyCM35pScFJEliEYiH8Q3oSKLqkkIPN1MVB7UE6RoLK8ZD' FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token) my_account = AdAccount('act_306011116959172') fields = [] params = { 'objective': 'PAGE_LIKES', 'status': 'PAUSED', 'buying_type': 'AUCTION', 'name': 'My Campaign', } campaign = my_account.create_campaign( fields=fields, params=params, ) print('campaign', campaign) campaign_id = campaign.get_id()
def deleteAllCampaigns(self): my_account = AdAccount(fbid=self.account_id) my_account.remote_read() for c in my_account.get_campaigns(): c.remote_delete()
#! <venv>/bin python3.8 # -*- coding: utf-8 -*- """ Created on 21/10/20 1:45 pm @author: David Wong """ from facebook_business.api import FacebookAdsApi from facebook_business.adobjects.adaccount import AdAccount my_app_id = '3396366213760437' my_app_secret = '332122d6f131b3a6329d1d07279baf13' my_access_token = 'EAAwQZBiGyxbUBANWYkO29qZCxQIDsouqUNXLfPs6vZCwMkXKSdOTnY6COow7a7tCtpKaGzG4QZBKq17b0BxS2zQASdRkhujfsZCYYpZBqgUEVZAxQ324iWTZBWiAFCZAxEu54T6pt2yPXFGhSaX2dfsZC0vg06dhU6DJq9LZBiLwvvS0QZDZD' FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token) my_account = AdAccount('act_502604490299991') campaigns = my_account.get_campaigns()
app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<AD_ACCOUNT_ID>' FacebookAdsApi.init(access_token=access_token) fields = [] params = { 'creative': { 'instagram_actor_id': '<instagramActorID>', 'object_story_spec': { 'link_data': { 'call_to_action': { 'type': 'LEARN_MORE', 'value': { 'link': '<url>' } }, 'caption': 'www.example.com', 'image_hash': '<imageHash>', 'link': '<url>', 'message': 'Message' }, 'page_id': '<pageID>' } }, 'ad_format': 'INSTAGRAM_STANDARD', } print AdAccount(id).get_generate_previews( fields=fields, params=params, )
def api_create(self, parent_id, fields=None, params=None, batch=None, pending=False): from facebook_business.adobjects.adaccount import AdAccount return AdAccount(api=self._api, fbid=parent_id).create_ad_place_page_set(fields, params, batch, pending)
from facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.adsinsights import AdsInsights from facebook_business.api import FacebookAdsApi from facebook_business.adobjects.adreportrun import AdReportRun import time import datetime import json api = FacebookAdsApi.init(access_token='xxxxx') account = AdAccount('xxxxx') today = datetime.date.today() startDate=str(today - datetime.timedelta(days=3)) endDate=str(today - datetime.timedelta(days=3)) fileName="facebook_api_"+startDate+".json" data = [] params = { 'level': AdsInsights.Level.ad, 'time_range': { 'since': startDate, 'until': endDate, }, 'fields': [ AdsInsights.Field.ad_id, AdsInsights.Field.ad_name, AdsInsights.Field.adset_name, AdsInsights.Field.campaign_id, AdsInsights.Field.campaign_name, AdsInsights.Field.reach, AdsInsights.Field.spend, AdsInsights.Field.unique_clicks,
from facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.campaign import Campaign from facebook_business.api import FacebookAdsApi access_token = 'EAAIBXnH6dpoBABQUXtk7rZBQHDI3V7ZBsRfUoty2BmXdcf0xqslRA3FwnElUqOceCeYGnx1Qo9AWoxRdisPveIuqo7bF5LJlGolQ2WblBZAWuAVBqVJ5V3KBV1MNtbVZBLG7DaHHNK1C6tJV5GPCrHmmhyf6AE0OrcxHPHNg636TLYSuBVQaZBl3bCDcQEucZD' app_secret = '638a132cb4b3d2b290f23b6385732820' app_id = '564455104214682' id = '311327033205854' FacebookAdsApi.init(access_token=access_token) fields = [ ] params = { 'name': 'My campaign', 'objective': 'LINK_CLICKS', 'status': 'PAUSED', 'special_ad_categories': [], } print (AdAccount(id).create_campaign( fields=fields, params=params, ))
FacebookAdsApi.init(app_id, app_secret, access_token) params = { 'time_range': { 'since': '2020-01-01', 'until': '2020-12-30' }, 'time_increment': 1, 'level': 'adset', 'sort': ['spend_descending'], 'export_format': 'csv' } fields = [ 'account_name', 'campaign_name', 'campaign_id', 'adset_name', 'adset_id', 'impressions', 'clicks', 'cpm', 'spend', 'ctr' ] me = User(fbid='me') my_accounts = list(me.get_ad_accounts()) insights = list( AdAccount('act_332828570147114').get_insights(params=params, fields=fields)) df = pd.DataFrame(columns=fields) for field in fields: df["{}".format(field)] = [x['{}'.format(field)] for x in insights] df.to_csv("insights.csv", index=False)
def get_facebook_data(event, context): pubsub_message = base64.b64decode(event['data']).decode('utf-8') bigquery_client = bigquery.Client() if 'date' in event['attributes']: yesterday = event['attributes']['date'].strftime('%Y-%m-%d') else: yesterday = date.today() - timedelta(1) if pubsub_message == 'get_currency': table_id = event['attributes']['table_id'] dataset_id = event['attributes']['dataset_id'] project_id = event['attributes']['project_id'] api_key = event['attributes']['api_key'] from_currency = event['attributes']['from_currency'] to_currency = event['attributes']['to_currency'] source = from_currency + to_currency cur_source = [] params = { 'access_key': api_key, 'currencies': to_currency, 'source': from_currency, 'date': yesterday.strftime("%Y-%m-%d") } url = 'http://api.currencylayer.com/historical' try: r = requests.get(url, params=params) except requests.exceptions.RequestException as e: logger.error('request to currencylayer error: {}').format(e) return e if r.json()["success"] is True: exist_dataset_table(bigquery_client, table_id, dataset_id, project_id, schema_exchange_rate) cur_source.append({ 'date': yesterday.strftime("%Y-%m-%d"), 'currencies': source, 'rate': r.json()['quotes'][source] }) insert_rows_bq(bigquery_client, table_id, dataset_id, project_id, cur_source) else: logger.error('request to currencylayer error: {}').format( r.json()['error']['info']) return 'ok' elif pubsub_message == 'get_facebook': table_id = event['attributes']['table_id'] dataset_id = event['attributes']['dataset_id'] project_id = event['attributes']['project_id'] app_id = event['attributes']['app_id'] app_secret = event['attributes']['app_secret'] access_token = event['attributes']['access_token'] account_id = event['attributes']['account_id'] try: FacebookAdsApi.init(app_id, app_secret, access_token) account = AdAccount('act_' + str(account_id)) insights = account.get_insights( fields=[ AdsInsights.Field.account_id, AdsInsights.Field.campaign_id, AdsInsights.Field.campaign_name, AdsInsights.Field.adset_name, AdsInsights.Field.adset_id, AdsInsights.Field.ad_name, AdsInsights.Field.ad_id, AdsInsights.Field.spend, AdsInsights.Field.impressions, AdsInsights.Field.clicks, AdsInsights.Field.actions, AdsInsights.Field.conversions ], params={ 'level': 'ad', 'time_range': { 'since': yesterday.strftime("%Y-%m-%d"), 'until': yesterday.strftime("%Y-%m-%d") }, 'time_increment': 1 }) except Exception as e: logger.info(e) print(e) raise fb_source = [] for index, item in enumerate(insights): actions = [] conversions = [] if 'actions' in item: for i, value in enumerate(item['actions']): actions.append({ 'action_type': value['action_type'], 'value': value['value'] }) if 'conversions' in item: for i, value in enumerate(item['conversions']): conversions.append({ 'action_type': value['action_type'], 'value': value['value'] }) fb_source.append({ 'date': item['date_start'], 'ad_id': item['ad_id'], 'ad_name': item['ad_name'], 'adset_id': item['adset_id'], 'adset_name': item['adset_name'], 'campaign_id': item['campaign_id'], 'campaign_name': item['campaign_name'], 'clicks': item['clicks'], 'impressions': item['impressions'], 'spend': item['spend'], 'conversions': conversions, 'actions': actions }) if exist_dataset_table(bigquery_client, table_id, dataset_id, project_id, schema_facebook_stat, clustering_fields_facebook) == 'ok': insert_rows_bq(bigquery_client, table_id, dataset_id, project_id, fb_source) return 'ok'
# 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 facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.customaudience import CustomAudience from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<AD_ACCOUNT_ID>' FacebookAdsApi.init(access_token=access_token) fields = [ ] params = { 'name': 'My Test Engagement Custom Audience', 'rule': {'inclusions':{'operator':'or','rules':[{'event_sources':[{'id':'<pageID>','type':'page'},{'id':'<pageID2>','type':'page'}],'retention_seconds':31536000,'filter':{'operator':'and','filters':[{'field':'event','operator':'eq','value':'page_engaged'}]}}]}}, 'prefill': '1', } print AdAccount(id).create_custom_audience( fields=fields, params=params, )
# 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 facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.adcreative import AdCreative from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<AD_ACCOUNT_ID>' FacebookAdsApi.init(access_token=access_token) fields = [ ] params = { 'object_story_id': '<pageID>_<postID>', } print AdAccount(id).create_ad_creative( fields=fields, params=params, )
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])
def get_ad_sets(self, account_id, include_archived, limit): """ Retrieves and displays a list of ad sets of a given account, and analyze how likely a similar ad for Instagram can be created. Params: * `account_id` is your Facebook Ad Account id. * `include_archived` specifies whether archived ad sets should be analyzed. * `limit` is how many ad sets to analyze. This script will analyze the first `limit` ad sets as in the response, not including those which use Instagram placement already. The more this limit is, the longer it takes to run. If you run the script directly and are willing to wait for a while, you can drop the lines of code around it. For more information see the [Instagram Ads document]( https://developers.facebook.com/docs/marketing-api/guides/instagramads/) """ locale.setlocale(locale.LC_ALL, '') if include_archived: params = { 'limit': limit, AdSet.Field.configured_status: [ 'PENDING', 'ACTIVE', 'PAUSED', 'PENDING_REVIEW', 'DISAPPROVED', 'PREAPPROVED', 'PENDING_BILLING_INFO', 'CAMPAIGN_PAUSED', 'CAMPAIGN_GROUP_PAUSED', 'ARCHIVED' ], } else: params = {'limit': limit} account = AdAccount(account_id) ad_sets = account.get_ad_sets(fields=[ AdSet.Field.id, AdSet.Field.campaign_id, AdSet.Field.name, AdSet.Field.configured_status, AdSet.Field.targeting, ], params=params) cache = {} count = 0 results = [] for ad_set in ad_sets: if count >= limit: break count += 1 result = {} result['id'] = ad_set['id'] result['name'] = ad_set['name'] logger.error(ad_set) # Get targeting from ad set targeting = ad_set.get(AdSet.Field.targeting, None) logger.error(targeting) if targeting is not None: publisher_platforms = targeting.get('publisher_platforms', None) pp_str = '' if publisher_platforms is None: result['publisher_platforms'] = '<li>DEFAULT</li>' else: for pp in publisher_platforms: pp_str += ('<li>' + self.translate_placement_publisher( str(pp)) + '</li>') result['publisher_platforms'] = pp_str params = { 'currency': 'USD', 'targeting_spec': targeting, 'optimize_for': AdSet.OptimizationGoal.impressions, } if publisher_platforms is not None and "instagram" in \ publisher_platforms: count -= 1 continue reach_fb = account.get_reach_estimate(params=params)[0].get( 'users', 0) targeting['publisher_platforms'] = ["instagram"] targeting['facebook_positions'] = None params = { 'currency': 'USD', 'targeting_spec': targeting, 'optimize_for': AdSet.OptimizationGoal.impressions, } reach_ig = account.get_reach_estimate(params=params)[0].get( 'users', 0) self.add_check_result(result, self.check_audience(reach_fb, reach_ig)) result["audience"] = reach_ig * 100 / reach_fb result["ig_audience"] = locale.format("%d", reach_ig, grouping=True) # Get objective and status from Campaign campaign_id = ad_set[AdSet.Field.campaign_id] campaign = self.get_ad_campaign(cache, campaign_id) result["c_objective"] = \ campaign[Campaign.Field.objective].replace("_", " ") result["c_status"] = campaign[Campaign.Field.configured_status] check = self.check_objective(result["c_objective"]) if check['eligibility'] == 5: result['objective_supported'] = 1 elif check['eligibility'] == 1: result['objective_supported'] = 0 else: result['objective_supported'] = 2 self.add_check_result(result, check) # Get creative and check the media if campaign[Campaign.Field.objective] == 'PRODUCT_CATALOG_SALES': result['preview_url'] = \ 'Images from product catalog are not supported.' results.append(result) result['creative_ready'] = False continue creatives = ad_set.get_ad_creatives([ AdCreative.Field.object_story_id, ]) result['creative_ready'] = False if not creatives: comment = 'No creative found in this ad set.' self.add_check_result(result, { "eligibility": 3, }) result['preview_url'] = comment results.append(result) continue creative = creatives[0] story_id = creative.get(AdCreative.Field.object_story_id, 0) if story_id == 0: comment = 'No post fround in the first creative of this ad set.' self.add_check_result(result, { "eligibility": 3, }) result['preview_url'] = comment results.append(result) continue # Check whether the creative's post is IG ready try: # This Graph API call is not a part of Ads API thus no SDK post = FacebookAdsApi.get_default_api().call( 'GET', (story_id, ), params={ 'fields': 'is_instagram_eligible,child_attachments' }, ) post_ig_eligible = post.json()['is_instagram_eligible'] except FacebookRequestError: post_ig_eligible = False result['creative_ready'] = post_ig_eligible if post_ig_eligible: self.add_check_result(result, { "eligibility": 5, }) # Generate preview # As we do not know which IG account you will use, # just use a hardcoded one for preview. jasper_ig_account = "1023317097692584" ad_format = AdPreview.AdFormat.instagram_standard creative_spec = { AdCreative.Field.instagram_actor_id: jasper_ig_account, AdCreative.Field.object_story_id: story_id, } params = { 'creative': creative_spec, 'ad_format': ad_format, } preview = account.get_generate_previews(params=params) result['preview_url'] = preview[0].get_html() \ .replace('width="320"', 'width="340"', 1) else: comment = 'The creative needs to be modified for Instagram.' self.add_check_result(result, { "eligibility": 3, }) result['preview_url'] = comment results.append(result) return list( sorted(results, key=lambda result: result['eligibility'], reverse=True))
# 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 facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.adcreative import AdCreative from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<ID>' FacebookAdsApi.init(access_token=access_token) fields = [ 'name', ] params = {} print AdAccount(id).get_ad_creatives( fields=fields, params=params, )
def api_create(self, parent_id, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.adobjects.adaccount import AdAccount return AdAccount(api=self._api, fbid=parent_id).create_ad_creative(fields, params, batch, success, failure, pending)
def api_create(self, parent_id, fields=None, params=None, batch=None, pending=False): from facebook_business.adobjects.adaccount import AdAccount return AdAccount(api=self._api, fbid=parent_id).get_insights_async(fields, params, batch, pending)