Ejemplo n.º 1
0
		def __init__(self, my_access_token, my_account_id, my_app_id = 'XXXXXXX', my_app_secret='XXXXXXXXXX'):
				self.my_app_id = my_app_id
				self.my_app_secret = my_app_secret
				self.my_access_token = my_access_token
				self.my_account_id = my_account_id
				FacebookAdsApi.init(self.my_app_id, self.my_app_secret, self.my_access_token)
				self.api = FacebookAdsApi.get_default_api()
Ejemplo n.º 2
0
 def __init__(self, post):
     self.ad_account_id = "act_" + post["fb_ad_account"]
     self.post = post
     FacebookAdsApi.init(app_id=app_id,
                         app_secret=app_secret,
                         access_token=post["access_token"],
                         api_version="v3.0")
Ejemplo n.º 3
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    token = 'EAAatqMY9YeQBAKo2WiunzO8xaxA0YwqQXfflxCLKuZAZA75i44dndFAYrXP1wwiaDnNElMPy28HalSgz52vI8qkSyW45u8C96o8MZA0hPQU8SA9ZCOhFKoySma4HZAtMR7JLZB262BEY6jDMIEPaKe2P4tTIsdllZBsrmWPyJjCh3of5Tl1hXRZBMG8kZBtM6ViNapBVpbrHw0tSqVPcwe9a9'
    FacebookAdsApi.init(access_token=token)

    params = {
        'q': name,
        'limit': 10000000,
        'locate': 'pt_br',
        'type': 'adinterest',
    }

    name = TargetingSearch.search(params=params)

    if name:
        return func.HttpResponse(f"Hello {name}!")
    else:
        return func.HttpResponse(
            "Please pass a name on the query string or in the request body",
            status_code=400)
Ejemplo n.º 4
0
def data(request):
    print(request)
    # environmental variables for facebook auth
    app_id = os.environ['APP_ID']
    app_secret = os.environ['APP_SECRET']
    access_token = os.environ['ACCESS_TOKEN']
    FacebookAdsApi.init(app_id, app_secret, access_token)

    campaign_id = request.GET['campaign-id']

    def get_campaign_stats(campaign):
        campaign = Campaign(campaign)
        params = {
            'data_preset': 'lifetime',
            'fields': [
                Insights.Field.impressions,
                Insights.Field.unique_clicks,
                Insights.Field.reach,
                Insights.Field.cpm,
                Insights.Field.spend,
            ]
        }
        data_set = campaign.get_insights(params=params)
        return data_set[0]

    data_set = get_campaign_stats(campaign_id)
    data_set['cpm'] = str(data_set['cpm'])[:4]
    context = {
        'data_set': data_set,
        'name': 'Campaign Breakdown',
    }
    print(data_set)
    return render(request, 'campaigns_data/data.html', context)
Ejemplo n.º 5
0
def data(request):
    print(request)
    # environmental variables for facebook auth
    app_id = os.environ['APP_ID']
    app_secret = os.environ['APP_SECRET']
    access_token = os.environ['ACCESS_TOKEN']
    FacebookAdsApi.init(app_id, app_secret, access_token)

    campaign_id = request.GET['campaign-id']

    def get_campaign_stats(campaign):
        campaign = Campaign(campaign)
        params = {
            'data_preset':
            'lifetime',
            'fields': [
                Insights.Field.impressions,
                Insights.Field.unique_clicks,
                Insights.Field.reach,
                Insights.Field.cpm,
                Insights.Field.spend,
            ]
        }
        data_set = campaign.get_insights(params=params)
        return data_set[0]

    data_set = get_campaign_stats(campaign_id)
    data_set['cpm'] = str(data_set['cpm'])[:4]
    context = {
        'data_set': data_set,
        'name': 'Campaign Breakdown',
    }
    print(data_set)
    return render(request, 'campaigns_data/data.html', context)
Ejemplo n.º 6
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
Ejemplo n.º 7
0
    def auth(cls):
        """
            Prepare for Ads API calls and return a tuple with act_id
            and page_id. page_id can be None but act_id is always set.
        """
        config = cls.load_config()

        if cls._is_authenticated:
            return config['act_id'], config.get('page_id', None)

        if config['app_id'] and config['app_secret'] \
           and config['act_id'] and config['access_token']:

            FacebookAdsApi.init(
                config['app_id'],
                config['app_secret'],
                config['access_token'],
                config['act_id'],
            )

            cls._is_authenticated = True

            return config['act_id'], config.get('page_id', None)

        else:
            required_fields = set(
                ('app_id', 'app_secret', 'act_id', 'access_token'))

            missing_fields = required_fields - set(config.keys())
            raise FacebookError(
                '\n\tFile config.json needs to have the following fields: {}\n'
                '\tMissing fields: {}\n'.format(
                    ', '.join(required_fields),
                    ', '.join(missing_fields),
                ))
Ejemplo n.º 8
0
def getFacebookAPI(token, act_id, secret):
    token, act_id, secret
    if secret != '-':
        api = FacebookAdsApi.init(access_token=token, app_secret=secret)
    else:
        api = FacebookAdsApi.init(access_token=token)

    return api
Ejemplo n.º 9
0
def get_insights(insight_id=None,
                 timerange=None,
                 fields=None,
                 action_breakdown=False,
                 service=None):
    if service:
        FacebookAdsApi.init(service["app_id"], service["app_secret"],
                            service["access_token"])

    if not timerange:
        today = datetime.datetime.now()
        timerange = {
            "since": (today - datetime.timedelta(days=7)).strftime("%Y-%m-%d"),
            "until": today.strftime("%Y-%m-%d")
        }
    if not fields:
        fields = ("call_to_action_clicks,canvas_avg_view_percent," +
                  "impressions,social_clicks,website_clicks,ctr").split(",")

    params = {
        'time_range': timerange,
    }

    if action_breakdown:
        params['action_breakdown'] = 'action_type'
    else:
        params['time_increment'] = '1'
    cdata = None
    if insight_id.startswith("account/"):
        cdata = get_account_insights(insight_id[8:], fields, params)
    if insight_id.startswith("campaign/"):
        cdata = get_campaign_insights(insight_id[9:], fields, params)
    if insight_id.startswith("adset/"):
        cdata = get_adset_insights(insight_id[6:], fields, params)
    if insight_id.startswith("ad/"):
        cdata = get_ad_insights(insight_id[3:], fields, params)

    if not cdata:
        return {}

    data = None
    if action_breakdown:
        data = {}
        dt = cdata[0]
        for f in fields:
            name = ID_TO_NAME.get(f, f)
            data[name] = dt[f]
    else:
        data = []
        for f in fields:
            v = []
            for cd in cdata:
                date = cd["date_start"]
                v.append([date, cd[f]])
            name = ID_TO_NAME.get(f, f)
            data.append({'name': name, 'values': v})

    return data
Ejemplo n.º 10
0
def download_data():
    """Initializes the FacebookAdsAPI, retrieves the ad accounts and downloads the data"""
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    FacebookAdsApi.init(config.app_id(), config.app_secret(),
                        config.access_token())
    ad_accounts = _get_ad_accounts()
    download_data_sets(ad_accounts)
Ejemplo n.º 11
0
def api_boot(credentials):
    """Function initializing the API connection to Facebook Ads API."""

    application_id = credentials['facebook_ads']['app_id']
    secret = credentials['facebook_ads']['app_secret']
    token = credentials['facebook_ads']['access_token']

    FacebookAdsApi.init(application_id, secret, token)
    print("Facebook Ads API connection successfully initialized.")
Ejemplo n.º 12
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)
Ejemplo n.º 13
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
Ejemplo n.º 14
0
Archivo: main.py Proyecto: Peridian/etl
def facebook_get_service(config):
    '''
    Connects to Facebook Ads platform
    '''
    session = FacebookSession(config['app_id'], config['app_secret'],
                              config['access_token'])
    api = FacebookAdsApi(session)
    FacebookAdsApi.set_default_api(api)
    FacebookAdsApi.init(config['app_id'], config['app_secret'],
                        config['access_token'])
Ejemplo n.º 15
0
    def _deco(*args, **kwargs):
        access_token = None
        try:
            body = json.loads(args[3].decode())
            access_token = body.get('access_token')
        except Exception as ex:
            access_token = conf.facebook.access_token

        finally:
            FacebookAdsApi.init(conf.facebook.app_id, conf.facebook.app_secret, access_token)
            func(*args, **kwargs)
Ejemplo n.º 16
0
def index(request):
    #Initialize a new Session and instanciate an Api object
    my_app_id = '1672585882991034'
    my_app_secret = '38c9b5fba3cf14297b1da57832c45057'
    my_access_token = 'CAAXxNT9peboBAG7SNVFXKOm8NillZAQxQLWXIf2N1PZArEpKZCpMTYZCZAGLZBYq0Gdzq7E1l90I7GlIBN2lLpON37JZBzwuADu7iJk7QByBYyeHAsUr62TTiS9wOBkd9JezaZCZCZB6MnSizo5VftYYVnt5rjQ1gDmTgALKIoPxPZC560jJij88hsvXFu64xaiDjnWTFWqSZAiIPwZDZD' 
    FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)

    #Add after FacebookAdsApi.init
    me = AdUser(fbid='me')
    my_account = me.get_ad_accounts()[0]
    print my_account

    return HttpResponse('Hello from Python!')
Ejemplo n.º 17
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()
Ejemplo n.º 18
0
def webhook(request):
    print(request.method)
    print(request.GET)
    print(request.POST)
    print(request.body)

    challenge = request.GET.get("hub.challenge", "")
    token = request.GET.get("hub.verify_token", "")
    mode = request.GET.get('hub.mode', "")
    msg = 'you are an error!'
    if token == 'abc1234':
        return HttpResponse(challenge)

    leadgen_id = '0007'
    page = None
    try:
        body_unicode = request.body.decode('utf-8')
        body = json.loads(body_unicode)
        entry = body['entry'][0]['changes'][0]['value']

        ad_id = entry['ad_id']
        form_id = entry['form_id']
        leadgen_id = entry['leadgen_id']
        created_time = entry['created_time']
        page_id = entry['page_id']
        adgroup_id = entry['adgroup_id']

        # TODO FB recognize LeadGen
        my_app_id = settings.FB_APP_ID
        my_app_secret = settings.FB_APP_SECRET
        my_access_token = settings.FB_APP_ACCESS_TOKEN

        FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
        fields = []
        params = {}

        page = models.Page.objects.get(page_id=page_id)
        fb_lead = Lead(leadgen_id).api_get(
            fields=fields,
            params=params,
        )
        lead = models.Lead.create_from_fb_lead(fb_lead, page)
        msg = 'lead saved!'
    except Exception as e:
        models.Lead.objects.create(leadgen_id=leadgen_id, page=page)
        print('%s (%s)' % (str(e), type(e)))

        msg = 'lead did not saved :('

    return HttpResponse(msg)
Ejemplo n.º 19
0
        def request_new_fb_pixel():
            from facebookads.api import FacebookAdsApi
            from facebookads.objects import AdsPixel, AdUser

            FacebookAdsApi.init(
                app.config['FB_MY_APP_ID'],
                app.config['FB_MY_APP_SECRET'],
                app.config['FB_MY_ACCESS_TOKEN']
            )

            me = AdUser(fbid='me')
            account = me.get_ad_accounts()[0]
            pixel = account.get_ads_pixels([AdsPixel.Field.code])
            return pixel.get_id(), pixel['code'].decode("utf-8")
Ejemplo n.º 20
0
def download_data():
    """Initializes the FacebookAdsAPI, retrieves the ad accounts and downloads the data"""
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    FacebookAdsApi.init(config.app_id(),
                        config.app_secret(),
                        config.access_token())
    ad_accounts = _get_ad_accounts()
    target_accounts = list(filter(None, config.target_accounts().split(',')))
    if len(target_accounts) > 0:
        logging.info('the app can see %s accounts but the configuration specified only %s target accounts: %s', len(ad_accounts), len(target_accounts), ', '.join(target_accounts))
        ad_accounts = [ad_account for ad_account in ad_accounts if ad_account['account_id'] in config.target_accounts()]
        logging.info('after filtering %s accounts will be downloaded: %s', len(target_accounts), ', '.join(target_accounts))
    download_data_sets(ad_accounts)
Ejemplo n.º 21
0
        def request_new_fb_pixel():
            from facebookads.api import FacebookAdsApi
            from facebookads.objects import AdsPixel, AdUser

            FacebookAdsApi.init(
                app.config['FB_MY_APP_ID'],
                app.config['FB_MY_APP_SECRET'],
                app.config['FB_MY_ACCESS_TOKEN']
            )

            me = AdUser(fbid='me')
            account = me.get_ad_accounts()[0]
            pixel = account.get_ads_pixels([AdsPixel.Field.code])
            return pixel.get_id(), pixel['code'].decode("utf-8")
Ejemplo n.º 22
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
Ejemplo n.º 23
0
 def test_fb(self):
     try:
         config_file = open('./autogen_docs_config.json')
     except IOError:
         print("No config file found, skipping docs tests")
         exit()
     config = json.load(config_file)
     my_app_id = config['app_id']
     my_app_secret = config['app_secret']
     my_access_token = config['access_token']
     FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
     self.assertIsNotNone(FacebookAdsApi.API_VERSION)
     me = objects.AdUser(fbid='me')
     my_accounts = list(me.get_ad_accounts())
     self.assertGreater(len(my_accounts), 0, '账号数大于0个')
     config_file.close()
Ejemplo n.º 24
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)
Ejemplo n.º 25
0
def get_fb_accounts(request):	
	FacebookAccount.objects.all().delete()
	try:
		fb_acc = SocialAccount.objects.get(user_id = request.user.id,provider='facebook')
		fb_tok = SocialToken.objects.get(account=fb_acc)
	except:
		return HttpResponse("error connecting Social Accounts")
	
	#setting the user information
	my_app_id = '1604519246476149'
	my_app_secret = '5a93aee73f1d2856dd542f53e268e483'
	my_access_token = fb_tok.token
	
	#gets the ad accounts in a single, pre-existing facebook account
	FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
	me = objects.AdUser(fbid='me')
	my_accounts = list(me.get_ad_accounts())

	#does it have ad accounts
	if len(my_accounts) == 0:
		return HttpResponse("no Ad Accounts Exist")
	
	#important note, facebook allows us to only check upto 25
	#accounts, we did the privacy note now just need to check if we can
	#increase the amount
	index = 0
	
	for current_account in my_accounts:
		if index == 25:
			break
		
		index = index + 1
		
		fields=[
			AdAccount.Field.account_id,
			AdAccount.Field.name
			]
		
		current_account.remote_read(fields=fields)
		if AdAccount.Field.name == "":
			pass
		account_model = FacebookAccount()
		account_model.account_name = str(current_account[AdAccount.Field.name])
		account_model.account_id = str(current_account[AdAccount.Field.account_id])
		#account_model.report = report_model
		if not account_model.account_name == "":
			account_model.save()
Ejemplo n.º 26
0
def auth(access_token=None):
    if sys.__stdin__.isatty():
        access_token = access_token or config['access_token']
        FacebookAdsApi.init(
            config['app_id'],
            config['app_secret'],
            access_token
        )
    else:
        raise FacebookError(
            "\n\n"
            "## (/ o_o)/ ~  _|___|_ \n"
            "## bootstrap.auth() should only be used in Python's interactive "
            "shell. Try: python -i facebookads/bootstrap.py\n"
            "## Or try using FacebookAdsApi.init()"
            "\n"
        )
Ejemplo n.º 27
0
def auth(access_token=None):
    if sys.__stdin__.isatty():
        access_token = access_token or config['access_token']
        FacebookAdsApi.init(
            config['app_id'],
            config['app_secret'],
            access_token,
            config['act_id'],
        )
    else:
        raise FacebookError(
            "\n\n"
            "## (/ o_o)/ ~  _|___|_ \n"
            "## bootstrap.auth() should only be used in Python's interactive "
            "shell. Try: python -i facebookads/bootstrap.py\n"
            "## Or try using FacebookAdsApi.init()"
            "\n")
Ejemplo n.º 28
0
def hello_world(formId):
    # Facebook app keys
    my_app_id = '<YOUR_FB_APP_ID>'
    my_app_secret = '<YOUR_FB_APP_SECRET>'
    my_access_token = '<YOUR_FB_APP_ACCESS_TOKEN>'

    FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)

    if formId != None:
        form = LeadgenForm(formId)
        leads = form.get_leads()
        email = leads[0]['field_data'][0]['values'][0]
        name = leads[0]['field_data'][1]['values'][0]

        result = add_list_member(email,name);
        return 'Hello,formId:  {0}, {1}!'.format(formId,result)
    return 'hello Fb world'
Ejemplo n.º 29
0
def get_fb_accounts(request):
    FacebookAccount.objects.all().delete()
    try:
        fb_acc = SocialAccount.objects.get(user_id=request.user.id,
                                           provider='facebook')
        fb_tok = SocialToken.objects.get(account=fb_acc)
    except:
        return HttpResponse("error connecting Social Accounts")

    #setting the user information
    my_app_id = ''
    my_app_secret = ''
    my_access_token = fb_tok.token

    #gets the ad accounts in a single, pre-existing facebook account
    FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
    me = objects.AdUser(fbid='me')
    my_accounts = list(me.get_ad_accounts())

    #does it have ad accounts
    if len(my_accounts) == 0:
        return HttpResponse("no Ad Accounts Exist")

    #important note, facebook allows us to only check upto 25
    #accounts, we did the privacy note now just need to check if we can
    #increase the amount
    index = 0

    for current_account in my_accounts:
        if index == 25:
            break

        index = index + 1

        fields = [AdAccount.Field.account_id, AdAccount.Field.name]

        current_account.remote_read(fields=fields)
        if AdAccount.Field.name == "":
            pass
        account_model = FacebookAccount()
        account_model.account_name = str(current_account[AdAccount.Field.name])
        account_model.account_id = str(
            current_account[AdAccount.Field.account_id])
        #account_model.report = report_model
        if not account_model.account_name == "":
            account_model.save()
Ejemplo n.º 30
0
def webhook():
    if request.method == 'GET':
        #https://developers.facebook.com/docs/graph-api/webhooks#setupget
        if request.args.get('hub.verify_token') == FB_VERIFY_TOKEN:
            return request.args.get('hub.challenge')
        else:
            return "Token Verification Failed"
    else:
        FacebookAdsApi.init(FACEBOOK_APP_ID, FACEBOOK_APP_SECRET, FACEBOOK_ACCESS_TOKEN)

        leadgen_info = json.loads(request.data)
        lead_id = leadgen_info['entry'][0]['changes'][0]['value']['leadgen_id']
        lead = Lead(lead_id)
        lead_data = lead.remote_read()

        processLead(lead_data)

        return "Success"
Ejemplo n.º 31
0
    def __init__(self):
        configs = json.load(
            open(
                os.path.join(os.path.dirname(__file__),
                             "facebook_configs.json")))
        self.app_id = configs["app_id"]
        self.app_secret = configs["app_secret"]
        self.access_token = configs["access_token"]
        self.account_ids = configs["account_ids"]
        self.params = configs["insights"]["params"]
        self.fields = configs["insights"]["fields"]
        self.report_local_dir = configs["report_local_dir"]
        self.log_local_dir = configs["log_local_dir"]
        self.reprot_remote_dir = configs["report_remote_dir"]

        try:
            FacebookAdsApi.init(self.app_id, self.app_secret,
                                self.access_token)
        except FacebookError:
            print 'got an error when initializing the api, probably due to access token expiring.'
Ejemplo n.º 32
0
def facebookMain(fbCred, emails_list):
    act_id = fbCred['fb_user_id']
    user_access_token = fbCred['user_token']
    # user_access_token = 'CAAHsB1lutXABADNT3ppqATXZBdUwlfgEViIVlaHl5A14CpZBzoCvWi3qycaVdZAtLPnVFH5QY7EKY1UWYuYzvJptzrFaNcE8OXIOOYVo1hX33h8Ml2M9n5yyd7UJ3PHwOtixi6VgJNJY7sZAYY6b4CwqwCwZAjXir8aKAzmu6GMWZAutDKdSQ482SnawqJRIA7XVgR3K7HGIx1ZA4rOEFra'
    # Login
    FacebookAdsApi.init(my_app_id, my_app_secret, user_access_token)
    ad_account = AdAccount(act_id)

    ### use this to login as yourself (if loged in on this computer)
    # me = AdUser(fbid='me')
    # my_account = me.get_ad_accounts()[0]

    # Push emails to 3Targeting default list
    audiences_list = getCustomAudiences(ad_account)
    my_audiences = findAudienceByName(AUDIENCE_DEFAULT_NAME, audiences_list)
    if my_audiences:
        retVal = LoadCustomAudience(my_audiences[0], f=emails_list, datatype='email')
    else:
        retVal = CreateCustomAudience(ad_account, AUDIENCE_DEFAULT_NAME, description=AUDIENCE_DEFAULT_DESCRIPTION, f=emails_list, datatype='email')
    return retVal
Ejemplo n.º 33
0
def main(access_token, ad_account_id, app_secret, *args, **kwargs):
    FacebookAdsApi.init(access_token=access_token)

    adAccounts = AdAccount(ad_account_id).get_insights(
        fields=['campaign_id'],
        params={
            'level': 'campaign',
            'breakdowns': [],
        },
    )

    insights = []

    with open('marketing.csv', 'w') as csvfile:

        writter = csv.writer(csvfile,
                             delimiter=',',
                             quotechar='|',
                             quoting=csv.QUOTE_MINIMAL)

        writter.writerow(['date', 'campaign_id', 'campaign_name', 'spend'])

        for adAccount in adAccounts:
            campaign = Campaign(adAccount['campaign_id'])

            params = {
                'level': 'ad',
                'date_preset': 'lifetime',
                'time_increment': 1,
                'fields': ['campaign_id', 'spend', 'campaign_name']
            }

            insights += campaign.get_insights(params=params)

        for insight in insights:
            writter.writerow([
                insight['date_start'],
                insight['campaign_id'],
                insight['campaign_name'],
                insight['spend'],
            ])
    def add_ids_to_account(token,
                           aud_id,
                           list_ids_to_add,
                           fb_schema=CustomAudience.Schema.email_hash):
        FacebookAdsApi.init(access_token=token, api_version='v8.0')
        audience = CustomAudience(aud_id)
        listlen = len(list_ids_to_add)

        chunck_size = 30000
        count_added = 0
        for i in range(int(np.ceil(listlen / chunck_size))):
            starti = i * chunck_size
            if (i + 1) * chunck_size < listlen:
                endi = (i + 1) * chunck_size
            else:
                endi = listlen
            list0 = list_ids_to_add[starti:endi]

            count_added += len(list0)
            audience.add_users(fb_schema, list0)
        print("%i IDs added to the audience id: %i" % (count_added, aud_id))
 def generate_record(self):
     my_app_id = '881513028613192'
     my_app_secret = '4252ecaa9b6b11ed5d72ddb8fc2528db'
     my_access_token = 'CAAMhuz7vdEgBAPSuWuBSoCjsV0P45Y3KrqU7y5blqHVyM3XshUN9Dr3ZBNJWZCGJljogD6ZC2XSbqXT4D7I6PVH7isy4EBDqb1U3lB005yIM65ov4fCYUKz3J42kxMfwZBpVZABqBM5vOjZApE6ZC9PvOkRnc7mwZBMFZBnVXBiy37LgJJP2RQrZACpTac2s9INasZD'
     FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
     
     campaign = Campaign('6029907036952')
     campaign.remote_read(fields=[
         Campaign.Field.name,
         Campaign.Field.effective_status,
         Campaign.Field.objective,
     ])
     params = {
         'date_preset': 'last_30_days',
     }
     insights = campaign.get_insights(params=params)
     
     self.write({'name': campaign['name']})
     self.write({'result': insights[0]['actions'][0]['value']})
     self.write({'reach': insights[0]['reach']})
     self.write({'cost': insights[0]['cost_per_total_action']})
     self.write({'amount_spent': insights[0]['spend']})
Ejemplo n.º 36
0
    def initialize(self, app_id=None, app_secret=None, access_token=None):
        """Initialize the FB API"""
        if self.app_id and self.app_secret and self.access_token:

            FacebookAdsApi.init(self.app_id,
                                self.app_secret,
                                self.access_token,
                                api_version=self.__class__.api_version)

            return True

        elif app_id and app_secret and access_token:

            FacebookAdsApi.init(app_id,
                                app_secret,
                                access_token,
                                api_version=self.__class__.api_version)

            return True

        else:
            print('app_id, app_secret, and access_token must be set.')
            return False
Ejemplo n.º 37
0
    def auth(cls):
        """
            Prepare for Ads API calls and return a tuple with act_id
            and page_id. page_id can be None but act_id is always set.
        """
        config = cls.load_config()

        if cls._is_authenticated:
            return config['act_id'], config.get('page_id', None)

        if config['app_id'] and config['app_secret'] \
           and config['act_id'] and config['access_token']:

            FacebookAdsApi.init(
                config['app_id'],
                config['app_secret'],
                config['access_token'],
                config['act_id'],
            )

            cls._is_authenticated = True

            return config['act_id'], config.get('page_id', None)

        else:
            required_fields = set(
                ('app_id', 'app_secret', 'act_id', 'access_token')
            )

            missing_fields = required_fields - set(config.keys())
            raise FacebookError(
                '\n\tFile config.json needs to have the following fields: {}\n'
                '\tMissing fields: {}\n'.format(
                    ', '.join(required_fields),
                    ', '.join(missing_fields),
                )
            )
from __future__ import print_function
from __future__ import unicode_literals
from facebookads.objects import TargetingSearch
from facebookads.api import FacebookAdsApi
from facebookads.exceptions import *

config_file = open('./examples/docs/config.json')
config = json.load(config_file)
config_file.close()

ad_account_id = config['account_id']
access_token = config['access_token']
app_id = config['app_id']
app_secret = config['app_secret']

FacebookAdsApi.init(app_id, app_secret, access_token)

# _DOC open [SEARCH_GEOLOCATION_WITH_COUNTRY]
from facebookads.objects import TargetingSearch
params = {
    'q': 'un',
    'type': 'adgeolocation',
    'location_types': ['country'],
}

resp = TargetingSearch.search(params=params)
print(resp)
# _DOC close [SEARCH_GEOLOCATION_WITH_COUNTRY]

# _DOC open [SEARCH_GEOLOCATION_WITH_REGION]
from facebookads.objects import TargetingSearch
Ejemplo n.º 39
0
repo_dir = os.path.join(this_dir, os.pardir)
sys.path.insert(1, repo_dir)

from facebookads.objects import AdAccount, AsyncJob
from facebookads.api import FacebookAdsApi
import time
import os
import json

this_dir = os.path.dirname(__file__)
config_filename = os.path.join(this_dir, 'config.json')
config_file = open(config_filename)
config = json.load(config_file)
config_file.close()

api = FacebookAdsApi.init(access_token=config['access_token'])
account_id = config['act_id']

account = AdAccount(account_id)

# Both Insights and Reportstats
i_async_job = account.get_insights(params={'level': 'ad'}, async=True)

# Insights
while True:
    job = i_async_job.remote_read()
    print("Percent done: " + str(job[AsyncJob.Field.async_percent_completion]))
    time.sleep(1)
    if job:
        # print "Done!"
        break
Ejemplo n.º 40
0
this_dir = os.path.dirname(__file__)
config_filename = os.path.join(this_dir, os.pardir, os.pardir, 'config.json')

import sys
sys.path.insert(1, os.path.join(this_dir, os.pardir, os.pardir))

config_file = open(config_filename)
config = json.load(config_file)
config_file.close()

from facebookads.api import FacebookAdsApi
from facebookads.objects import ProductCatalog, Product

FacebookAdsApi.init(
    config['app_id'],
    config['app_secret'],
    config['access_token'],
)

if __name__ == '__main__':
    catalog_id = '<INSERT_YOUR_CATALOG_ID_HERE>'
    catalog = ProductCatalog(catalog_id)

    items = []
    for line in sys.stdin.readlines():
        if line.endswith('\n'):
            items.append(line[:-1].split(','))
        else:
            items.append(line.split(','))

    for item in items:
from facebookads.adobjects.user import User
from facebookads.adobjects.page import Page
from facebookads.adobjects.pagepost import PagePost
from facebookads.adobjects.adaccount import AdAccount
from facebookads.adobjects.campaign import Campaign
from facebookads.adobjects.adset import AdSet
from facebookads.adobjects.adcreative import AdCreative
from facebookads.adobjects.ad import Ad
from facebookads.api import FacebookAdsApi

access_token = '<ACCESS_TOKEN>'
app_secret = '<APP_SECRET>'
app_id = '<APP_ID>'
id = '<ID>'
FacebookAdsApi.init(access_token=access_token)

# User get
fields = [
]
params = {
}
user = User(id).get(
  fields=fields,
  params=params,
)
print 'user', user
user_id = user.get_id()
print 'user_id:', user_id, '\n'

# Get page access token and page_id
Ejemplo n.º 42
0
def month_fb_data(request, account_model):

	try:
		fb_acc = SocialAccount.objects.get(user_id = request.user.id,provider='facebook')
		fb_tok = SocialToken.objects.get(account=fb_acc)
	except:
		return HttpResponse("error connecting Social Accounts")
	
	#setting the user information
	my_app_id = '1604519246476149'
	my_app_secret = '5a93aee73f1d2856dd542f53e268e483'
	my_access_token = fb_tok.token
	
	#gets the ad accounts in a single, pre-existing facebook account
	FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
	me = objects.AdUser(fbid='me')
	my_accounts = list(me.get_ad_accounts())

	#does it have ad accounts
	if len(my_accounts) == 0:
		return HttpResponse("no Ad Accounts Exist")
	
	#important note, facebook allows us to only check upto 25
	#accounts, we did the privacy note now just need to check if we can
	#increase the amount
	index = 0
	
	for current_account in my_accounts:
		if index == 25:
			break
		
		index = index + 1
		
		fields=[
			AdAccount.Field.account_id,
			AdAccount.Field.name
			]
		
		current_account.remote_read(fields=fields)
		
		if account_model.account_name == str(current_account[AdAccount.Field.name]):
			break
		
	ad_campaigns = current_account.get_ad_campaigns()
				
	for current_campaign in ad_campaigns:
		
		fields=[
			AdCampaign.Field.name,
    		AdCampaign.Field.status,
    		AdCampaign.Field.id]
				
		params = {
			'date_preset': 'last_30_days'
		}	
		
		try:
			current_campaign.remote_read(fields=fields, params=params)
		except:
			pass
			
		fields = {    			
    		'impressions',
    		'clicks',
		'spend'
    	}
		try:
			data = str(current_campaign.get_insights(fields=fields,params=params))
		except:
			pass
		data = '['+data[12:]
		try:
			ast.literal_eval(data)
			json_string = json.dumps(data)
			parsed_data = json.loads(data)				
		except:
			continue
			
		campaign_model = FacebookCampaign()
		campaign_model.name = str(current_campaign[AdCampaign.Field.name])
		campaign_model.campaign_id = str(current_campaign[AdCampaign.Field.id])
		campaign_model.status = str(current_campaign[AdCampaign.Field.status])
		campaign_model.clicks = int(parsed_data[0]['clicks'])
		campaign_model.impressions = int(parsed_data[0]['impressions'])
		campaign_model.cost = float(parsed_data[0]['spend'])
		if not campaign_model.impressions == 0:
			campaign_model.CTR = round(campaign_model.clicks * 100/campaign_model.impressions,2)
			campaign_model.CPM = round(campaign_model.cost * 1000 / campaign_model.impressions,2)
		if not campaign_model.clicks == 0:
			campaign_model.CPC = round(campaign_model.cost/campaign_model.clicks,2)
		campaign_model.account = account_model
		campaign_model.save()	
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from facebookads.adobjects.adset import AdSet
from facebookads.adobjects.adsinsights import AdsInsights
from facebookads.api import FacebookAdsApi

access_token = '<ACCESS_TOKEN>'
app_secret = '<APP_SECRET>'
app_id = '<APP_ID>'
id = '<ID>'
FacebookAdsApi.init(access_token=access_token)

fields = [
  'impressions',
]
params = {
  'breakdown': 'publisher_platform',
}
print AdSet(id).get_insights(
  fields=fields,
  params=params,
)
from facebookads.api import FacebookAdsApi
from facebookads.objects import AdUser, Campaign, AdAccount, AdSet
from facebookads import FacebookSession, FacebookAdsApi, objects
import os

my_app_id = os.environ['APP_ID']
my_app_secret = os.environ['APP_SECRET']
my_access_token = 'CAAN4vFUE2ZAgBAHaZA6dmP6v4eIxOcV8TtA2crGjLG47ZCEllpjUSUlGFGDIFCX0KQrWBw8OGY9I7vi087ekgpaoldSyaya3HtIJgzC7oR2GQnpE8TfWi8uAB7LqtjMGqtgmvzFXZBTytZCkMDVm9WTC9vBqQZAuxVpj10yyQZC0WigZBaxvKfvG' #Your user access token
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)

"""
17
University of Louisville
id num: act_1006561952727232
18
Ruffino Canada
id num: act_999404050109689
19
Damp Rid
id num: act_946663412050420
20
Stoli Canada
id num: act_971018509614910
21
Beau tea Bar
id num: act_916124548437640
22
Pop Crush
id num: act_933960369987391
23
Ravage
Ejemplo n.º 45
0
def get_report(request):
	
	Campaign.objects.all().delete()
	Account.objects.all().delete()
	
	#check if user is authenticated
	if not request.user.is_authenticated():
		return render(request, 'account/login.html')	

	#setting the user information
	my_app_id = '1604519246476149'
	my_app_secret = '5a93aee73f1d2856dd542f53e268e483'
	current_user = SocialAccount.objects.get(user=request.user, provider='facebook')
	current_token = SocialToken.objects.get(account=current_user)
	my_access_token = current_token.token
  
	FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
	me = objects.AdUser(fbid='me')
	my_accounts = list(me.get_ad_accounts())
  
	if len(my_accounts) == 0:
		return HttpResponse("no Ad Accounts Exist")
	index = 0
  	
	for current_account in my_accounts:
		if index == 5:
			break
		index = index + 1
		
		current_account.remote_read(fields=[
				AdAccount.Field.account_id,
				AdAccount.Field.name,
				AdAccount.Field.amount_spent,
		])
		
		account_model = Account()
		account_model.account_name = str(current_account[AdAccount.Field.name])
		account_model.account_id = str(current_account[AdAccount.Field.account_id])
		account_model.account_cost = str(float(current_account[AdAccount.Field.amount_spent])/100)
		account_model.save()
		
		ad_campaigns = current_account.get_ad_campaigns()
				
		for current_campaign in ad_campaigns:
		
			current_campaign.remote_read(fields=[
			AdCampaign.Field.name,
    			AdCampaign.Field.status,
    			AdCampaign.Field.id,
    		])
			fields = {    			
    			'impressions',
    			'clicks',
    			'cpc'
    		}
			data = str(current_campaign.get_insights(fields=fields))
			data = '['+data[12:]
			try:
				ast.literal_eval(data)
				json_string = json.dumps(data)
				parsed_data = json.loads(data)				
			except:
				continue
			
			campaign_model = Campaign()
			campaign_model.name = str(current_campaign[AdCampaign.Field.name])
			campaign_model.campaign_id = str(current_campaign[AdCampaign.Field.id])
			campaign_model.status = str(current_campaign[AdCampaign.Field.status])
			campaign_model.clicks = int(parsed_data[0]['clicks'])
			campaign_model.cpc = float(parsed_data[0]['cpc'])
			campaign_model.impressions = int(parsed_data[0]['impressions'])
			campaign_model.account = account_model
			campaign_model.save()
	
	return HttpResponse("Good Humes")