def get_account_business_info(self, account_id):
     account = AdAccount('act_%s' % str(account_id))
     account.remote_read(fields=[AdAccount.Field.business])
     business_info = account[AdAccount.Field.business]
     if business_info:
         return business_info
     return {}
    def get_ads_insight(self, report_date,account_id):

        ad_account = AdAccount(fbid=account_id)
        limit = 5000
        fields = ['campaign_name',
                'ad_id',
                'reach',
                'date_start',
                'date_stop',
                'impressions',
                'actions',
                'ctr',
                'clicks',
                'objective',
                'spend'
            ]
        params = {
            'time_range': {
                'since': report_date,
                'until': report_date
            },
#            'date_preset':'last_7d',
            'action_attribution_windows': ['28d_click','28d_view'],
            'breakdowns': ['gender', 'age'],
            'time_increment':'1',             
            'level': 'ad',
            'limit': limit if limit > 0 else None
        }
        insights = ad_account.get_insights(fields, params)
        return insights
예제 #3
0
 def __init__(self, account_id):
     prefs = Preferences.objects.get()
     ad_account_id = 'act_%s' % account_id
     FacebookAdsApi.init(access_token=prefs.facebook_access_token)
     fields = [
         'account_id',
         'account_name',
         'cost_per_total_action',
         'impressions',
         'total_action_value',
         'spend',
     ]
     now = timezone.now()
     last_day = calendar.monthrange(now.year, now.month)[1]
     params = {
         'time_range': {
             'since': now.strftime('%Y-%m-01'),
             'until': now.strftime('%Y-%m-') + '%s' % last_day
         },
         'filtering': [],
         'level': 'account',
         'breakdowns': [],
     }
     try:
         self.data = AdAccount(ad_account_id).get_insights(fields=fields,
                                                           params=params)[0]
     except:
         self.data = None
예제 #4
0
    def get_report(self, fields, params, file_dir):
        """
            Uses asynchronous calls to avoid time out. Pins every 15 seconds to check status. Once done, pull 
            the data, and dump data into a local file
            :param fields: all valid fields we can retrieve from an Ad account
            :param params: specifies report level, report dates, breakdowns, filters
            :param file_dir: specifies the downloading location
            :return: None
        """
        with gzip.open(file_dir, 'wb') as outfile:
            for account_id in self.account_ids:
                account = AdAccount('act_' + account_id)

                async_job = account.get_insights(fields=fields,
                                                 params=params,
                                                 async=True)
                async_job.remote_read()
                while async_job[
                        AdReportRun.Field.async_status] != 'Job Completed':
                    time.sleep(5)
                    async_job.remote_read()
                time.sleep(1)

                for result in async_job.get_result():
                    json.dump(result.export_all_data(), outfile)
                    outfile.write('\n')
        outfile.close()
예제 #5
0
def test_campaign_upload(campaign_data, account):
    """
    Args:
        campaign_data (dict): parameters parsed from Json
        account (str): Account where to upload the campaing

    Returns:
        TYPE: Description
    """
    # Check if we're working with the correct account
    active_account = AdAccount(account)
    active_account.remote_read(fields=[AdAccount.Field.name])

    print('Uploading a campaign to %s' % active_account[AdAccount.Field.name])

    confirm = input('Do you want to continue? Y/N  --> ')
    if confirm not in ('y', 'Y'):
        print('Aborted campaign upload')
        return

    print("\nRunning validations...")
    # Initial validations
    validate(campaign_data)

    print("\nUploading campaign...")
    # Get existing or create a new campaign
    campaign_id = create_campaign(campaign_data, account)
    print('Campaign uploaded!')
    # Create Ad set
    print("\nUploading AdSet...")
    create_ad_set(campaign_data, account, campaign_id)
    print('Ad set uploaded!')
예제 #6
0
파일: FB.py 프로젝트: prokashev/facebookapi
def getvalues():
    tmp_string = str(AdAccount(ad_account_id).get_insights(
        fields=fields,
        params=params,
    )).split('<AdsInsights>')
    tmp_string = str(tmp_string)[7:][:-3]

    i = 2
    list_of_jsons = str(tmp_string).split(', \'')
    for json1 in list_of_jsons:
        json1 = json1.replace('\\n    ', '')
        json1 = json1.replace('\\n', '')
        try:
            j = json.loads(json1)
            cn = j['campaign_name']
            sp = j['spend']
            print cn
            print type(cn)
            cost = Decimal(sp) * Parser.q
            print cost
            sheet.update_acell('B1', month)
            if modified_list.find(cn) != -1:
                print ("String in the string!")
            else:
                sheet.update_acell('A' + str(i), cn)

            sheet.update_acell('B' + str(i), cost)

            i += 1
        except ValueError:
            'stupid error, everything works'
 def get_campaigns_info_by_account(self, account_id):
     account = AdAccount('act_%s' % str(account_id))
     campaigns = account.get_campaigns(fields=[
         Campaign.Field.id, Campaign.Field.name, Campaign.Field.objective,
         Campaign.Field.status, Campaign.Field.updated_time
     ])
     if campaigns: return campaigns
     return {}
 def get_account_info(self, account_id):
     account = AdAccount('act_%s' % str(account_id))
     account.remote_read(fields=[
         AdAccount.Field.id, AdAccount.Field.name,
         AdAccount.Field.account_status
     ])
     if account: return account
     return {}
예제 #9
0
def get_campaigns(account_id):
    fields = ["id", "name"]

    def decorate(x):
        return {"value": x["id"], "name": x["name"]}

    account = AdAccount(account_id)
    return [decorate(x) for x in account.get_campaigns(fields)]
예제 #10
0
    def get_ads_insight(self, account_id, from_time, to_time):
        """sample_response:: <api.Cursor> [
            <AdsInsights> {
                "ad_name": "Ad name here",
                "adset_name": "Sample name",
                "campaign_id": "123456789",
                "campaign_name": "Campaign Test name",
                "cost_per_unique_click": "0.727143",
                "cpc": "0.727143",
                "ctr": "1.62037",
                "date_start": "2019-12-10",
                "date_stop": "2019-12-10",
                "spend": "5.09",
                "clicks": "7",
                "unique_clicks": "7"
            },
        ]"""
        params = self.build_params(from_time, to_time)
        the_ad_account = AdAccount(account_id)
        try:
            async_job = the_ad_account.get_insights_async(fields=self.fields,
                                                          params=params)
            status = async_job.remote_read()
            while status['async_percent_completion'] < 100:
                time.sleep(1)
                status = async_job.remote_read()
            result = async_job.get_result()

            insight_data_list = []
            for item_ad_insight in result._queue:
                temp_dict = {}
                for _key in self.fields:
                    try:
                        temp_dict.update({
                            _key:
                            item_ad_insight.__getitem__(_key),
                        })
                    except KeyError:
                        temp_dict.update({
                            _key: '',
                        })
                if temp_dict:
                    insight_data_list.append(temp_dict)
            for k in self.required_merged_field_list:
                self.final_data.update(
                    {k: self.add_value_by_key(k, insight_data_list)})
            if len(insight_data_list) > 0:
                remaining_fields_set = set(self.fields) ^ set(
                    self.required_merged_field_list)
                for f in remaining_fields_set:
                    # remaining fields has same value of all items of the list. That's why only first item is considered
                    self.final_data.update(
                        {f: insight_data_list[0].get(f, '')})
        except FacebookRequestError:
            pass
            # print(er)
        return self.final_data
예제 #11
0
 def api_create(self,
                parent_id,
                fields=None,
                params=None,
                batch=None,
                pending=False):
     from facebookads.adobjects.adaccount import AdAccount
     return AdAccount(api=self._api, fbid=parent_id).get_insights_async(
         fields, params, batch, pending)
 def api_create(self,
                parent_id,
                fields=None,
                params=None,
                batch=None,
                pending=False):
     from facebookads.adobjects.adaccount import AdAccount
     return AdAccount(api=self._api, fbid=parent_id).create_custom_audience(
         fields, params, batch, pending)
예제 #13
0
def create_campaign(account_id, name, objective, status):
    account = AdAccount(account_id)

    campaign = Campaign(parent_id=account.get_id_assured())
    campaign[Campaign.Field.name] = name
    campaign[Campaign.Field.objective] = objective
    campaign[Campaign.Field.configured_status] = status

    print(campaign.remote_create())
    def get_adset_info_by_account(self, account_id):
        account = AdAccount('act_%s' % str(account_id))
        adsets = account.get_ad_sets(fields=[
            AdSet.Field.id, AdSet.Field.name, AdSet.Field.campaign_id,
            AdSet.Field.status
        ])

        if adsets: return adsets
        return {}
def adset_comment_fetcher(account, params, fields):
    """
    fetches ad ids and corresponding adset name from active campaigns for the selected ad account
    """
    account = AdAccount(account)

    adset_insights = account.get_insights(fields=fields, params=params)
    for insight in adset_insights:
        adset_name_ad_id[insight['adset_name']] = insight['ad_id']
    return adset_name_ad_id
예제 #16
0
 def get_prospecting_campaign_id(self, acc_id):
     """Takes in an account id and searches across the ad accounts campaigns looking for the campaign name Prospecting. If found, return the campaign id."""
     account = AdAccount(acc_id).get_campaigns()
     for camp in account:
         campaign =  Campaign(camp['id'])
         campaign.remote_read(fields=[
             Campaign.Field.name,
         ])
         if campaign['name'] == 'Prospecting':
             return camp['id']
예제 #17
0
    def getfacebookApi(self):
        if self.secret != '-':
            self.api = FacebookAdsApi.init(access_token=self.token,
                                           app_secret=self.secret,
                                           api_version='v3.2')
        else:
            self.api = FacebookAdsApi.init(access_token=self.token,
                                           api_version='v3.2')

        self.account = AdAccount('act_' + act_id)
 def api_create(self,
                parent_id,
                fields=None,
                params=None,
                batch=None,
                pending=False):
     from facebookads.adobjects.adaccount import AdAccount
     return AdAccount(api=self._api,
                      fbid=parent_id).create_reach_frequency_prediction(
                          fields, params, batch, pending)
예제 #19
0
def get_ad_account():

    if secret != '-':
        FacebookAdsApi.init(access_token=token,
                            app_secret=secret,
                            api_version='v4.0')
    else:
        FacebookAdsApi.init(access_token=token, api_version='v4.0')
    account = AdAccount('act_' + act_id)
    return account
예제 #20
0
파일: main.py 프로젝트: Peridian/etl
def facebook_data_extraction(config):
    '''
    Facebook Ads platform data extraction
    '''
    facebook_get_service(config)
    me = User(fbid='me')
    print('me', me)
    print('me.remote_read(fields=[User.Field.permissions])', me.remote_read())
    ad_account = AdAccount(config['ad_account_id'])
    print('ad_account', ad_account.remote_read())
    print('ad_account', ad_account.get_campaigns())
    return ''
 def get_account_category(self, account_id):
     account_category_dict = {"category": "unknow", "subcategory": "unknow"}
     account = AdAccount('act_%s' % str(account_id))
     application = account.get_applications(
         fields=["category", "subcategory"])
     if application:
         if "category" in application[0].keys():
             account_category_dict["category"] = application[0]["category"]
         if "subcategory" in application[0].keys():
             account_category_dict["subcategory"] = application[0][
                 "subcategory"]
     return account_category_dict
    def match_custom_audience(self, **kwargs):
        fb_api_init()
        out = []
        words = [x.lower() for x in kwargs['words']]
        account = AdAccount(kwargs['account_id'])
        ca = account.get_custom_audiences(fields=[CustomAudience.Field.name])

        for audience in ca:
            if any(word in [x.lower() for x in audience['name'].split(' ')]
                   for word in words):
                out.append(audience)

        return out
예제 #23
0
def crawlDemographics(output_file_path, sleep_time):
    country = 'US'
    destination_file_path = '%s%s/' % (output_file_path, country)

    verifyDir(destination_file_path)
    print destination_file_path

    log_file = open('%slog_all.txt' % (destination_file_path), 'w')
    exception_log_file = open(
        '%sexception_log_all.txt' % (destination_file_path), 'w')

    if secret != '-':
        FacebookAdsApi.init(access_token=token,
                            app_secret=secret,
                            api_version='v3.1')
    else:
        FacebookAdsApi.init(access_token=token, api_version='v3.1')
    account = AdAccount('act_' + act_id)

    count_total_requests = 0
    count_interest_ids = 0
    count_exceptions = 0
    count_sequenced_exceptions = 0

    cur_time = getCurrentTime()
    log_file.write('Execution initialized: %s \n' % cur_time)
    count_interest_ids += 1

    #first element of the following list indicates to the crawler to collect the demographics for the US only whereas second and third one are
    # the interests related to the new york times and washington post, respectively.
    list_of_interests = ['all_%s' % cur_time, '6003058819532', '6003096798132']
    for interest_id in list_of_interests:
        #         interest_id =  'all_%s' % cur_time
        #         crawlInterest(interest_id, destination_file_path, account, log_file, exception_log_file, sleep_time)
        count_total_requests, count_sequenced_exceptions, count_exceptions = crawlInterest(
            interest_id, destination_file_path, account, log_file,
            exception_log_file, count_total_requests,
            count_sequenced_exceptions, count_exceptions, sleep_time)
        if count_sequenced_exceptions == MAXIMUM_EXCEPTIONS:
            log_file.write('******** Sequenced exceptions == %d **********\n' %
                           MAXIMUM_EXCEPTIONS)
            log_file.write('******** Going to terminate **********\n')
            break

    log_file.write('total of interest ids: %d \n' % count_interest_ids)
    log_file.write('total of requests: %d \n' % count_total_requests)
    log_file.write('total of exceptions: %d \n' % count_exceptions)
    log_file.write('Execution finalized: %s \n' % getCurrentTime())

    # # safe exit
    log_file.close()
 def get_creatives(self, report_date, account_id):
     ad_account = AdAccount(fbid=account_id)
     limit = 500
     fields = [AdCreative.Field.thumbnail_url]
     params = {
         'time_range': {
             'since': report_date,
             'until': report_date
         },
         #        'date_preset':'last_90d',
         'limit': limit if limit > 0 else None
     }
     insights = ad_account.get_ad_creatives(fields, params)
     return insights
def ad_ids_fetcher(account, params, fields):
    """
    fetches ad ids from active campaigns for the selected ad account

    """
    account = AdAccount(account)
    try:
        adset_insights = account.get_insights(fields=fields, params=params)
    except Exception:
        exception_catcher('/facebook_ads_comments_analyzer/')

    ad_ids_list = [insight['ad_id'] for insight in adset_insights]

    return ad_ids_list
 def ads(self, report_date, account_id):
     ad_account = AdAccount(fbid=account_id)
     limit = 5000
     fields = ['id', 'creative', Ad.Field.name]
     params = {
         'time_range': {
             'since': report_date,
             'until': report_date
         },
         #        'date_preset':'last_90d',
         'limit': limit if limit > 0 else None
     }
     insights = ad_account.get_ads(fields, params)
     return insights
예제 #27
0
def get_fb_data(AccountId):
    FacebookAdsApi.init(facebookConfig.Configs['App_id'],
                        facebookConfig.Configs['App_secret'],
                        facebookConfig.Configs['Access_token'])

    my_account = AdAccount(facebookConfig.Accounts[AccountId])

    # Grab insight info for all ads in the adaccount

    #Ever this function will get data from yesterday
    #If somebody wants to change the range of date, is necessary to change the param 'date_preset'
    #You can change the level of your request. example: ad, adset or campaign
    '''
    I dont recommend change the param date_preset because the data comes cumulative, not good for me.
    The data from yesterday is better and trustworthy . I suggest to compare with reports from your Business manager facebook
    '''
    data = my_account.get_insights(
        params={
            'date_preset': 'yesterday',
            'level': 'ad'
        },
        fields=[
            AdsInsights.Field.account_id,
            AdsInsights.Field.account_name,
            #AdsInsights.Field.campaign_id,
            AdsInsights.Field.campaign_name,
            AdsInsights.Field.ad_name,
            AdsInsights.Field.ad_id,
            AdsInsights.Field.adset_id,
            AdsInsights.Field.adset_name,
            AdsInsights.Field.cost_per_outbound_click,
            AdsInsights.Field.outbound_clicks,
            AdsInsights.Field.spend,
            AdsInsights.Field.clicks,
            AdsInsights.Field.inline_link_clicks,
            AdsInsights.Field.inline_link_click_ctr,
            AdsInsights.Field.cpm,
            AdsInsights.Field.ctr,
            AdsInsights.Field.reach,
            AdsInsights.Field.frequency,
            AdsInsights.Field.impressions
        ])

    dataNormalize = normalize.dumps_data(data)

    df = normalize.change_types(dataNormalize)

    return df
예제 #28
0
def create_video(request):
    FacebookAdsApi.init(account_id=settings.FACEBOOK_MAIN_AD_ACCOUNT,
                        access_token=settings.FACEBOOK_TEST_TOKEN)
    ad_video = AdAccount(
        fbid=settings.FACEBOOK_MAIN_AD_ACCOUNT
    ).create_ad_video(
        params={
            AdVideo.Field.slideshow_spec: {
                'images_urls': [
                    'https://www.downtownrochestermn.com/_files/images/sbs15tkssblue[1].png',
                    'http://d3sdoylwcs36el.cloudfront.net/VEN-virtual-enterprise-network-business-opportunities-small-fish_id799929_size485.jpg',
                    'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQmvDxaUoi9wsAm2H0qvdaCn8ISnkqOPSBDojx7WznZLoAMhvW_mjI7Pw'
                ]
            }
        })
    return JsonResponse(ad_video.export_all_data(), safe=False)
예제 #29
0
def get_campaign_list(account_id):
    try:
        ad_account = AdAccount(account_id)
        campaigns = ad_account.get_campaigns(fields=[
            Campaign.Field.name, Campaign.Field.id, Campaign.Field.status
        ])
        active_campaign_hash = {}
        for campaign in campaigns:
            if 'ACTIVE' in campaign[Campaign.Field.status]:
                active_campaign_hash[campaign[Campaign.Field.id]] = campaign[
                    Campaign.Field.name]
        logger.info(active_campaign_hash)
        return active_campaign_hash

    except exceptions.FacebookError, e:
        logger.error('Error %s' % e)
        return {}
예제 #30
0
    def get_ad_accounts(self, business_id):
        """Returns list of adaccounts associated with the ads pixel"""
        response = self.get_api_assured().call(
            'GET',
            (self.get_id_assured(), 'shared_accounts'),
            params={
                'business': business_id
            },
        ).json()

        ret_val = []
        if response:
            keys = response['data']
            for item in keys:
                search_obj = AdAccount()
                search_obj.update(item)
                ret_val.append(search_obj)
        return ret_val