Пример #1
0
def list_campaigns():
    FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
    my_account = AdAccount(f'act_{ad_account}')
    fields = [
        'account_id',
        'budget_rebalance_flag',
        'budget_remaining',
        'buying_type',
        'can_create_brand_lift_study',
        'can_use_spend_cap',
        'configured_status',
        'created_time',
        'effective_status',
        'id',
        'name',
        'objective',
        'recommendations',
        'source_campaign',
        'source_campaign_id',
        'spend_cap',
        'start_time',
        'status',
        'updated_time',
    ]
    return my_account.get_campaigns(fields=fields)
Пример #2
0
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)
Пример #3
0
def get_campaign_data(ad_account: adaccount.AdAccount) -> {}:
    """Retrieves the campaign data of the ad account as a dictionary

    Args:
        ad_account: An ad account for which to retrieve the campaign data

    Returns:
        A dictionary with {campaign_id: {'name': 1, 'attributes': {}}} format

    """
    logging.info('get campaign data for account {}'.format(
        ad_account['account_id']))
    campaigns = ad_account.get_campaigns(fields=['id', 'name', 'adlabels'],
                                         params={
                                             'limit':
                                             1000,
                                             'status':
                                             ['ACTIVE', 'PAUSED', 'ARCHIVED']
                                         })
    result = {}

    for campaign in campaigns:
        result[campaign['id']] = {
            'name': campaign['name'],
            'attributes': parse_labels(campaign.get('adlabels', []))
        }
    return result
Пример #4
0
def get_campaign(account_ids):
    my_account = AdAccount(account_ids)
    campaigns = my_account.get_campaigns()
    params = {'fields': [Campaign.Field.id, Campaign.Field.name]}
    for campaign in campaigns:
        print(campaign)
        campaigns = campaign.api_get(fields=params.get('fields'),
                                     params=params)
        campaign_name = campaigns.get('name')
        campaign_id = campaigns.get('id')
        return {'campaign_ids': campaign_id, 'campaign_name': campaign_name}
def FB_data_request(my_app_id, my_app_secret, my_access_token,Accounts,start_date,end_date):
    FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
    
    fields = ['account_id','account_name','campaign_id','campaign_name','clicks','date_start','frequency','impressions','reach','spend']
    params = {'time_range':{'since': start_date,'until': end_date},'time_increment':'1'}
    FB_df=pd.DataFrame()
    account_id=[]
    account_name=[]
    campaign_id=[]
    campaign_name=[]
    clicks=[]
    date_start=[]
    frequency=[]
    impressions=[]
    
    reach=[]
    spend=[]
    for account in Accounts:
        my_account = AdAccount('act_'+account)
        campaigns = my_account.get_campaigns()._queue
        
        print(len(campaigns))
        for campaign in campaigns:
            print(campaign.get_id())
            
            #print(campaign)
            campinsights=campaign.get_insights(fields=fields,params=params)
            #print(campaign.get('full_view_reach'))
            print(len(campinsights))
            for inscampaign in campinsights:
                account_id.append(inscampaign['account_id'])
                account_name.append(inscampaign['account_name'])
                campaign_id.append(inscampaign['campaign_id'])
                campaign_name.append(inscampaign['campaign_name'])
                clicks.append(inscampaign['clicks'])
                date_start.append(inscampaign['date_start'])
                frequency.append(inscampaign['frequency'])
                impressions.append(inscampaign['impressions'])
                reach.append(inscampaign['reach'])
                spend.append(inscampaign['spend'])
    FB_df['Account Id']= account_id
    FB_df['Account Name']= account_name
    FB_df['Campaign Id']= campaign_id
    FB_df['Campaign Name']= campaign_name
    FB_df['Clicks']= clicks
    FB_df['Date']= date_start
    FB_df['Frequency']= frequency
    FB_df['Impressions']= impressions
    FB_df['Reach']= reach
    FB_df['Spend']= spend
    
    #FB_df.to_csv('example.csv')
    print(FB_df.head())
    return(FB_df)
Пример #6
0
def getCampaign():
    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 = ['id', 'name', 'objective']
    account = AdAccount(dict1['account_id'])
    campaigns = account.get_campaigns(fields=fields)
    for i in campaigns:
        if i['id'] == '120330000453089803':
            print(i)
Пример #7
0
 def run_query_on_fb_account_obj_conf(self, params, ad_object_id):
     if ad_object_id.startswith("act_"):
         raise ClickException(
             "Wrong format. Account ID should only contains digits")
     account = AdAccount("act_" + ad_object_id)
     campaigns = account.get_campaigns()
     for el in chain(*[
             self.run_query_on_fb_campaign_obj_conf(params,
                                                    campaign.get("id"))
             for campaign in campaigns
     ]):
         yield el
Пример #8
0
def get_request(account_id, table, params, fields):
    """account_id: unique id for ad account in format act_<ID>
    table: The table object found in the models module
    params: dictionary of parameters for request
    fields: list of fields for request
    --> returns requested data from Facebook Marketing API
    """
    my_account = AdAccount(account_id)
    if table == 'accounts':
        cursor = my_account.api_get(params=params, fields=fields)
        return dict(cursor)
    if table == 'campaigns':
        cursor = my_account.get_campaigns(params=params, fields=fields)
        request = [campaign for campaign in cursor]
        return request
    if table == 'adsets':
        request = my_account.get_ad_sets(params=params, fields=fields)
        return request
    if table == 'ads_insights':
        cursor = my_account.get_insights_async(params=params, fields=fields)
        cursor.api_get()
        while cursor[AdReportRun.Field.async_status] != "Job Completed":
            time.sleep(1)
            cursor.api_get()
            time.sleep(1)
        request = cursor.get_result(params={"limit": 1000})
        return request
    if table == 'ads_insights_age_and_gender':
        cursor = my_account.get_insights_async(params=params, fields=fields)
        cursor.api_get()
        while cursor[AdReportRun.Field.async_status] != "Job Completed":
            time.sleep(1)
            cursor.api_get()
            time.sleep(1)
        request = cursor.get_result(params={"limit": 1000})
        return request
    if table == 'ads_insights_region':
        cursor = my_account.get_insights_async(params=params, fields=fields)
        cursor.api_get()
        while cursor[AdReportRun.Field.async_status] != "Job Completed":
            time.sleep(1)
            cursor.api_get()
            time.sleep(1)
        request = cursor.get_result(params={"limit": 1000})
        return request
Пример #9
0
class FbApi(object):
    def __init__(self, config_file=None):
        self.config_file = config_file
        self.df = pd.DataFrame()
        self.config = None
        self.account = None
        self.campaign = None
        self.app_id = None
        self.app_secret = None
        self.access_token = None
        self.act_id = None
        self.config_list = []
        self.date_lists = None
        self.field_lists = None
        self.adset_dict = None
        self.cam_dict = None
        self.ad_dict = None
        self.pixel = None
        if self.config_file:
            self.input_config(self.config_file)

    def input_config(self, config_file):
        logging.info('Loading Facebook config file: ' + str(config_file))
        self.config_file = os.path.join(config_path, config_file)
        self.load_config()
        self.check_config()
        FacebookAdsApi.init(self.app_id, self.app_secret, self.access_token)
        self.account = AdAccount(self.config['act_id'])

    def load_config(self):
        try:
            with open(self.config_file, 'r') as f:
                self.config = json.load(f)
        except IOError:
            logging.error(self.config_file + ' not found.  Aborting.')
            sys.exit(0)
        self.app_id = self.config['app_id']
        self.app_secret = self.config['app_secret']
        self.access_token = self.config['access_token']
        self.act_id = self.config['act_id']
        self.config_list = [
            self.app_id, self.app_secret, self.access_token, self.act_id
        ]

    def check_config(self):
        for item in self.config_list:
            if item == '':
                logging.warning(item + 'not in FB config file.  Aborting.')
                sys.exit(0)

    def set_id_name_dict(self, fb_object):
        if fb_object == Campaign:
            fields = ['id', 'name']
            self.cam_dict = list(self.account.get_campaigns(fields=fields))
        elif fb_object == AdSet:
            fields = ['id', 'name', 'campaign_id']
            self.adset_dict = list(self.account.get_ad_sets(fields=fields))
        elif fb_object == Ad:
            fields = ['id', 'name', 'campaign_id', 'adset_id']
            self.ad_dict = list(self.account.get_ads(fields=fields))

    def campaign_to_id(self, campaigns):
        if not self.cam_dict:
            self.set_id_name_dict(Campaign)
        cids = [x['id'] for x in self.cam_dict if x['name'] in campaigns]
        return cids

    def adset_to_id(self, adsets, cids):
        as_and_cam = list(itertools.product(adsets, cids))
        if not self.adset_dict:
            self.set_id_name_dict(AdSet)
        asids = [
            tuple([x['id'], x['campaign_id']]) for x in self.adset_dict
            if tuple([x['name'], x['campaign_id']]) in as_and_cam
        ]
        return asids

    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()

    @staticmethod
    def geo_target_search(geos):
        all_geos = []
        for geo in geos:
            params = {
                'q': geo,
                'type': 'adgeolocation',
                'location_types': [Targeting.Field.country],
            }
            resp = TargetingSearch.search(params=params)
            all_geos.extend(resp)
        return all_geos

    @staticmethod
    def target_search(targets_to_search):
        all_targets = []
        for target in targets_to_search[1]:
            params = {
                'q': target,
                'type': 'adinterest',
            }
            resp = TargetingSearch.search(params=params)
            if not resp:
                logging.warning(target + ' not found in targeting search.  ' +
                                'It was not added to the adset.')
                continue
            if targets_to_search[0] == 'interest':
                resp = [resp[0]]
            new_tar = [dict((k, x[k]) for k in ('id', 'name')) for x in resp]
            all_targets.extend(new_tar)
        return all_targets

    @staticmethod
    def get_matching_saved_audiences(audiences):
        aud_list = []
        for audience in audiences:
            audience = CustomAudience(audience)
            val_aud = audience.remote_read(fields=['targeting'])
            aud_list.append(val_aud)
            aud_list = aud_list[0]['targeting']
        return aud_list

    def get_matching_custom_audiences(self, audiences):
        act_auds = self.account.get_custom_audiences(
            fields=[CustomAudience.Field.name, CustomAudience.Field.id])
        audiences = [{
            'id': x['id'],
            'name': x['name']
        } for x in act_auds if x['id'] in audiences]
        return audiences

    def set_target(self, geos, targets, age_min, age_max, gender, device,
                   publisher_platform, facebook_positions):
        targeting = {}
        if geos and geos != ['']:
            targeting[Targeting.Field.geo_locations] = {
                Targeting.Field.countries: geos
            }
        if age_min:
            targeting[Targeting.Field.age_min] = age_min
        if age_max:
            targeting[Targeting.Field.age_max] = age_max
        if gender:
            targeting[Targeting.Field.genders] = gender
        if device and device != ['']:
            targeting[Targeting.Field.device_platforms] = device
        if publisher_platform and publisher_platform != ['']:
            targeting[Targeting.Field.publisher_platforms] = publisher_platform
        if facebook_positions and facebook_positions != ['']:
            targeting[Targeting.Field.facebook_positions] = facebook_positions
        for target in targets:
            if target[0] == 'interest' or target[0] == 'interest-broad':
                int_targets = self.target_search(target)
                targeting[Targeting.Field.interests] = int_targets
            if target[0] == 'savedaudience':
                aud_target = self.get_matching_saved_audiences(target[1])
                targeting.update(aud_target)
            if target[0] == 'customaudience':
                aud_target = self.get_matching_custom_audiences(target[1])
                targeting[Targeting.Field.custom_audiences] = aud_target
        return targeting

    def create_adset(self, adset_name, cids, opt_goal, bud_type, bud_val,
                     bill_evt, bid_amt, status, start_time, end_time, prom_obj,
                     country, target, age_min, age_max, genders, device, pubs,
                     pos):
        if not self.adset_dict:
            self.set_id_name_dict(AdSet)
        for cid in cids:
            if adset_name in ([
                    x['name'] for x in self.adset_dict
                    if x['campaign_id'] == cid
            ]):
                logging.warning(adset_name + ' already in campaign.  This ' +
                                'ad set was not uploaded.')
                continue
            targeting = self.set_target(country, target, age_min, age_max,
                                        genders, device, pubs, pos)
            params = {
                AdSet.Field.name: adset_name,
                AdSet.Field.campaign_id: cid,
                AdSet.Field.billing_event: bill_evt,
                AdSet.Field.status: status,
                AdSet.Field.targeting: targeting,
                AdSet.Field.start_time: start_time,
                AdSet.Field.end_time: end_time,
            }
            if bid_amt == '':
                params['bid_strategy'] = 'LOWEST_COST_WITHOUT_CAP'
            else:
                params[AdSet.Field.bid_amount] = int(bid_amt)
            if opt_goal in [
                    'CONTENT_VIEW', 'SEARCH', 'ADD_TO_CART', 'ADD_TO_WISHLIST',
                    'INITIATED_CHECKOUT', 'ADD_PAYMENT_INFO', 'PURCHASE',
                    'LEAD', 'COMPLETE_REGISTRATION'
            ]:
                if not self.pixel:
                    pixel = self.account.get_ads_pixels()
                    self.pixel = pixel[0]['id']
                params[AdSet.Field.promoted_object] = {
                    'pixel_id': self.pixel,
                    'custom_event_type': opt_goal,
                    'page_id': prom_obj
                }
            elif 'APP_INSTALLS' in opt_goal:
                opt_goal = opt_goal.split('|')
                params[AdSet.Field.promoted_object] = {
                    'application_id': opt_goal[1],
                    'object_store_url': opt_goal[2],
                }
            else:
                params[AdSet.Field.optimization_goal] = opt_goal
                params[AdSet.Field.promoted_object] = {'page_id': prom_obj}
            if bud_type == 'daily':
                params[AdSet.Field.daily_budget] = int(bud_val)
            elif bud_type == 'lifetime':
                params[AdSet.Field.lifetime_budget] = int(bud_val)
            self.account.create_ad_set(params=params)

    def upload_creative(self, creative_class, image_path):
        cre = creative_class(parent_id=self.account.get_id_assured())
        if creative_class == AdImage:
            cre[AdImage.Field.filename] = image_path
            cre.remote_create()
            creative_hash = cre.get_hash()
        elif creative_class == AdVideo:
            cre[AdVideo.Field.filepath] = image_path
            cre.remote_create()
            creative_hash = cre.get_id()
        else:
            creative_hash = None
        return creative_hash

    def get_all_thumbnails(self, vid):
        video = AdVideo(vid)
        thumbnails = video.get_thumbnails()
        if not thumbnails:
            logging.warning('Could not retrieve thumbnail for vid: ' +
                            str(vid) + '.  Retrying in 120s.')
            time.sleep(120)
            thumbnails = self.get_all_thumbnails(vid)
        return thumbnails

    def get_video_thumbnail(self, vid):
        thumbnails = self.get_all_thumbnails(vid)
        thumbnail = [x for x in thumbnails if x['is_preferred'] is True]
        if not thumbnail:
            thumbnail = thumbnails[1]
        else:
            thumbnail = thumbnail[0]
        thumb_url = thumbnail['uri']
        return thumb_url

    @staticmethod
    def request_error(e):
        if e._api_error_code == 2:
            logging.warning(
                'Retrying as the call resulted in the following: ' + str(e))
        else:
            logging.error('Retrying in 120 seconds as the Facebook API call'
                          'resulted in the following error: ' + str(e))
            time.sleep(120)

    def create_ad(self,
                  ad_name,
                  asids,
                  title,
                  body,
                  desc,
                  cta,
                  durl,
                  url,
                  prom_obj,
                  ig_id,
                  view_tag,
                  ad_status,
                  creative_hash=None,
                  vid_id=None):
        if not self.ad_dict:
            self.set_id_name_dict(Ad)
        for asid in asids:
            if ad_name in [
                    x['name'] for x in self.ad_dict
                    if x['campaign_id'] == asid[1] and x['adset_id'] == asid[0]
            ]:
                logging.warning(ad_name + ' already in campaign/adset. ' +
                                'This ad was not uploaded.')
                continue
            if vid_id:
                params = self.get_video_ad_params(ad_name, asid, title, body,
                                                  desc, cta, url, prom_obj,
                                                  ig_id, creative_hash, vid_id,
                                                  view_tag, ad_status)
            elif isinstance(creative_hash, list):
                params = self.get_carousel_ad_params(ad_name, asid, title,
                                                     body, desc, cta, durl,
                                                     url, prom_obj, ig_id,
                                                     creative_hash, view_tag,
                                                     ad_status)
            else:
                params = self.get_link_ad_params(ad_name, asid, title, body,
                                                 desc, cta, durl, url,
                                                 prom_obj, ig_id,
                                                 creative_hash, view_tag,
                                                 ad_status)
            for attempt_number in range(100):
                try:
                    self.account.create_ad(params=params)
                    break
                except FacebookRequestError as e:
                    self.request_error(e)

    def get_video_ad_params(self, ad_name, asid, title, body, desc, cta, url,
                            prom_obj, ig_id, creative_hash, vid_id, view_tag,
                            ad_status):
        data = self.get_video_ad_data(vid_id, body, title, desc, cta, url,
                                      creative_hash)
        story = {
            AdCreativeObjectStorySpec.Field.page_id: str(prom_obj),
            AdCreativeObjectStorySpec.Field.video_data: data
        }
        if ig_id and str(ig_id) != 'nan':
            story[AdCreativeObjectStorySpec.Field.instagram_actor_id] = ig_id
        creative = {AdCreative.Field.object_story_spec: story}
        params = {
            Ad.Field.name: ad_name,
            Ad.Field.status: ad_status,
            Ad.Field.adset_id: asid[0],
            Ad.Field.creative: creative
        }
        if view_tag and str(view_tag) != 'nan':
            params['view_tags'] = [view_tag]
        return params

    def get_link_ad_params(self, ad_name, asid, title, body, desc, cta, durl,
                           url, prom_obj, ig_id, creative_hash, view_tag,
                           ad_status):
        data = self.get_link_ad_data(body, creative_hash, durl, desc, url,
                                     title, cta)
        story = {
            AdCreativeObjectStorySpec.Field.page_id: str(prom_obj),
            AdCreativeObjectStorySpec.Field.link_data: data
        }
        if ig_id and str(ig_id) != 'nan':
            story[AdCreativeObjectStorySpec.Field.instagram_actor_id] = ig_id
        creative = {AdCreative.Field.object_story_spec: story}
        params = {
            Ad.Field.name: ad_name,
            Ad.Field.status: ad_status,
            Ad.Field.adset_id: asid[0],
            Ad.Field.creative: creative
        }
        if view_tag and str(view_tag) != 'nan':
            params['view_tags'] = [view_tag]
        return params

    @staticmethod
    def get_video_ad_data(vid_id, body, title, desc, cta, url, creative_hash):
        data = {
            AdCreativeVideoData.Field.video_id: vid_id,
            AdCreativeVideoData.Field.message: body,
            AdCreativeVideoData.Field.title: title,
            AdCreativeVideoData.Field.link_description: desc,
            AdCreativeVideoData.Field.call_to_action: {
                'type': cta,
                'value': {
                    'link': url,
                },
            },
        }
        if creative_hash[:4] == 'http':
            data[AdCreativeVideoData.Field.image_url] = creative_hash
        else:
            data[AdCreativeVideoData.Field.image_hash] = creative_hash
        return data

    @staticmethod
    def get_link_ad_data(body, creative_hash, durl, desc, url, title, cta):
        data = {
            AdCreativeLinkData.Field.message: body,
            AdCreativeLinkData.Field.image_hash: creative_hash,
            AdCreativeLinkData.Field.caption: durl,
            AdCreativeLinkData.Field.description: desc,
            AdCreativeLinkData.Field.link: url,
            AdCreativeLinkData.Field.name: title,
            AdCreativeLinkData.Field.call_to_action: {
                'type': cta,
                'value': {
                    'link': url,
                },
            },
        }
        return data

    @staticmethod
    def get_carousel_ad_data(creative_hash,
                             desc,
                             url,
                             title,
                             cta,
                             vid_id=None):
        data = {
            AdCreativeLinkData.Field.description: desc,
            AdCreativeLinkData.Field.link: url,
            AdCreativeLinkData.Field.name: title,
            AdCreativeLinkData.Field.call_to_action: {
                'type': cta,
                'value': {
                    'link': url,
                },
            },
        }
        if creative_hash[:4] == 'http':
            data['picture'] = creative_hash
        else:
            data[AdCreativeVideoData.Field.image_hash] = creative_hash
        if vid_id:
            data[AdCreativeVideoData.Field.video_id] = vid_id
        return data

    @staticmethod
    def get_individual_carousel_param(param_list, idx):
        if idx < len(param_list):
            param = param_list[idx]
        else:
            logging.warning('{} does not have index {}.  Using last available.'
                            ''.format(param_list, idx))
            param = param_list[-1]
        return param

    def get_carousel_ad_params(self, ad_name, asid, title, body, desc, cta,
                               durl, url, prom_obj, ig_id, creative_hash,
                               view_tag, ad_status):
        data = []
        for idx, creative in enumerate(creative_hash):
            current_description = self.get_individual_carousel_param(desc, idx)
            current_url = self.get_individual_carousel_param(url, idx)
            current_title = self.get_individual_carousel_param(title, idx)
            if len(creative) == 1:
                data_ind = self.get_carousel_ad_data(creative_hash=creative[0],
                                                     desc=current_description,
                                                     url=current_url,
                                                     title=current_title,
                                                     cta=cta)
            else:
                data_ind = self.get_carousel_ad_data(creative_hash=creative[1],
                                                     desc=current_description,
                                                     url=current_url,
                                                     title=current_title,
                                                     cta=cta,
                                                     vid_id=creative[0])
            data.append(data_ind)
        link = {
            AdCreativeLinkData.Field.message: body,
            AdCreativeLinkData.Field.link: url[0],
            AdCreativeLinkData.Field.caption: durl,
            AdCreativeLinkData.Field.child_attachments: data,
            AdCreativeLinkData.Field.call_to_action: {
                'type': cta,
                'value': {
                    'link': url[0],
                },
            },
        }
        story = {
            AdCreativeObjectStorySpec.Field.page_id: str(prom_obj),
            AdCreativeObjectStorySpec.Field.link_data: link
        }
        if ig_id and str(ig_id) != 'nan':
            story[AdCreativeObjectStorySpec.Field.instagram_actor_id] = ig_id
        creative = {AdCreative.Field.object_story_spec: story}
        params = {
            Ad.Field.name: ad_name,
            Ad.Field.status: ad_status,
            Ad.Field.adset_id: asid[0],
            Ad.Field.creative: creative
        }
        if view_tag and str(view_tag) != 'nan':
            params['view_tags'] = [view_tag]
        return params
Пример #10
0
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
Пример #11
0
 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()
Пример #12
0
class FacebookExecutor:
    """ Facebook FacebookExecutor.
    Arguments:
        """
    def __init__(self):
        self.client = None
        self.access_token = None
        self.account = None
        self.account_id = None
        self.pixel_id = None
        self.set_api_config()

    def set_api_config(self):
        """
        Loads access_token from FACEBOOK_APPLICATION_CREDENTIALS.
        """
        try:
            with open(os.environ["FACEBOOK_APPLICATION_CREDENTIALS"]) as facebook_cred:
                data = json.load(facebook_cred)
                self.access_token = data["access_token"]
        except KeyError:
            raise KeyError("FACEBOOK_APPLICATION_CREDENTIALS env variable needed")
        self.set_client()

    def set_client(self):
        """
        Sets self.client using the access token.
        """
        self.client = FacebookAdsApi.init(access_token=self.access_token)

    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 set_pixel_id(self, pixel_id):
        """ Sets the Pixel ID
        """
        self.pixel_id = pixel_id
        logging.info("Set the pixel_id as %s", self.pixel_id)

    def get_campaign_insights(self, account_id, fields, start_date, end_date):
        """
        Sets insights from the Facebook Insight API.
        Parameters:
            account_id: ID associated to the Facebook Account
            start_date: The start date
            end_date: The end date
            fields: list of field to be fetched
            start_date/end_date: defines the time range to get insights for (YYYY-mm-dd).
        """
        self.set_account(account_id)
        out = []
        params = {
            'effective_status': ['ACTIVE'],
            'level': 'campaign',
            'time_range': {
                'since': start_date,
                'until': end_date
                }
        }
        logging.debug("Downloading insights for account %s", self.account_id)
        logging.debug("fields: %s", fields)
        logging.debug("params: %s", params)
        campaign_insights = self.account.get_insights(
            params=params,
            fields=fields
        )

        for insight in campaign_insights:
            out.append(dict(insight))
        return out

    def get_active_campaigns(self):
        return self.account.get_campaigns(
            fields=['account_id', 'name', 'daily_budget', 'lifetime_budget'],
            params={
                'effective_status': ["ACTIVE"],
                'is_completed': False
            }
        )

    def get_active_campaign_budgets(self, account_id):
        """
        Fetches active campaign metadata from the Facebook API.
        Returns a dataframe with the following fields:
            - account_id
            - campaign_id
            - campaign_name
            - budget_type (daily_budget or lifetime_budget)
            - budget amount in account currency
        """
        self.set_account(account_id)
        campaigns = self.get_active_campaigns()
        out = transform_campaign_budget(campaigns)
        return out

    def update_daily_budget(self, account_id, campaign_id, new_budget):
        """
        Update the budget on the facebook API
        """
        self.set_account(account_id)
        campaigns = self.get_active_campaigns()
        for campaign in campaigns:
            if campaign.get_id() == campaign_id:
                from pygyver.etl.toolkit import configure_logging
                configure_logging()
                logging.info(
                    "Loading new budget for campaign %s",
                    campaign_id
                )
                logging.info(
                    "Current daily_budget for campaign %s: %s",
                    campaign_id,
                    campaign['daily_budget']
                )
                campaign.api_update(
                    params={'daily_budget': round(new_budget*100)}
                )
                logging.info(
                    "New daily_budget for campaign %s: %s",
                    campaign_id,
                    new_budget
                )

        return campaigns

    def push_conversions_api_events(self, events, test_event_code=None):
        """
        Pushes a list of Events to the Facebook Conversions API.

        :param events: A list of Facebook Events to push to the conversions API
        :type events: list of Event
        :param test_event_code: A test_event_code from Facebook Events Manager to mark these as test events
        :type test_event_code: str

        Returns: A dictionary with the parsed response from the Facebook API
        rtype: dict[str, str]
        """
        if len(events) > 1000:
            logging.error("The maximum number of events that Facebook accepts in a single API call is 1,000. "
                          "Please use the split_events_to_batches() function to split the events into batches")
            raise ValueError

        event_request = EventRequest(
            events=events,
            pixel_id=self.pixel_id,
        )

        # Add the test_event_code if one is given
        if test_event_code:
            event_request.test_event_code = test_event_code

        api_response = {}

        try:
            event_response = event_request.execute()
            logging.info('%s events pushed to Facebook Conversions API', event_response.events_received)
            api_response['status'] = 'API Success'
            api_response['fb_trace_id'] = event_response.fbtrace_id
            api_response['messages'] = '\n'.join(event_response.messages)
            api_response['total_events'] = event_response.events_received

        except FacebookRequestError as e:
            logging.error('There was a Facebook Conversions API error:\n\t%s', e)
            api_response['status'] = 'API Error'
            api_response['fb_trace_id'] = e.body()['error']['fbtrace_id']
            error_message = e.body()['error']['message']
            error_message = ': '.join([error_message, e.body()['error']['error_user_msg']])
            api_response['messages'] = error_message
            api_response['total_events'] = None

        return api_response
Пример #13
0
def get_list_campaign(account_ids):
    my_account = AdAccount(account_ids)
    campaign = my_account.get_campaigns()
    return campaign
Пример #14
0
    def handle(self, *args, **kwargs):
        FacebookAdsApi.set_default_api(api)

        # print('\n\n\n********** Reading objects example. **********\n')

        # Pro tip: Use list(me.get_ad_accounts()) to make a list out of
        # all the elements out of the iterator
        business_account = AdAccount(config['act_id'])
        business_account.remote_read(fields=[AdAccount.Field.tos_accepted])

        camp = business_account.get_campaigns()

        # for attr, value in camp.__dict__.items():
        #     print(attr, 'campaign_name')
        for campaign in camp:
            get_camp_insights = campaign.get_insights(fields=[
                'campaign_name',
                'impressions',
                'clicks',
                'unique_clicks',
                'actions',
                'spend',
                'cpm',
            ])

            # print("Testing "+str(get_camp_insights))
            if (bool(get_camp_insights) == True):
                client = get_camp_insights[0]['campaign_name']
                # print(get_camp_insights)
                imp_ressions = get_camp_insights[0]['impressions']
                spend = get_camp_insights[0]['spend']
                date_start = get_camp_insights[0]['date_start']
                date_stop = get_camp_insights[0]['date_stop']
                client = client.replace(' - ', '@@')

                split_array = client.split('@@')

                damo = date.today()

                bill_month = '{:02}'.format(damo.month)
                bill_year = '{:04}'.format(damo.year)
                bill_date = '0'

                for value in split_array:
                    if 'BD' in value:
                        if len(value) == 3 or len(value) == 4:
                            bill_date = value.replace('BD', '')
                            # bill_date = bill_year+'-'+bill_month+'-'+bill_date
                            if bill_month == '02' and bill_date > '28':
                                bill_date = '28'
                            bill_date = bill_year + '-' + bill_month + '-' + bill_date
                    else:
                        continue
                if split_array[0][1:5] == 'TEST':
                    client_id = '9876'
                else:
                    client_id = (re.findall(r'\d+', client.split('@@')[0])[0])
                client_name = (client.split('@@')[0].split('] ')[1].strip())
                try:
                    if 'for ' in client:
                        target_impressions = int(
                            (re.findall(r'\d+',
                                        client.split('for ')[1])[0]))
                    else:
                        target_impressions = int(
                            (re.findall(r'\d+',
                                        client.split('@@')[1])[0]))
                except:
                    target_impressions = 0

                status = 'na'

                days = (datetime.now().date() -
                        datetime.strptime(bill_date, "%Y-%m-%d").date()).days
                if days < 0:
                    bill_datea = datetime.strptime(bill_date, "%Y-%m-%d")
                    bill_dateaa = bill_datea + relativedelta(months=-1)
                    days = (datetime.now() - bill_dateaa).days

                days_range_dict = {
                    15: 10,
                    16: 20,
                    17: 30,
                    18: 40,
                    19: 50,
                    20: 60,
                    21: 70,
                    22: 80,
                    23: 90,
                    24: 100
                }

                if target_impressions > 0:
                    get_percent = (int(imp_ressions) /
                                   target_impressions) * 100
                    #print(days_range_dict)
                    if get_percent > 250:
                        status = 'co'
                    elif get_percent >= 120 and get_percent <= 250:
                        status = 'ov'
                    elif days > 17 and days < 25:
                        if get_percent < 120 and days > 14 and days < 25:
                            if (days_range_dict[days]):
                                status = 'ot'
                            else:
                                status = 'cu'
                        else:
                            status = 'cu'
                    elif get_percent < 120 and days > 14 and days < 25:
                        if (days_range_dict[days]):
                            status = 'ot'
                        elif days > 14 and days < 18:
                            if (days_range_dict[days]):
                                status = 'un'
                    elif days > 9 and days < 15:
                        if imp_ressions == 0:
                            status = 'un'
                    else:
                        pass
                else:
                    get_percent = 0
                    pass

                # print(status)

                app_tag = 'resultli'
                data = {
                    'spend': spend,
                    'target_impressions': target_impressions,
                    'date_start': date_start,
                    'date_stop': date_stop,
                    'impressions': imp_ressions,
                    'client_id': client_id,
                    'client_name': client_name,
                    'bill_date': bill_date,
                    'percentage': get_percent,
                    'status': status,
                    'app_tag': app_tag,
                    'days': days
                }

                print(data)
Пример #15
0

# r = requests.get('http://213.162.241.217/fb_bidmod/json_accounts.php')
# data = json.loads(r.text.encode('utf-8'))

for cu_data in data:
	act_cid = "act_" + cu_data['cid']
	print("act_" + cu_data['cid'])

	if "weather" in cu_data['services']:
		print("found weather api")
		account = AdAccount(act_cid)
		campaigns = account.get_campaigns(fields=[
		    Campaign.Field.name,
		    Campaign.Field.configured_status,
		], params={
			'effective_status': ['ACTIVE'],
			'filtering':  [{'field':'name', 'operator':'CONTAIN','value':'Weather API'}], #set to SUMMER
		})

		for i in campaigns:
			c_value = campaigns
			

			temp_campaign = Campaign(i["id"])
			campaign_name = i["name"]
			print(temp_campaign, " campaing id")
			temp_campaign_str = i["id"]
			adsets = temp_campaign.get_ad_sets(fields=[
			    AdSet.Field.name,
			    AdSet.Field.id,
Пример #16
0
def get_campaigns(app_id: str, app_secret: str, account_access_token: str, account_id: str):
    FacebookAdsApi.init(app_id, app_secret, account_access_token)
    account = AdAccount(account_id)
    return  account.get_campaigns()
Пример #17
0
def data():

    my_access_token = request.form['acctoken']
    FacebookAdsApi.init(access_token=my_access_token)
    adacc = 'act_' + request.form['accid']
    my_account = AdAccount(adacc)

    #getting all fields and removing some fields that are not in the document that produce errors
    Fields_Campaign = [
        attr for attr in dir(Campaign.Field)
        if not callable(getattr(Campaign.Field, attr))
        and not attr.startswith("__")
    ]
    Fields_Ad = [
        attr for attr in dir(Ad.Field)
        if not callable(getattr(Ad.Field, attr)) and not attr.startswith("__")
    ]
    Fields_AdCreative = [
        attr for attr in dir(AdCreative.Field)
        if not callable(getattr(AdCreative.Field, attr))
        and not attr.startswith("__")
    ]
    a = ['call_to_action', 'image_file', 'is_dco_internal']
    Fields_AdCreative = [i for i in Fields_AdCreative if i not in a]
    Fields_AdSets = [
        attr for attr in dir(AdSet.Field) if
        not callable(getattr(AdSet.Field, attr)) and not attr.startswith("__")
    ]
    b = [
        'line_number', 'rb_prediction_id', 'time_start', 'time_stop',
        'topline_id', 'tune_for_category', 'upstream_events',
        'full_funnel_exploration_mode', 'daily_imps', 'date_format',
        'execution_options', 'campaign_spec'
    ]
    Fields_AdSets = [i for i in Fields_AdSets if i not in b]
    Fields_AdsInsights = [
        attr for attr in dir(AdsInsights.Field)
        if not callable(getattr(AdsInsights.Field, attr))
        and not attr.startswith("__")
    ]
    c = [
        'dwell_3_sec', 'dwell_5_sec', 'actions_per_impression',
        'actions_results', 'activity_recency', 'ad_format_asset', 'age',
        'amount_in_catalog_currency', 'app_store_clicks',
        'attention_events_per_impression', 'attention_events_unq_per_reach',
        'body_asset', 'call_to_action_asset', 'call_to_action_clicks',
        'campaign_delivery', 'campaign_end', 'campaign_start',
        'cancel_subscription_actions', 'card_views', 'catalog_segment_actions',
        'catalog_segment_value_in_catalog_currency',
        'catalog_segment_value_mobile_purchase_roas',
        'catalog_segment_value_website_purchase_roas',
        'conditional_time_spent_ms_over_10s_actions',
        'conditional_time_spent_ms_over_15s_actions',
        'conditional_time_spent_ms_over_2s_actions',
        'conditional_time_spent_ms_over_3s_actions',
        'conditional_time_spent_ms_over_6s_actions', 'contact_actions',
        'contact_value', 'cost_per_action_result',
        'cost_per_completed_video_view', 'cost_per_contact',
        'cost_per_customize_product', 'cost_per_donate', 'cost_per_dwell',
        'cost_per_dwell_3_sec', 'cost_per_dwell_5_sec', 'cost_per_dwell_7_sec',
        'cost_per_find_location', 'cost_per_schedule', 'cost_per_start_trial',
        'cost_per_submit_application', 'cost_per_subscribe',
        'cost_per_total_action', 'country', 'creative_fingerprint',
        'customize_product_actions', 'customize_product_value',
        'deduping_1st_source_ratio', 'deduping_2nd_source_ratio',
        'deduping_3rd_source_ratio', 'deduping_ratio', 'deeplink_clicks',
        'description_asset', 'device_platform', 'dma', 'donate_actions',
        'donate_value', 'dwell_3_sec, dwell_5_sec', 'dwell_7_sec',
        'dwell_rate', 'earned_impression', 'find_location_actions',
        'find_location_value', 'frequency_value', 'gender',
        'hourly_stats_aggregated_by_advertiser_time_zone',
        'hourly_stats_aggregated_by_audience_time_zone', 'image_asset',
        'impression_device', 'impressions_auto_refresh', 'impressions_gross',
        'link_url_asset', 'media_asset', 'newsfeed_avg_position',
        'newsfeed_clicks', 'newsfeed_impressions', 'optimization_goal',
        'performance_indicator', 'place_page_id', 'placement',
        'platform_position', 'product_id', 'publisher_platform',
        'recurring_subscription_payment_actions', 'region', 'rule_asset',
        'schedule_actions', 'schedule_value', 'start_trial_actions',
        'start_trial_value', 'submit_application_actions',
        'submit_application_value', 'subscribe_actions', 'subscribe_value',
        'thumb_stops', 'title_asset', 'today_spend', 'total_action_value',
        'total_actions', 'total_unique_actions', 'unique_impressions',
        'video_asset', 'video_complete_watched_actions',
        'video_completed_view_or_15s_passed_actions', 'website_clicks'
    ]
    Fields_AdsInsights = [i for i in Fields_AdsInsights if i not in c]

    #get data from campaigns to ads insights
    alldata = []
    campaign = my_account.get_campaigns(fields=Fields_Campaign)
    #	ad_Creative = my_account.get_ad_creatives(fields =Fields_AdCreative)
    #	ads = my_account.get_ads(fields=Fields_Ad)
    #	ad_sets =  my_account.get_ad_sets(fields=Fields_AdSets)
    #	ad_insight = my_account.get_insights(fields = Fields_AdsInsights)

    alldata.append(campaign)
    #	alldata.push(ad_Creative)
    #	alldata.append(ads)
    #	alldata.push(ad_sets)
    #	alldata.append(ad_insight)

    return render_template("data.html", data=alldata)
Пример #18
0
 def deleteAllCampaigns(self):
     my_account = AdAccount(fbid=self.account_id)
     my_account.remote_read()
     for c in my_account.get_campaigns():
         c.remote_delete()
Пример #19
0
class FacebookReporter:
    def __init__(self):
        app_id = '769583813938024'
        app_secret = '0d785a6bb23bc248a827fed820fe4ea0'
        access_token = 'EAAK77rHay2gBANEqlTi1DEbX7oDnyGbu9d3crWlPTHDHeeRL32WtPAPW0yn3cafTw98VXaTpwBZCubl20jRijqZBZCANU9RtMKdJWoYkXRZChW0IFEvJmBw7YrybTFsrnoKH3JvYZBGZAeuRYNMs4Agb2bsO1aeCGFVk3YlqjehRDAKqkXPEuZA'
        self.facebook_api = FacebookAdsApi.init(app_id, app_secret,
                                                access_token)
        self.ad_account = AdAccount('act_881123992711859')
        self.fields = [
            'video_play_actions', 'video_p25_watched_actions',
            'video_p50_watched_actions', 'video_p75_watched_actions',
            'video_p100_watched_actions', 'attribution_setting', 'objective',
            'reach', 'impressions', 'frequency', 'account_currency',
            'campaign_id', 'campaign_name', 'adset_name', 'adset_id',
            'ad_name', 'ad_id', 'ad_impression_actions', 'spend',
            'unique_inline_link_clicks', 'actions'
        ]

        self.params = {
            'level': 'ad',
            'date_preset': 'last_30d',
            'time_increment': 1,
            'use_unified_attribution_setting': True,
            'default_summary': True,
        }
        self.current_ads = []

    def get_ad_data_or_sleep(self, ad):
        """
        Get needed data for ads or sleep
        :param ad:
        :return:
        """
        while True:
            ad_data = {'ad_id': ad}

            try:

                ad = Ad(ad)

                creative = AdCreative(
                    ad.api_get(fields=[Ad.Field.creative])['creative']['id'])
                fields = [
                    AdCreative.Field.call_to_action_type,
                    AdCreative.Field.object_story_spec
                ]

                creative.api_get(fields=fields)
                creative = dict(creative)
                try:
                    call_to_action = creative['object_story_spec'][
                        'video_data']['call_to_action']
                    try:
                        print(creative['object_story_spec']['photo_data'])
                    except KeyError:
                        pass

                    ad_data['website_url'] = call_to_action['value']['link']

                    ad_data['call_to_action_type'] = call_to_action['type']
                    ad_data['headline'] = creative['object_story_spec'][
                        'video_data']['title']
                    ad_data['description'] = creative['object_story_spec'][
                        'video_data']['message']

                    video = AdVideo(creative['object_story_spec']['video_data']
                                    ['video_id'])
                    ad_data['video_name'] = video.api_get(
                        fields=[AdVideo.Field.title])['title']
                except KeyError:
                    pass
                self.current_ads.append(ad_data)
            except FacebookRequestError as e:
                print(type(e.api_error_code()))
                if e.api_error_code() == 803:
                    break
                print('Sleeping right now for ads')

                time.sleep(600)
            else:
                break

        return ad_data

    def get_insights_or_sleep(self, campaign):
        """
        Collect insights for campaign or sleep for time to not trigger Facebook API limits
        :param campaign:
        :return:
        """
        while True:
            try:
                insights = campaign.get_insights(fields=self.fields,
                                                 params=self.params,
                                                 is_async=True)
                insights.api_get()
                while insights[
                        AdReportRun.Field.
                        async_status] != 'Job Completed' or insights[
                            AdReportRun.Field.async_percent_completion] < 100:
                    time.sleep(1)
                    insights.api_get()
                    print(insights[AdReportRun.Field.async_percent_completion])
                time.sleep(1)
                insights = insights.get_result()
            except FacebookRequestError:
                print('Sleeping right now for insights')
                time.sleep(600)
            else:
                break
        return insights

    def get_campaigns_or_sleep(self):
        while True:
            try:
                campaigns = self.ad_account.get_campaigns()
            except FacebookRequestError:
                print('Sleeping right now for campaigns')
                time.sleep(30)
            else:
                break
        return campaigns

    def generate_report(self, breakdowns):
        rows = []
        campaigns = []
        for campaign in self.get_campaigns_or_sleep():
            campaigns.append(campaign)
        for i in range(len(campaigns)):

            self.params['breakdowns'] = breakdowns
            insights = self.get_insights_or_sleep(campaigns[i])
            for y in range(len(insights)):
                insight = dict(insights[y])
                flag = False
                for ad in self.current_ads:
                    if ad['ad_id'] == insight['ad_id']:
                        insight.update(ad)
                        flag = True
                        break
                if not flag:
                    insight.update(self.get_ad_data_or_sleep(insight['ad_id']))
                rows.append(insight)
                print(
                    f'Pulling dats for campaign, {i}/{len(campaigns)}, {y}/{len(insights)}'
                )
                try:
                    json.dumps(rows)
                except:
                    rows.remove(insight)
            CSVGenerator().generate_report(rows, breakdowns)
Пример #20
0
"""

from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.adaccount import AdAccount

#Claves de acceso
my_app_id = '276686046355294'
my_app_secret = '888a472886359feee3c0c0e45b414c00'
my_access_token = 'EAAD7pP2B314BAMKHIBTjpPQqXKYOZArD5v7ZBvGbuZAgNNE1YKsqj3iYZAYm2LowacK8NkHOh2eEZCXhhafRvBXk20Um4ZBMn26DVXA5hDoBhQSXn6xJjWhnA9jm85q7sih7sT7WokUI2fLzUm4Xa6n5hpipZASZAF1BwEp8BXCY6PJzdnWoK6ZB1DkT6fBqzyZBmZBvyzINaFgowZDZD'

#Iniciar API
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)

#Llamadas
my_account = AdAccount('act_754103418273978')
campaigns = my_account.get_campaigns()

print(campaigns)

import requests

a = requests.get(
    "https://graph.facebook.com/276686046355294/720786428006108/adnetworkanalytics/?metrics=['fb_ad_network_imp']&access_token=EAAD7pP2B314BAMKHIBTjpPQqXKYOZArD5v7ZBvGbuZAgNNE1YKsqj3iYZAYm2LowacK8NkHOh2eEZCXhhafRvBXk20Um4ZBMn26DVXA5hDoBhQSXn6xJjWhnA9jm85q7sih7sT7WokUI2fLzUm4Xa6n5hpipZASZAF1BwEp8BXCY6PJzdnWoK6ZB1DkT6fBqzyZBmZBvyzINaFgowZDZD"
)
a
base = a.content

type(base)

#Llamadas Interesess
Пример #21
0
class LibFacebook:
    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 create_ad_tree(self):
        # Campaign fields
        fields = ["id",
                  "account_id",
                  "adlabels",
                  "bid_strategy",
                  "boosted_object_id",
                  "brand_lift_studies",
                  "budget_rebalance_flag",
                  "budget_remaining",
                  "buying_type",
                  "can_create_brand_lift_study",
                  "can_use_spend_cap",
                  "configured_status",
                  "created_time",
                  "daily_budget",
                  "effective_status",
                  "issues_info",
                  "lifetime_budget",
                  "name",
                  "objective",
                  "recommendations",
                  "source_campaign",
                  "source_campaign_id",
                  "spend_cap",
                  "start_time",
                  "status",
                  "stop_time",
                  "updated_time"]

        # List of all campaigns
        campaigns = self.account.get_campaigns(fields=fields)

        # Ad set fields
        fields = ["id",
                  "account_id",
                  "adlabels",
                  "adset_schedule",
                  "attribution_spec",
                  "bid_amount",
                  "bid_info",
                  "bid_strategy",
                  "billing_event",
                  "budget_remaining",
                  "campaign",
                  "campaign_id",
                  "configured_status",
                  "created_time",
                  "creative_sequence",
                  "daily_budget",
                  "daily_min_spend_target",
                  "daily_spend_cap",
                  "destination_type",
                  "effective_status",
                  "end_time",
                  "frequency_control_specs",
                  "instagram_actor_id",
                  "is_dynamic_creative",
                  "issues_info",
                  "lifetime_budget",
                  "lifetime_imps",
                  "lifetime_min_spend_target",
                  "lifetime_spend_cap",
                  "name",
                  "optimization_goal",
                  "pacing_type",
                  "promoted_object",
                  "recommendations",
                  "recurring_budget_semantics",
                  "rf_prediction_id",
                  "source_adset",
                  "source_adset_id",
                  "start_time",
                  "status",
                  "targeting",
                  "time_based_ad_rotation_id_blocks",
                  "time_based_ad_rotation_intervals",
                  "updated_time",
                  "use_new_app_click"]

        # List of all ad sets
        ad_sets = self.account.get_ad_sets(fields=fields)

        # Ad fields
        fields = ["id",
                  "account_id",
                  "ad_review_feedback",
                  "adlabels",
                  "adset",
                  "adset_id",
                  "bid_amount",
                  "bid_info",
                  "bid_type",
                  "campaign",
                  "campaign_id",
                  "configured_status",
                  "conversion_specs",
                  "created_time",
                  "creative",
                  "effective_status",
                  "issues_info",
                  "last_updated_by_app_id",
                  "name",
                  "recommendations",
                  "source_ad",
                  "status",
                  "tracking_specs",
                  "updated_time"]

        # List of all ads
        ads = self.account.get_ads(fields=fields)

        ad_tree = []
        for i in campaigns:
            ad_structure_dict = {"campaign": i.export_all_data(),
                                 "adset_list": []}

            a = 0
            for j in ad_sets:
                if j["campaign_id"] == i["id"]:
                    ad_structure_dict["adset_list"].append({"ad_set": j.export_all_data(),
                                                            "ad_list": []})

                    for k in ads:
                        if k["adset_id"] == j["id"]:
                            ad_structure_dict["adset_list"][a]["ad_list"].append({"ad": k.export_all_data()})

                    a += 1

            ad_tree.append(ad_structure_dict)

        return ad_tree