def create_campaign(campaign_data, account): """Creates a campaign, by default in paused status Args: campaign_data (dict): A dict with campaign data, parsed from JSON account (str): Account where to upload the campaign Returns: object: Campaign object? """ # Existing campaing can be defined via campaign_id (or maybe name, not sure yet) if campaign_data.get('campaign_id'): campaign = Campaign(fbid=campaign_data.get('campaign_id'))[Campaign.Field.id] else: campaign[Campaign.Field.name] = campaign_data.get('campaign_name') campaign[Campaign.Field.objective] = getattr(Campaign.Objective, campaign_data.get('objective')) # If not status is given, then default to Paused campaign[Campaign.Field.status] = getattr(Campaign.Status, campaign_data.get('status', 'paused')) campaign.remote_create() # Returns campaign id, it seems. Why do it via AdSet, dunno campaign_id = campaign[AdSet.Field.id] return campaign_id
def get_adsets(campaign_id): fields = ["id", "name"] def decorate(n, x): return {"value": x["id"], "name": x.get("name", "Adset #%s" % n)} account = Campaign(campaign_id) return [decorate(n, x) for n, x in enumerate(account.get_ad_sets(fields))]
def get_adset_info_by_campaign(self, campaign_id): campaign = Campaign('%s' % str(campaign_id)) adsets = campaign.get_ad_sets(fields=[ AdSet.Field.id, AdSet.Field.name, AdSet.Field.campaign_id, AdSet.Field.status ]) if adsets: return adsets return {}
def create_campaign(account_id, name, objective, status): account = AdAccount(account_id) campaign = Campaign(parent_id=account.get_id_assured()) campaign[Campaign.Field.name] = name campaign[Campaign.Field.objective] = objective campaign[Campaign.Field.configured_status] = status print(campaign.remote_create())
def get_campaign(): """ Fetching your campaign """ campaign = Campaign(my_campaign_id) campaign.remote_read(fields=[Campaign.Field.name, Campaign.Field.objective]) assert campaign[Campaign.Field.name] == 'my_man_joon SDK' assert campaign[Campaign.Field.objective] == Campaign.Objective.page_likes return campaign
def get_campaign(): """ Fetching your campaign, and checking that you get the right result """ campaign = Campaign(my_campaign_id) campaign.remote_read( fields=[Campaign.Field.name, Campaign.Field.objective]) assert campaign[Campaign.Field.name] == 'We\'re Toast SDK' assert campaign[Campaign.Field.objective] == Campaign.Objective.page_likes return campaign
def get_prospecting_campaign_id(self, acc_id): """Takes in an account id and searches across the ad accounts campaigns looking for the campaign name Prospecting. If found, return the campaign id.""" account = AdAccount(acc_id).get_campaigns() for camp in account: campaign = Campaign(camp['id']) campaign.remote_read(fields=[ Campaign.Field.name, ]) if campaign['name'] == 'Prospecting': return camp['id']
def create_campaign(): campaign = Campaign(parent_id='act_259842962') campaign.update({ Campaign.Field.name: 'My Campaign', Campaign.Field.objective: Campaign.Objective.link_clicks, }) campaign.remote_create(params={ 'status': Campaign.Status.paused, }) print(campaign) return campaign
def spent_on_event(self, event): fields = ['campaign_name', 'campaign_id', 'spend'] params = {"date_preset": "lifetime"} if event.facebook_campaign_id: # my_account = objects.AdAccount('act_19596279') campaign_id = event.facebook_campaign_id campaign = Campaign(campaign_id) insights = campaign.get_insights(fields=fields, params=params) if len(insights) > 0: return insights[0]['spend'] else: return None else: return None
def get_current_date_stats(self, campaign_id, curr_date): """Takes in a campaign id and returns all the required data for the current date""" campaign = Campaign(campaign_id) fields = ['account_name', 'campaign_name', 'clicks', 'cpc', 'reach', 'ctr', 'frequency', 'impressions', 'cpm', 'relevance_score'] insights = campaign.get_insights(fields=fields, params={ 'time_range':{'since':curr_date, 'until':curr_date}, 'time_increment':1}) return insights
def get_adset_list(campaign_id): try: campaign = Campaign(campaign_id) adsets = campaign.get_ad_sets( fields=[AdSet.Field.name, AdSet.Field.id, AdSet.Field.status], params={ AdSet.Field.effective_status: [AdSet.EffectiveStatus.active] }) active_adset_hash = {} for adset in adsets: active_adset_hash[adset[AdSet.Field.id]] = adset[AdSet.Field.name] logger.info(active_adset_hash) return active_adset_hash except exceptions.FacebookError, e: logger.error('Error %s' % e) return {}
def main(access_token, ad_account_id, app_secret, *args, **kwargs): FacebookAdsApi.init(access_token=access_token) adAccounts = AdAccount(ad_account_id).get_insights( fields=['campaign_id'], params={ 'level': 'campaign', 'breakdowns': [], }, ) insights = [] with open('marketing.csv', 'w') as csvfile: writter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) writter.writerow(['date', 'campaign_id', 'campaign_name', 'spend']) for adAccount in adAccounts: campaign = Campaign(adAccount['campaign_id']) params = { 'level': 'ad', 'date_preset': 'lifetime', 'time_increment': 1, 'fields': ['campaign_id', 'spend', 'campaign_name'] } insights += campaign.get_insights(params=params) for insight in insights: writter.writerow([ insight['date_start'], insight['campaign_id'], insight['campaign_name'], insight['spend'], ])
def get_adset_insight_by_campaign(self, campaign_id, breakdown_attribute=None, start_dt=None, stop_dt=None): campaign = Campaign('%s' % str(campaign_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_name', 'adset_id', 'action_values', 'clicks', 'impressions', 'reach', 'spend', 'actions', 'cpc', 'cpm', 'cpp', 'ctr', 'frequency' ] params['level'] = 'adset' insights = campaign.get_insights(params=params) if insights: return insights return {}
def create_campaign(self, act_id, campaign_name, spend_cap=10000, campaign_objective=Campaign.Objective.link_clicks): """ Creates named campaign within the advertising account with spendcap.a A full list of campaign objectives is available at Campaign.Objective Returns <Campaign> { "id": "6090107330196", "name": "AJM_TEST_NES", "objective": "LINK_CLICKS" } """ campaign = Campaign(parent_id='act_{}'.format(act_id)) campaign.update({ Campaign.Field.spend_cap: spend_cap, Campaign.Field.name: campaign_name, Campaign.Field.objective: campaign_objective, }) campaign.remote_create(params={ 'status': Campaign.Status.paused, }) return campaign
def get_campaign_stats(self,campaign_id): """Takes in a campaign id and returns all the required data points for the campaign""" campaign = Campaign(campaign_id) fields = ['account_name', 'campaign_name', 'clicks', 'cpc', 'reach', 'ctr', 'frequency', 'impressions', 'cpm', 'relevance_score'] #Need to create a new list for data data = [] #Grab lifetime campaign stats to find start and end date of campaign and convert to datetime formate insights = campaign.get_insights(fields=fields, params={'date_preset':'lifetime'}) date_begin = datetime.datetime.strptime(insights[0]['date_start'], "%Y-%m-%d") date_end = datetime.datetime.strptime(insights[0]['date_stop'], "%Y-%m-%d") date_diff = datetime.timedelta(days=25) new_date = date_begin + date_diff #Pass in these values to the api api_date_first = str(date_begin).split()[0] api_date_last = str(new_date).split()[0] #Strange API limitation where you can only grab 25 values at a time. while date_begin < date_end: insights = campaign.get_insights(fields=fields, params={ 'time_range':{'since':api_date_first, 'until':api_date_last}, 'time_increment':1}) insights = list(insights) date_begin = new_date new_date = date_begin + date_diff api_date_first = api_date_last api_date_last = str(new_date).split()[0] data += insights return data
def create_campaign(): campaign_name = raw_input("Please enter campaign name.\n") campaign = Campaign(parent_id=header.my_account['id']) campaign.update({ Campaign.Field.name: campaign_name, Campaign.Field.objective: Campaign.Objective.link_clicks, }) campaign.remote_create(params={ 'status': Campaign.Status.paused, }) campaign = str(campaign) campaign = campaign.replace('<Campaign> ', '') campaign = json.loads(campaign) return campaign['id']
Campaign.Field.name, Campaign.Field.objective, } params = { Campaign.Field.effective_status: [ 'ACTIVE', ], } account = AdAccount(ad_account_id) campaigns = account.get_campaigns(fields=fields, params=params) print campaigns fields = [ AdsInsights.Field.impressions, AdsInsights.Field.inline_link_clicks, AdsInsights.Field.spend, ] params = { 'end_time': 1504275690, } if len(campaigns) > 0: campaign = Campaign(campaigns[0]['id']) insights = campaign.get_insights(fields=fields, params=params) print insights
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
categories = file['categories'].split(',') number_of_ads = int(file['number_of_ads']) number_of_items = int(file['number_of_items']) number_of_cards = int(file['number_of_cards']) interest_list = file['interest_list'].split(',') age_min = int(file['age_min']) age_max = int(file['age_max']) daily_budget = file['daily_budget'] bid_amount = file['bid_amount'] start_time = file['start_time'] end_time = file['end_time'] connection1 = header.create_connection(os.environ['FB_APP_DATABASE_URL']) dbCursor = connection1.cursor(cursor_factory=psycopg2.extras.DictCursor) campaign = Campaign(campaign_id) campaign.remote_read(fields=[Campaign.Field.name, Campaign.Field.id]) countries = campaign[Campaign.Field.name].split(',') for country in countries: for name in categories: for interest in interest_list: adset_name = interest.replace('.txt', '') + '-' + name interests = get_targeting.list_ids(interest) adset_id = adset.create_adset(country, interests, age_min, age_max, adset_name, campaign_id, daily_budget, bid_amount, start_time, end_time) dbCursor.execute( "SELECT l.design_id FROM line_items l,categories_designs cd,categories c WHERE cd.design_id=l.design_id AND c.id=cd.category_id AND l.created_at > current_date - interval '90' day and c.name like '" + name +
import initialization from facebookads.adobjects.campaign import Campaign AD_ACCOUNT_ID = initialization.account_id parent_id = AD_ACCOUNT_ID campaign = Campaign(parent_id=parent_id) campaign.update({ Campaign.Field.name: 'Test Campaign', Campaign.Field.objective: Campaign.Objective.link_clicks, }) campaign.remote_create(params={ 'status': Campaign.Status.paused, })
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token) my_business = Business(fbid=my_business_id) # print("my_business:", my_business) my_accounts = list(my_business.get_assigned_ad_accounts()) # print("All accounts:", my_accounts) selected_adaccount = my_accounts[1] # print("Selected Ad Account:", selected_adaccount) campaign_fields = [ Campaign.Field.id, Campaign.Field.name, Campaign.Field.objective, Campaign.Field.status ] # Import a list of Campaigns' Id. # Create your list by listing your Campaign Ids # in the campaigns_group var located in your my_facebook_access.py, # which should be located on your Desktop (see README.md). # Also, you can just create a list var of Campaign Ids directly here, in this file. selected_campaigns = campaigns_group for each_campaign in selected_campaigns: selected_campaign = Campaign(fbid=each_campaign) print(selected_campaign.api_get(fields=campaign_fields)) selected_adsets = selected_campaign.get_ad_sets([ AdSet.Field.id, AdSet.Field.name, AdSet.Field.status, AdSet.Field.optimization_goal, AdSet.Field.billing_event, AdSet.Field.bid_amount, AdSet.Field.bid_info ]) print(selected_adsets)
def activate_campaign(): campaign = Campaign(my_campaign_id) campaign[Campaign.Field.status] = 'ACTIVE' campaign.remote_update() pass
def read_campaign(id): campaign = Campaign(id) campaign.remote_read(fields=[Campaign.Field.name]) print(campaign) return campaign
def get_campaign(): """ Fetch your campaign """ campaign = Campaign(my_campaign_id) pass
""" campaign_fields = [ Campaign.Field.id, Campaign.Field.name, Campaign.Field.objective, Campaign.Field.status ] # Import a list of Campaigns' Id. # Create your list by listing your Campaign Ids # in the campaigns_group var located in your my_facebook_access.py, # which should be located on your Desktop (see README.md). # Also, you can just create a list var of Campaign Ids directly here, in this file. selected_campaigns = campaigns_group for each_campaign in selected_campaigns: selected_campaign = Campaign(fbid=each_campaign) print(selected_campaign.api_get(fields=campaign_fields)) # Use the code bellow to do changes in the Campaign (selected_campaign): """ print("Before:", selected_campaign.api_get(fields=campaign_fields)) selected_campaign.api_update(params={ 'status': Campaign.Status.paused }) print("After:", selected_campaign.api_get(fields=campaign_fields)) """ selected_adsets = selected_campaign.get_ad_sets( [AdSet.Field.id, AdSet.Field.name, AdSet.Field.status])
def get_campaign(): """ Fetch your campaign """ campaign = Campaign(my_campaign_id) return campaign
]) #print(account.get_activities()) #"event_time": "2018-03-10T01:05:58+0000", #"event_type": "update_ad_run_status" header = "access_token=" + access_token #url = "https://graph.facebook.com/v2.10/act_693598040844198/campaigns?fields=name,status,insights{reach,impressions,clicks}" #res = r.get(url,headers=header) #i = AdAccount(aid).get_insights(fields=fields, async=True) from facebookads.adobjects.campaign import Campaign from facebookads.adobjects.adsinsights import AdsInsights as Insights campaign = Campaign('23842767635360263') params = {'time_range': {'since': '2018-02-01', 'until': '2018-03-01'}} insights = account.get_insights(params=params) print(insights) #print(campaign.Field.name.Impressions) #print(campaign.get_ads(fields=["name","status","insights{reach,impressions,clicks}"])) #print(campaign[adobjects.campaign]) #insights = campaign.get_insights(params=params) #print(insights) #print(account.remote_read(fields=[AdAccount.Field.end_advertiser_name]))
def facebook_campaign_stats(adcampaign, start_date_str, end_date_str, allow_cache=False): session = FacebookSession(BUSINESS_APP_ID, BUSINESS_APP_SECRET, adcampaign.ad_account.access_token) api = FacebookAdsApi(session) FacebookAdsApi.set_default_api(api) params = { 'time_range': { 'since': start_date_str, 'until': end_date_str, }, 'fields': [ AdsInsights.Field.impressions, AdsInsights.Field.clicks, AdsInsights.Field.spend, AdsInsights.Field.actions, AdsInsights.Field.ctr, AdsInsights.Field.inline_link_clicks, AdsInsights.Field.inline_link_click_ctr, AdsInsights.Field.cpc, ], } cache_file = '/tmp/%s-%s-%s.json' % (adcampaign.fbid, start_date_str, end_date_str) if allow_cache and os.path.isfile(cache_file): last_modified = datetime.fromtimestamp(os.path.getmtime(cache_file)) if last_modified > datetime.now() - timedelta(hours=1): with open(cache_file, 'r') as cache_file: return json.load(cache_file) last_err = None # TODO(chesterwu): verify the API rate limit not exceeded. Ref - # developers.facebook.com/docs/marketing-api/api-rate-limiting for i in xrange(3): try: campaign = Campaign(adcampaign.fbid) campaign_api_response = campaign.remote_read(fields=[ Campaign.Field.effective_status, Campaign.Field.spend_cap ]) insights = campaign.get_insights(params=params) except FacebookError as e: last_err = e else: break else: raise Exception( 'Failed to retrieve Facebook data for Adcampaign %s: %s' % (adcampaign, str(last_err))) if insights: insight = insights[0] campaign_stats = { 'status': campaign_api_response.get('effective_status'), 'spend_cap': campaign_api_response.get('spend_cap'), 'impressions': insight['impressions'], 'clicks': insight['clicks'], 'spent': float(insight['spend']) * 100, 'ctr': insight['ctr'], 'link_clicks': insight['inline_link_clicks'], 'website_ctr': insight['inline_link_click_ctr'], 'cpc': insight['cpc'], } else: campaign_stats = { 'status': campaign_api_response.get('effective_status'), 'spend_cap': campaign_api_response.get('spend_cap'), 'impressions': 0, 'clicks': 0, 'link_clicks': 0, 'spent': 0, 'ctr': None, 'website_ctr': None, 'cpc': None, } with open(cache_file, 'w') as cache_file: json.dump(campaign_stats, cache_file) return campaign_stats
# 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.campaign import Campaign from facebookads.adobjects.ad import Ad 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 = [ 'name', ] params = {} print Campaign(id).get_ads( fields=fields, params=params, )
__author__ = "DonQ" from facebookads import objects from facebookads.adobjects.campaign import Campaign from facebookads.api import FacebookAdsApi my_app_id = '1251527148216435' my_app_secret = 'f5c8b29c2e3636d0112f8cebac0648da' my_access_token = 'EAARyQd8YoHMBAMWk85H02JS90mfRz2bTvWcZB9cxjBvIwalFmmWmK5rcRTJ3ulTgFQ9Tt0KnFJtfZA4AND3FWkWpBEYhNSndZBi' \ 'ZCF7iKStXhvBwX5eFNcQ6VwbmJ3lHcfmZC8tRZCZBYP8cRP2B7wj6JZCBczTQJnE8rqSPGSLgzh0d5ZBjjwWOIuLH8JgHLr9p0SgS' \ 'iam01ObZB4rs5ruozs' proxies = { 'http': 'http://101.251.219.122:7070', 'https': 'http://101.251.219.122:7070' } FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token, proxies=proxies) # me = objects.AdUser(fbid='me') # my_accounts = list(me.get_ad_accounts()) # print my_accounts # print type(my_accounts[0]) campaign = Campaign(parent_id='act_117254168798866') campaign.update({ Campaign.Field.name: 'My Campaign', Campaign.Field.objective: Campaign.Objective.link_clicks, }) Campaign.remote_create(params={ 'status': Campaign.Status.paused, })
# Call Facebook Api FacebookAdsApi.init(access_token=access_token) # Add after FacebookAdsApi.init me = AdAccountUser(fbid='me') my_account = me.get_ad_accounts()[0] Account_Id = my_account['id'] # Set up Account class class Account(object): def __init__(self, account_id): self.account_id = account_id # Add new Account ID new_acc = Account(account_id=Account_Id) campaign = Campaign(new_acc.account_id) params = {'date_preset': 'this_year'} fields = [ 'campaign_name', 'adset_name', 'adset_id', 'impressions', 'spend', 'reach', 'actions', 'action_values' ] insights = campaign.get_insights(fields, params) print insights
#Use one of these campaign objectives: #EVENT_RESPONSES, LINK_CLICKS, OFFER_CLAIMS, PAGE_LIKES, #POST_ENGAGEMENT, PRODUCT_CATALOG_SALES, VIDEO_VIEWS, #LEAD_GENERATION, LOCAL_AWARENESS, BRAND_AWARENESS, #REACH, APP_INSTALLS, CONVERSIONS params = { 'name': campaign_name, 'objective': 'BRAND_AWARENESS', 'status': campaign_status, } # when using parent id get this message: WARNING:root:parent_id as a parameter of constructor is being deprecated. # need to figure out new approache campaign = Campaign(parent_id=my_parent_id) campaign.remote_create(params=params) campaign_id = campaign.get_id() ### Ad Set ### print 'Creating Ad Set: ', adset_name params = { 'name': adset_name, 'optimization_goal': 'BRAND_AWARENESS', 'billing_event': 'IMPRESSIONS', 'promoted_object': { 'page_id': page_id }, 'daily_budget': my_daily_budget, 'is_autobid': True,