def view_campaign(request): FacebookAdsApi.init(access_token=access_token, app_id=app_id, app_secret=app_secret) my_account = AdAccount('act_' + user_id) campaigns = my_account.get_campaigns() camp_id = [] for i in range(len(campaigns)): camp_id.append(campaigns[i]["id"]) campaign_data = [] for id in camp_id: campaign = Campaign(fbid=id) fields = [ Campaign.Field.id, Campaign.Field.name, Campaign.Field.status, ] campaign.remote_read(fields=fields) result = {} result["id"] = campaign[Campaign.Field.id] result["name"] = campaign[Campaign.Field.name] result["status"] = campaign[Campaign.Field.status] result["data_1"] = "ACTIVE" result["data_2"] = "PAUSED" campaign_data.append(result) context = {'campaigns': campaign_data} return render(request, 'fbapp/view_campaign.html', context)
def get_campaign_insights(self, date_preset=None): campaign = Campaign(self.campaign_id) params = { 'date_preset': date_preset, } insights = campaign.get_insights( params=params, fields=list(general_insights.values()) + list(target_insights.values())) if bool(insights): spend = insights[0].get(Field.spend) impressions = insights[0].get(Field.impressions) self.campaign_insights.update({Field.spend: int(spend)}) self.campaign_insights.update( {Field.impressions: int(impressions)}) for act in insights[0].get(Field.actions): if act["action_type"] in conversion_metrics: self.campaign_insights.update({ conversion_metrics[act["action_type"]]: int(act["value"]) }) self.campaign_insights.update({ 'cost_per_' + conversion_metrics[act["action_type"]]: float(spend) / float(act["value"]) }) return self.campaign_insights
def get_campaign_app(result_queue, campaign_info, app_id): try: logger.debug('campaign:{} get app'.format( campaign_info.get('CampaignId'))) facebook_app = facebook_apps.get(app_id) api = FacebookAdsApi.init(facebook_app.app_id, facebook_app.app_secret, facebook_app.access_token) Campaign(api=api) promoted_object = Campaign( campaign_info.get('CampaignId')).get_ad_sets( fields=['promoted_object'], params={'limit': 1000}) campaign_info['FBAppId'] = np.nan campaign_info['AppStoreUrl'] = np.nan campaign_info['CampaignName'] = np.nan for po in promoted_object: # try: if po.get('promoted_object') and po.get('promoted_object').get( 'object_store_url') and po.get('promoted_object').get( 'application_id'): campaign_info['FBAppId'] = str( po['promoted_object']['application_id']) campaign_info['AppStoreUrl'] = po['promoted_object'][ 'object_store_url'] break # except: # continue campaign_name = Campaign(campaign_info.get('CampaignId')).api_get( fields=[Campaign.Field.name], params={'limit': 1000}) if campaign_name.get('name'): campaign_info['CampaignName'] = campaign_name['name'] result_queue.put(campaign_info) except ConnectionError: raise except Exception, ex: logger.error('get_campaign_app error, ex:{}'.format(ex))
def campaign_status_update(self, campaign_id): try: campaign = Campaign(campaign_id) campaign[Campaign.Field.status] = 'ACTIVE' campaign.remote_update() print("Sucussfully Campaign updated!") except Exception as e: print(e)
def get_adsets(self): adset_list = list() campaign = Campaign(self.campaign_id) adsets = campaign.get_ad_sets(fields=[AdSet.Field.id]) ads = campaign.get_ad_sets(fields=[AdSet.Field.id]) for adset in adsets: adset_list.append(adset.get("id")) return adset_list
def delete_campaign(request, camid): FacebookAdsApi.init(access_token=access_token, app_id=app_id, app_secret=app_secret) campaign = Campaign(camid) campaign.remote_delete() return redirect('view-campaign')
def _fake_data_factory(self, fbid=None, **data): """ Fake campaign factory for testing purposes :return Campaign: Facebook SDK campaign object """ test_campaign = Campaign(fbid or self.campaign_id) test_campaign[Campaign.Field.account_id] = self.ad_account_id test_campaign.update(data) return test_campaign.export_all_data()
def update_campaign(request, campid, status): FacebookAdsApi.init(access_token=access_token, app_id=app_id, app_secret=app_secret) campaign = Campaign(campid) campaign[Campaign.Field.status] = status campaign.remote_update() return redirect('view-campaign')
def home(request): FacebookAdsApi.init(access_token=access_token, app_id=app_id, app_secret=app_secret) my_account = AdAccount('act_' + user_id) campaign = Campaign(parent_id=my_account.get_id_assured()) context = {"id": campaign.get_id()} return render(request, 'fbapp/home.html', context)
def createCampaign(self, name): print("**Creating {} Campaign...**".format(name)) campaign = Campaign() campaign['_parent_id'] = self.id campaign[Campaign.Field.name] = name campaign[Campaign.Field.objective] = 'LINK_CLICKS' campaign[Campaign.Field.status] = 'PAUSED' campaign.remote_create() self.campaign_id = str(campaign[Campaign.Field.id]) print("**Campaign ID: {}**".format(self.campaign_id)) return campaign
def create_campaign(self, account_id, name): """ Step 2: create a campaign. See [Campaign][1] for further details on the API used here. [1]: https://developers.facebook.com/docs/marketing-api/adcampaign """ campaign = Campaign(parent_id=account_id) campaign[Campaign.Field.name] = name campaign[Campaign.Field.objective] = (Campaign.Objective.app_installs) campaign.remote_create(params={'status': Campaign.Status.paused}) return campaign[Campaign.Field.id]
def create_campaign(_name, _spend_cap=None, _objective='CONVERSIONS', _buying_type='AUCTION', _status='Paused', _ad_account= ad_account_id): from facebook_business.adobjects.campaign import Campaign if _spend_cap > 999: pr = input("Campaign spend cap is set to $" + str(_spend_cap) + " (y/n)?") if pr != "y": _spend_cap = input("Enter the correct spend cap in dollars: $") if _spend_cap is None: _spend_cap = 922337203685478 #10000 = $100 else: _spend_cap = _spend_cap * 100 print(_spend_cap) campaign = Campaign(parent_id=_ad_account) campaign.update({ Campaign.Field.name: _name, Campaign.Field.objective: _objective, #APP_INSTALLS, BRAND_AWARENESS, CONVERSIONS, EVENT_RESPONSES, LEAD_GENERATION, LINK_CLICKS, LOCAL_AWARENESS, MESSAGES, OFFER_CLAIMS, PAGE_LIKES, POST_ENGAGEMENT, PRODUCT_CATALOG_SALES, REACH, VIDEO_VIEWS Campaign.Field.spend_cap: _spend_cap, #value of 922337203685478 will undo spend cap Campaign.Field.buying_type: _buying_type }) if _status == 'Active': campaign.remote_create(params={ #remote_update to change and remote_delete to delete 'status': Campaign.Status.active, }) else: campaign.remote_create(params={ # remote_update to change and remote_delete to delete 'status': Campaign.Status.paused, }) return campaign
def fetch_campaign_data(self, campaign_id): campaign = Campaign(campaign_id) campaign_datas = campaign.get_insights(fields=[ AdsInsights.Field.campaign_id, AdsInsights.Field.campaign_name, AdsInsights.Field.spend, AdsInsights.Field.impressions, AdsInsights.Field.unique_actions, AdsInsights.Field.reach], params={ 'breakdowns': ['hourly_stats_aggregated_by_audience_time_zone'], 'time_range': self.time_range}) return campaign_datas
def list_ad_set(): FacebookAdsApi.init(access_token=my_access_token) fields = [ 'account_id', 'attribution_spec', 'bid_strategy', 'billing_event', 'budget_remaining', 'campaign', 'campaign_id', 'configured_status', 'created_time', 'creative_sequence', 'daily_budget', 'destination_type', 'effective_status', 'id', 'lifetime_budget', 'lifetime_imps', 'name', 'optimization_goal', 'pacing_type', 'recommendations', 'recurring_budget_semantics', 'source_adset_id', 'start_time', 'status', 'targeting', 'updated_time', 'use_new_app_click', ] return Campaign(f'act_{ad_account}').get_ad_sets(fields=fields)
def create_campaign(self, campaign_name, objective, status, spend_cap): if not self.cam_dict: self.set_id_name_dict(Campaign) if campaign_name in ([x['name'] for x in self.cam_dict]): logging.warning(campaign_name + ' already in account. This ' + 'campaign was not uploaded.') return None self.campaign = Campaign(parent_id=self.account.get_id_assured()) self.campaign.update({ Campaign.Field.name: campaign_name, Campaign.Field.objective: objective, Campaign.Field.effective_status: status, Campaign.Field.spend_cap: int(spend_cap), Campaign.Field.special_ad_categories: 'NONE' }) self.campaign.remote_create()
def loadCampaignFromJson(self, jsonFile): campaign = Campaign(parent_id=self.account_id) config_file = open(jsonFile) config = json.load(config_file) config_file.close() for key in config.keys(): campaign[key] = config[key] return campaign
def run_query_on_fb_campaign_obj_conf(self, params, ad_object_id): campaign = Campaign(ad_object_id) if self.level == LEVELS_POSSIBLE_VALUES[2]: val_cmp = campaign.api_get(fields=self.desired_fields, params=params) yield val_cmp elif self.level == LEVELS_POSSIBLE_VALUES[1]: for el in chain(*[ self.run_query_on_fb_adset_obj_conf( params, adset.get("id")) for adset in campaign.get_ad_sets() ]): yield el else: raise ClickException("Received level: " + self.level + ". Available levels are " + repr(LEVELS_POSSIBLE_VALUES[1:3]))
def create_campaign(request): FacebookAdsApi.init(access_token=access_token, app_id=app_id, app_secret=app_secret) my_account = AdAccount('act_' + user_id) campaign = Campaign(parent_id=my_account.get_id_assured()) campaign[Campaign.Field.name] = "Campaign created by afnan -" + str( random.randint(1, 10)) campaign[Campaign.Field.objective] = 'LINK_CLICKS' campaign[Campaign.Field.status] = 'ACTIVE' campaign.remote_create() result = {"id": campaign.get_id()} return redirect('view-campaign')
def fetch_campaign_data(campaign_id): campaign = Campaign(campaign_id) campaign_datas = campaign.get_insights( fields=[ AdsInsights.Field.campaign_id, AdsInsights.Field.campaign_name, AdsInsights.Field.spend, AdsInsights.Field.impressions, AdsInsights.Field.unique_actions, AdsInsights.Field.reach ], params={ 'breakdowns': ['hourly_stats_aggregated_by_audience_time_zone'], 'time_range': { 'since': yesterday, 'until': today } }) for campaign_data in campaign_datas: result = {} result['spend'] = campaign_data['spend'] if\ 'spend' in campaign_data else '' result['impression_count'] = campaign_data['impressions'] if\ 'impressions' in campaign_data else '' result['reach_count'] = campaign_data['reach'] if\ 'reach' in campaign_data else '' result['ad_compaign_id'] = campaign_data['campaign_id'] if\ 'campaign_id' in campaign_data else '' result['stat_dt'] = campaign_data['date_start'] print(result['stat_dt']) result['stat_hour'] = \ str(int(campaign_data['hourly_stats_aggregated_by_audience_time_zone'][0:2]) + 1) try: for actions in campaign_data['unique_actions']: if actions['action_type'] == 'link_click': result['link_click_count'] = actions['value'] if actions[ 'action_type'] == 'offsite_conversion.fb_pixel_purchase': result['effective_count'] = actions['value'] except Exception as e: result['effective_count'] = '' result['link_click_count'] = '' result['create_time'] =\ datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") yield result
def get_ad_campaign(self, cache, campaign_id): """ Get the ad campaign. As some ad sets being analyzed belong to the same ad campaign, a caching is used to reduce the API calls. Params: * `cache` ad campaigns obtained already. * `campaign_id` the id of the ad campaign to be queried out. """ if (cache.get(campaign_id) is None): campaign = Campaign(fbid=campaign_id) campaign.remote_read(fields=[ Campaign.Field.name, Campaign.Field.configured_status, Campaign.Field.objective, ]) cache[campaign_id] = campaign return cache.get(campaign_id)
def test_get_campaign_with_wrong_fields(self): with warnings.catch_warnings(record=True) as warning: self.mock_response.status_code = StatusCode.ERROR self.mock_request.return_value = self.mock_response fields = [ 'unexist_field', ] params = {} with self.assertRaises(FacebookRequestError): campaign = Campaign(TestValue.CAMPAIGN_ID).api_get( fields=fields, params=params, ) self.assertEqual(len(warning), 1) self.assertTrue(issubclass(warning[0].category, UserWarning))
def test_get_campaign_with_wrong_fields(self, mock_request): with warnings.catch_warnings( record=True) as warning, self.assertRaises( FacebookRequestError): self.mock_response.status_code = 400 self.mock_response._content = '{"error": {"message": "(#100) Tried accessing nonexisting field"}}' mock_request.return_value = self.mock_response fields = [ 'unexist_field', ] params = {} campaign = Campaign(self.campaign_id).api_get( fields=fields, params=params, ) assert len(warning) == 1 assert issubclass(warning[0].category, UserWarning)
def device(): today = datetime.date.today() fields1 = [ 'account_name', 'campaign_name', 'campaign_id', 'reach', 'cost_per_action_type:post_reaction', 'action:post_reaction', 'unique_actions:post_reaction', 'inline_link_clicks', 'action:post_engagement', 'unique_outbound_clicks:outbound_click', 'cost_per_action_type:post_engagement', 'ctr', 'cost_per_unique_click', 'action:landing_page_view', 'unique_actions:landing_page_view', 'action:offsite_conversion.custom.281094269070676', 'cost_per_action_type:page_engagement', 'cost_per_unique_action_type:page_engagement', 'device_platform', 'action:offsite_conversion.custom.280669215754025', 'cost_per_unique_action_type:link_click', 'website_ctr:link_click', 'cpc', 'unique_actions:link_click', 'unique_actions:page_engagement', 'date_stop', 'unique_inline_link_clicks', 'cost_per_action_type:link_click', 'inline_post_engagement', 'unique_inline_link_click_ctr', 'cost_per_unique_action_type:landing_page_view', 'unique_link_clicks_ctr', 'action:page_engagement', 'cost_per_inline_post_engagement', 'action:link_click', 'cost_per_outbound_click:outbound_click', 'unique_ctr', 'cost_per_action_type:offsite_conversion.custom.280669215754025', 'impressions', 'unique_actions:post_engagement', 'cost_per_unique_action_type:post_engagement', 'inline_link_click_ctr', 'cost_per_action_type:landing_page_view', 'cost_per_action_type:offsite_conversion.custom.281094269070676', 'clicks', 'cost_per_unique_inline_link_click', 'outbound_clicks:outbound_click', 'date_start', 'instant_experience_clicks_to_open', 'unique_clicks', 'cost_per_unique_outbound_click:outbound_click', 'frequency', 'instant_experience_outbound_clicks', 'outbound_clicks_ctr:outbound_click', 'unique_outbound_clicks_ctr:outbound_click', 'spend', 'cpp', 'instant_experience_clicks_to_start', 'cpm', 'objective', 'cost_per_inline_link_click' ] 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 }, 'breakdowns': ['device_platform'] } 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() #print(campaignids) list_d = [] l = [] y = 0 for i in range(len(campaignids)): #print("loop ran ", i) try: c_id = campaignids[i]["id"] campaign = Campaign(c_id) camp_insights = campaign.get_insights(fields=fields, params=params) j = 0 #print(camp_insights) dic_camp = {} for item in camp_insights: #converting to dictionary dic_camp = dict(item) #print("converted to dictionary") #print(dic_camp) #flattening of data 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 #print(dic_camp) list_d.append(dic_camp) except IndexError: continue if list_d: filename1 = "FacebookAds/landing_device/" + "device_" + date1 + ".csv" filename2 = "FacebookAds/processing_device/csv/" + year + "/" + month + "/" + "publisher_device_" + date1 + ".csv" importtos3.write_to_s3(list_d, fields1, 'paragon-datalake', filename1, filename2) return list_d
def get_data_from_api(start_date,end_date): Campaign_ID = [] Page_ID = [] Amount_Spent = [] # Page_Name = [] campaigns_all = {"Campaign_id":[], "Page_id":[], "Amount_spent":[], } page_id = None pixel_id = None access_token = 'EAAUbBhxccoEBALbQCDsVMLzwdZBZAZBXApZA0t1Qy3GtjZALfs89EMFhH62f5Kp7FWvshYRTrur41B14vICAgTf1TOba8qx7SBPejdqR4gZBqZCGDo0l0WvsmzubUKKqHncpyqhSpUqcO7O0WJsB1PnSZAMY7t7awukDuIYwrisTYwZDZD' bussiness_account_id = '1517651558352959' app_secret = '7a3ad485c97dbf45ee83562bc0dcb570' app_id = '1437087943127681' start_time = datetime.datetime.now() FacebookAdsApi.init(app_id, app_secret, access_token) business = Business(bussiness_account_id) # Get all ad accounts on the business account my_ad_account =business.get_owned_ad_accounts(fields=[AdAccount.Field.id]) # fields = [ # 'name', # 'objective', # # 'spend', # ] # params = { # 'time_range':{'since':start_date,'until':end_date}, # # 'date_preset':'yesterday', # 'effective_status': ['ACTIVE','PAUSED'], # } # Iterate through the adaccounts for account in my_ad_account: print(len(my_ad_account)) # i = 0 # Create an addaccount object from the adaccount id to make it possible to get insights tempaccount = AdAccount(account[AdAccount.Field.id]) # campaigns_iter = tempaccount.get_campaigns(fields = fields, params = params) # CAMPAIGN_UPDATE_BATCH_LIMIT = 5 # for campaigns in generate_batches(campaigns_iter,CAMPAIGN_UPDATE_BATCH_LIMIT): # api_batch = api.new_batch() # for i, campaign in enumerate(campaigns_iter): # adset = AdAccount(campaign[Campaign.Field.id]).get_ad_sets( # fields=['id', 'name', 'promoted_object'], # params = {}) # print(adset) # api_batch.execute() # spend_val.append(campaign[Campaign.Field.id]) # print(campaign, i) # print(spend_val) # print(set(spend_val)) # Grab insight info for all ads in the adaccount account_data = tempaccount.get_insights(params={ # 'time_increment':'1', 'time_range':{'since':start_date, 'until':end_date}, 'level':'campaign', }, fields=[ AdsInsights.Field.campaign_id, AdsInsights.Field.campaign_name, AdsInsights.Field.spend, ] ) for campaign in account_data: try: #Check if you reached 75% of the limit, if yes then back-off for 5 minutes (put this chunk in your 'for ad is ads' loop, every 100-200 iterations) # if (check_limit(bussiness_account_id,access_token)>75): # print('75% Rate Limit Reached. Cooling Time 5 Minutes.') # logging.debug('75% Rate Limit Reached. Cooling Time 5 Minutes.') # time.sleep(300) #ID OF Campaign # if campaign!=[]: # print(campaign) # print(len(account_data)) campaign_id = campaign[AdsInsights.Field.campaign_id] campaign_spent_val = campaign[AdsInsights.Field.spend] # print(campaign_spent_val) my_camp = Campaign(campaign_id) print(my_camp) #Campaign Insights Object # campaign_spent_obj = my_camp.get_insights(params={}, fields=[AdsInsights.Field.spend]) # campaign_spent = campaign_spent_obj[Campaign.Field.spend] # print(campaign_spent_obj) #Campaign Spend value # campaigns_all["Amount_spent"].append(campaign_spent_val) #AdSet Object adset = AdAccount(my_camp[Campaign.Field.id]).get_ad_sets( fields=['id', 'name', 'promoted_object'], params = {}) #page and Pixel ID from Adset if 'page_id' in adset[0][AdSet.Field.promoted_object]: page_id = adset[0][AdSet.Field.promoted_object][AdPromotedObject.Field.page_id] campaigns_all["Page_id"].append(page_id) Page_ID.append(page_id) # page_req = rq.head('https://facebook.com/'+page_id) # print(page_req.headers) # # for page in Page_ID: # print(Page(page_id).api_get(fields=['name'],params={})) elif 'pixel_id' in adset[0][AdSet.Field.promoted_object]: pixel_id = adset[0][AdSet.Field.promoted_object][AdPromotedObject.Field.pixel_id] campaigns_all["Page_id"].append(pixel_id) Page_ID.append(pixel_id) else: continue # Add Values to Dictionary campaigns_all["Campaign_id"].append(campaign_id) campaigns_all["Amount_spent"].append(campaign_spent_val) Campaign_ID.append(campaign_id) Amount_Spent.append(campaign_spent_val) # print(campaigns_all) time.sleep(2) except KeyError as e: print(e) continue except Exception as e: print(e) if FacebookRequestError.api_error_code(e) == 17: print(campaigns_all) print("Limit Reached") print("Wait 5 minutes for cooldown") time.sleep(300) continue finally: end_time = datetime.datetime.now() diff = end_time - start_time print(diff) tuples_of_data = list(zip(Campaign_ID,Page_ID,Amount_Spent)) sum_amount = compare_values(tuples_of_data) print(sum_amount) # print(diff.total_seconds()) return campaigns_all,sum_amount
# 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.campaign import Campaign from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<ACTIVITY_ID>' FacebookAdsApi.init(access_token=access_token) fields = [ 'time_created', ] params = { } print Campaign(id).get( fields=fields, params=params, )
logger.Logger( "Dynamic Ads API CRON", "Dynamic Ads API is used to modify AdSets according to relevant data pulled" ).runtimelog() facebookmodule.FacebookSDKInit().runtimeSDK() data = accounts.Accounts( "https://portal.synlighet.no/fb/accounts/").runtimeaccount() for cu_data in data: act_cid = "act_" + cu_data['cid'] print("Account: ", act_cid) if "season" in cu_data['services']: print("found api") campaign = Campaign(parent_id=act_cid) campaign[Campaign.Field.name] = 'TEST - Product Catalog Sales Campaign' objective = Campaign.Objective.product_catalog_sales campaign[Campaign.Field.objective] = 'LINK_CLICKS' campaign.remote_create(params={ 'status': Campaign.Status.paused, }) print(campaign[Campaign.Field.id]) # temp_campaign = Campaign(i["id"]) # adsets = temp_campaign.adset( adset = AdSet(parent_id=act_cid) adset[AdSet.Field.name] = 'Product Catalog Sales Adset' adset[AdSet.Field.bid_amount] = 30
def test_get_campaign(self): with warnings.catch_warnings(record=True) as warning: self.mock_response.status_code = StatusCode.SUCCESS self.mock_response._content = str.encode( '{' '"' + str(FieldName.ACCOUNT_ID) + '":"' + str(TestValue.ACCOUNT_ID) + '",' '"' + str(FieldName.ADLABELS) + '":' + str(TestValue.AD_LABEL) + ',' '"' + str(FieldName.BID_STRATEGY) + '":"' + str(TestValue.BID_STRATEGY) + '",' '"' + str(FieldName.BOOSTED_OBJECT_ID) + '":"' + str(TestValue.BOOSTED_OBJECT_ID) + '",' '"' + str(FieldName.BRAND_LIFT_STUDIES) + '":' + str(TestValue.BRAND_LIFT_STUDIES) + ',' '"' + str(FieldName.BUDGET_REBALANCE_FLAG) + '":"' + str(TestValue.BUDGET_REBALANCE_FLAG) + '",' '"' + str(FieldName.BUDGET_REMAINING) + '": "' + str(TestValue.BUDGET_REMAINING) + '",' '"' + str(FieldName.BUYING_TYPE) + '":"' + str(TestValue.BUYING_TYPE) + '",' '"' + str(FieldName.CAN_CREATE_BRAND_LIFT_STUDY) + '":"' + str(TestValue.CAN_CREATE_BRAND_LIFT_STUDY) + '",' '"' + str(FieldName.CAN_USE_SPEND_CAP) + '":"' + str(TestValue.CAN_USE_SPEND_CAP) + '",' '"' + str(FieldName.CONFIGURED_STATUS) + '":"' + str(TestValue.CONFIGURED_STATUS) + '",' '"' + str(FieldName.CREATED_TIME) + '":"' + str(TestValue.CREATED_TIME) + '",' '"' + str(FieldName.DAILY_BUDGET) + '":"' + str(TestValue.DAILY_BUDGET) + '",' '"' + str(FieldName.EFFECTIVE_STATUS) + '":"' + str(TestValue.EFFECTIVE_STATUS) + '",' '"' + str(FieldName.ID) + '": "' + str(TestValue.CAMPAIGN_ID) + '",' '"' + str(FieldName.ISSUES_INFO) + '": ' + str(TestValue.ISSUES_INFO) + ',' '"' + str(FieldName.LAST_BUDGET_TOGGLING_TIME) + '":"' + str(TestValue.LAST_BUDGET_TOGGLING_TIME) + '",' '"' + str(FieldName.LIFETIME_BUDGET) + '":"' + str(TestValue.LIFETIME_BUDGET) + '",' '"' + str(FieldName.NAME) + '":"' + str(TestValue.NAME) + '",' '"' + str(FieldName.OBJECTIVE) + '":"' + str(TestValue.OBJECTIVE) + '",' '"' + str(FieldName.RECOMMENDATIONS) + '":' + str(TestValue.RECOMMENDATIONS) + ',' '"' + str(FieldName.PACING_TYPE) + '":"' + str(TestValue.PACING_TYPE) + '",' '"' + str(FieldName.PROMOTED_OBJECT) + '":' + str(TestValue.PROMOTED_OBJECT) + ',' '"' + str(FieldName.SPECIAL_AD_CATEGORY) + '":"' + str(TestValue.SPECIAL_AD_CATEGORY) + '",' '"' + str(FieldName.SPEND_CAP) + '":"' + str(TestValue.SPEND_CAP) + '",' '"' + str(FieldName.STATUS) + '":"' + str(TestValue.STATUS) + '",' '"' + str(FieldName.TOPLINE_ID) + '":"' + str(TestValue.TOPLINE_ID) + '",' '"' + str(FieldName.START_TIME) + '":"' + str(TestValue.START_TIME) + '",' '"' + str(FieldName.STOP_TIME) + '":"' + str(TestValue.STOP_TIME) + '",' '"' + str(FieldName.UPDATED_TIME) + '":"' + str(TestValue.UPDATED_TIME) + '"' '}') self.mock_request.return_value = self.mock_response fields = [ FieldName.ACCOUNT_ID, FieldName.ADLABELS, FieldName.BID_STRATEGY, FieldName.BOOSTED_OBJECT_ID, FieldName.BRAND_LIFT_STUDIES, FieldName.BUDGET_REBALANCE_FLAG, FieldName.BUDGET_REMAINING, FieldName.BUYING_TYPE, FieldName.CAN_CREATE_BRAND_LIFT_STUDY, FieldName.CAN_USE_SPEND_CAP, FieldName.CONFIGURED_STATUS, FieldName.CREATED_TIME, FieldName.DAILY_BUDGET, FieldName.EFFECTIVE_STATUS, FieldName.ID, FieldName.ISSUES_INFO, FieldName.LAST_BUDGET_TOGGLING_TIME, FieldName.LIFETIME_BUDGET, FieldName.NAME, FieldName.OBJECTIVE, FieldName.PACING_TYPE, FieldName.PROMOTED_OBJECT, FieldName.RECOMMENDATIONS, FieldName.SPECIAL_AD_CATEGORY, FieldName.SPEND_CAP, FieldName.START_TIME, FieldName.STATUS, FieldName.STOP_TIME, FieldName.TOPLINE_ID, FieldName.UPDATED_TIME, ] params = {} campaign = Campaign(TestValue.CAMPAIGN_ID).api_get( fields=fields, params=params, ) self.assertEqual(len(warning), 0) self.assertTrue(isinstance(campaign, Campaign)) self.assertEqual(campaign[FieldName.ACCOUNT_ID], TestValue.ACCOUNT_ID) self.assertEqual(campaign[FieldName.ADLABELS], [json.loads(TestValue.AD_LABEL)]) self.assertEqual(campaign[FieldName.BID_STRATEGY], TestValue.BID_STRATEGY) self.assertEqual(campaign[FieldName.BOOSTED_OBJECT_ID], TestValue.BOOSTED_OBJECT_ID) self.assertEqual(campaign[FieldName.BRAND_LIFT_STUDIES], [json.loads(TestValue.BRAND_LIFT_STUDIES)]) self.assertEqual(campaign[FieldName.BUDGET_REBALANCE_FLAG], TestValue.BUDGET_REBALANCE_FLAG) self.assertEqual(campaign[FieldName.BUDGET_REMAINING], TestValue.BUDGET_REMAINING) self.assertEqual(campaign[FieldName.BUYING_TYPE], TestValue.BUYING_TYPE) self.assertEqual(campaign[FieldName.CAN_CREATE_BRAND_LIFT_STUDY], TestValue.CAN_CREATE_BRAND_LIFT_STUDY) self.assertEqual(campaign[FieldName.CAN_USE_SPEND_CAP], TestValue.CAN_USE_SPEND_CAP) self.assertEqual(campaign[FieldName.CONFIGURED_STATUS], TestValue.CONFIGURED_STATUS) self.assertEqual(campaign[FieldName.CREATED_TIME], TestValue.CREATED_TIME) self.assertEqual(campaign[FieldName.DAILY_BUDGET], TestValue.DAILY_BUDGET) self.assertEqual(campaign[FieldName.EFFECTIVE_STATUS], TestValue.EFFECTIVE_STATUS) self.assertEqual(campaign[FieldName.ID], TestValue.CAMPAIGN_ID) self.assertEqual(campaign[FieldName.ISSUES_INFO], [json.loads(TestValue.ISSUES_INFO)]) self.assertEqual(campaign[FieldName.LAST_BUDGET_TOGGLING_TIME], TestValue.LAST_BUDGET_TOGGLING_TIME) self.assertEqual(campaign[FieldName.LIFETIME_BUDGET], TestValue.LIFETIME_BUDGET) self.assertEqual(campaign[FieldName.NAME], TestValue.NAME) self.assertEqual(campaign[FieldName.OBJECTIVE], TestValue.OBJECTIVE) self.assertEqual(campaign[FieldName.PACING_TYPE], [TestValue.PACING_TYPE]) self.assertTrue( isinstance(campaign[FieldName.PROMOTED_OBJECT], AdPromotedObject)) self.assertEqual(campaign[FieldName.RECOMMENDATIONS], [json.loads(TestValue.RECOMMENDATIONS)]) self.assertEqual(campaign[FieldName.SPECIAL_AD_CATEGORY], TestValue.SPECIAL_AD_CATEGORY) self.assertEqual(campaign[FieldName.SPEND_CAP], TestValue.SPEND_CAP) self.assertEqual(campaign[FieldName.STATUS], TestValue.STATUS) self.assertEqual(campaign[FieldName.START_TIME], TestValue.START_TIME) self.assertEqual(campaign[FieldName.STOP_TIME], TestValue.STOP_TIME) self.assertEqual(campaign[FieldName.TOPLINE_ID], TestValue.TOPLINE_ID) self.assertEqual(campaign[FieldName.UPDATED_TIME], TestValue.UPDATED_TIME)
from facebook_business.api import FacebookAdsApi from facebook_business.adobjects.campaign import Campaign import sys from env import ACCESS_TOKEN, CAMPAIGN_ID FacebookAdsApi.init(access_token=ACCESS_TOKEN) campaign = Campaign(fbid=CAMPAIGN_ID) ad_sets = campaign.get_ad_sets(fields=['name']) since = sys.argv[1] if len(sys.argv) > 1 else '2017-05-10' until = sys.argv[2] if len(sys.argv) > 2 else '2019-04-18' metric = sys.argv[3] if len(sys.argv) > 3 else 'link_click' def find_cost_per_action_type(action_type, list): for entry in list: if metric == entry['action_type']: return float(entry['value']) return None def get_insights(ad_set, action_type): insight_list = ad_set.get_insights( fields=['cost_per_action_type'], params={'time_range': { 'since': since,
def getadset(request): if request.method == 'GET': access_token=request.headers['token'] campaignId = request.GET.get('campaignId') app_secret = 'db4b3037cd105cfd23b6032aecd2c3ff' app_id = '263805807945856' id = 'act_2770121319724389' CAMPAIGN_ID = campaignId FacebookAdsApi.init(access_token=access_token) fields = ['name','start_time','end_time','targeting'] data1=[] params = {} ads= Campaign(CAMPAIGN_ID).get_ad_sets( fields=fields, params=params, ) for i in ads: orginalid=i['id'] start_time=i['start_time'] end_time=i['end_time'] targetings=i['targeting'] print(orginalid) try: print('---------------exit') gets=AdsetOrignal.objects.filter(id=orginalid) print('>>>>>>>>',gets) if list(gets) != []: gets = gets[0] #updte data in database AdsetOrignal.objects.filter(id=orginalid).update(start_time=start_time,end_time=end_time) else: print('not in db') except AdsetOrignal.DoesNotExist: AdsetOrignal.objects.create(id=orginalid,start_time=start_time,end_time=end_time,targeting=targetings) print('---------------------not exit') data={ 'id':i['id'], 'name':i['name'], 'start_time':i['start_time'], 'end_time':i['end_time'], 'targeting':i['targeting'], } data1.append(data) today = datetime.now(tz=utc) #end date then update adset orginal locations print('----------------today',today) for i in data1: ids=i['id'] orignallocation= AdsetOrignal.objects.filter(id=ids) adsts=Adset.objects.filter(id=ids) for i in adsts: end_times=i.end_time print('end_times-----',end_times) if end_times<= today: for orignallo in orignallocation: targeting=orignallo.targeting fields = ['targeting'] params = {'targeting':targeting} # print(params) AdSet(ids).api_update(fields=fields,params=params,) print('change orignal location adset',ids) Adset.objects.filter(id=ids).delete() else: print('end date is greter today date') #end code enddate update addset location # updte add set locaions usegin start date time for i in data1: ids=i['id'] adsts=Adset.objects.filter(id=ids) for i in adsts: start_times=i.start_time targeting=i.targeting print('start_time-----',start_times) if start_times <= today: fields = ['targeting'] params = targeting print(params) AdSet(ids).api_update(fields=fields,params=params,) print('updte location adset',ids) else: print('start_time is greter today date') #end code update adset return Response(data1) else: return HttpResponse('not found')
def create_lookalike_ads( self, account_id, name, tiered_lookalikes, optimization_goal, billing_event, tiered_bid_amounts, title, body, url, image_path, daily_budget=None, lifetime_budget=None, start_time=None, end_time=None, campaign=None, ): """ Take the tiered lookalike audiences and create the ads """ results = { 'adsets': [], 'ads': [], } tiers = len(tiered_lookalikes) if tiers != len(tiered_bid_amounts): raise TypeError('Audience and bid amount number mismatch.') # Create campaign if not campaign: campaign = Campaign(parent_id=account_id) campaign[Campaign.Field.name] = '{} Campaign'.format(name) campaign[Campaign.Field.objective] = \ Campaign.Objective.link_clicks campaign.remote_create(params={ 'status': Campaign.Status.paused, }) # Upload image img = AdImage(parent_id=account_id) img[AdImage.Field.filename] = image_path img.remote_create() image_hash = img.get_hash() # Inline creative for ads inline_creative = { AdCreative.Field.title: title, AdCreative.Field.body: body, AdCreative.Field.object_url: url, AdCreative.Field.image_hash: image_hash, } for tier in range(1, tiers + 1): # Create ad set ad_set = AdSet(parent_id=account_id) ad_set[AdSet.Field.campaign_id] = campaign.get_id_assured() ad_set[AdSet.Field.name] = '{0} AdSet tier {1}'.format(name, tier) ad_set[AdSet.Field.optimization_goal] = optimization_goal ad_set[AdSet.Field.billing_event] = billing_event ad_set[AdSet.Field.bid_amount] = tiered_bid_amounts[tier - 1] if daily_budget: ad_set[AdSet.Field.daily_budget] = daily_budget else: ad_set[AdSet.Field.lifetime_budget] = lifetime_budget if end_time: ad_set[AdSet.Field.end_time] = end_time if start_time: ad_set[AdSet.Field.start_time] = start_time audience = tiered_lookalikes[tier - 1] targeting = { Targeting.Field.custom_audiences: [{ 'id': audience[CustomAudience.Field.id], 'name': audience[CustomAudience.Field.name], }] } ad_set[AdSet.Field.targeting] = targeting ad_set.remote_create(params={ 'status': AdSet.Status.paused, }) # Create ad ad = Ad(parent_id=account_id) ad[Ad.Field.name] = '{0} Ad tier {1}'.format(name, tier) ad[Ad.Field.adset_id] = ad_set['id'] ad[Ad.Field.creative] = inline_creative ad.remote_create(params={ 'status': Ad.Status.paused, }) results['adsets'].append(ad_set) results['ads'].append(ad) return results