Beispiel #1
0
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 ''
Beispiel #2
0
    def _define_account(self):
        """
        It takes account and business list or None (befault)
        and extract only relivant AdAccounts.
        Return list of AdAccount
        """
        import time

        if self.account_ids and not self.business_ids:
            return {
                'BusinessID': {
                    'Unknown': [
                        AdAccount('act_' + self._clean_account_id(_id))
                        for _id in self.account_ids
                    ]
                }
            }

        elif not self.account_ids and not self.business_ids:
            me = User(fbid='me')
            return {'BusinessID': {'Unknown': me.get_ad_accounts()}}

        elif not self.account_ids and self.business_ids:
            business = [
                Business(self._clean_account_id(_id))
                for _id in self.business_ids
            ]
            result = {'BusinessID': {}}

            for _business in business:
                result['BusinessID'][_business['id']] = []
                for _account in _business.get_owned_ad_accounts():
                    result['BusinessID'][_business['id']].append(_account)
                time.sleep(60)
            return result

        elif self.account_ids and self.business_ids:
            accounts_in_userlist = [
                AdAccount('act_' + self._clean_account_id(_id))
                for _id in self.account_ids
            ]
            business = [
                Business(self._clean_account_id(_id))
                for _id in self.business_ids
            ]
            result = {'BusinessID': {}}

            for _business in business:
                result['BusinessID'][_business['id']] = []
                for _account in _business.get_owned_ad_accounts():
                    result['BusinessID'][_business['id']].append(_account)

                result['BusinessID'][_business['id']] = [
                    _account for _account in accounts_in_userlist
                    if _account in result['BusinessID'][_business['id']]
                ]
                time.sleep(60)
            return result

        else:
            return None
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
fields = [
  'access_token',
]
params = {
}
pages = User(id).get_accounts(
  fields=fields,
  params=params,
)
	def __init__(self):
		session = FacebookSession(fb_app_id, fb_app_secret, fb_extended_token)
		api = FacebookAdsApi(session)
		FacebookAdsApi.set_default_api(api)
		self.me = User(fbid='me')
		self.getAccounts()
class FacebookAPI:

	def __init__(self):
		session = FacebookSession(fb_app_id, fb_app_secret, fb_extended_token)
		api = FacebookAdsApi(session)
		FacebookAdsApi.set_default_api(api)
		self.me = User(fbid='me')
		self.getAccounts()

	def getAccounts(self):
		all_accounts = list(self.me.get_ad_accounts(
			fields=[AdAccount.Field.account_id, AdAccount.Field.name]))
		self.accounts = [account for account in all_accounts 
			if account['account_id'] in fb_account_ids.values()]

	def getSpendData(self, start_date, end_date, breakdown=None):
		self.setParameters(start_date, end_date, breakdown)
		self.spend_data = []
		for account in self.accounts:
			async_job = account.get_insights(params=self.params, async=True)
			status = async_job.remote_read()
			while status['async_percent_completion'] < 100:
				time.sleep(2)
				status = async_job.remote_read()
			time.sleep(1)
			result = async_job.get_result()
			self.account_name = account['name']
			self.account_id = account['account_id']
			self.compileResult(result)
		return self.spend_data

	def setParameters(self, start_date, end_date, breakdown):
		self.params = {'time_range': {'since': start_date, 'until': end_date}, 
			'fields': [
				AdsInsights.Field.campaign_name,
				AdsInsights.Field.campaign_id,
				AdsInsights.Field.adset_name,
				AdsInsights.Field.adset_id,
				AdsInsights.Field.ad_name,
				AdsInsights.Field.ad_id,
				AdsInsights.Field.spend,
				AdsInsights.Field.inline_link_clicks,
				AdsInsights.Field.unique_actions,
				AdsInsights.Field.impressions,
				AdsInsights.Field.unique_inline_link_clicks,
		 		AdsInsights.Field.reach,
		 		AdsInsights.Field.clicks,
		 		AdsInsights.Field.unique_clicks
		 	],
		'level': 'ad',
		'time_increment': 1}
		if breakdown != None:
			self.params['breakdowns'] = breakdown

	def compileResult(self, result):
		self.targeting_dict = {}
		self.creative_dict = {}
		for row in result:
			data_dict = {}
			data_dict['account_name'] = self.account_name
			data_dict['account_id'] = self.account_id
			data_dict['acquire_source'] = 'Facebook'
			data_dict['date'] = row['date_start']
			data_dict['campaign'] = row['campaign_name']
			data_dict['campaign_id'] = row['campaign_id']
			data_dict['adset'] = row['adset_name']
			data_dict['ad'] = row['ad_name']
			adset_id = row['adset_id']
			ad_id = row['ad_id']
			data_dict['adset_id'] = adset_id
			data_dict['ad_id'] = ad_id
			data_dict['spend'] = float(row['spend'])
			data_dict['clicks'] = int(row['inline_link_clicks'])
			data_dict['impressions'] = int(row['impressions'])
			data_dict['unique_impressions'] = int(row['reach'])
			data_dict['unique_clicks'] = int(row['unique_inline_link_clicks'])
			data_dict['installs'] = 0
			try: 
				data_dict['country'] = row['country']
			except KeyError:
				data_dict['country'] = parseCampaignName(row['campaign_name'], parameter='country')
			try:
				for action in row['unique_actions']:
					if action['action_type'] == 'mobile_app_install':
						data_dict['installs'] = action['value']
						break	
			except KeyError:
				pass
			try:
				self.targeting_dict[adset_id]
			except KeyError:
				self.setTargetingDict(adset_id)
			try:
				self.creative_dict[ad_id]
			except KeyError:
				self.setCreativeDict(ad_id)
			data_dict['title'] = self.creative_dict[ad_id]['title']
			data_dict['ad_copy'] = self.creative_dict[ad_id]['ad_copy']
			data_dict['age_max'] = self.targeting_dict[adset_id]['age_max']
			data_dict['age_min'] = self.targeting_dict[adset_id]['age_min']
			data_dict['gender'] = self.targeting_dict[adset_id]['gender']
			data_dict['user_os'] = self.targeting_dict[adset_id]['user_os']
			data_dict['app_install_state'] = self.targeting_dict[adset_id]['app_install_state']
			data_dict['marketing_type'] = self.targeting_dict[adset_id]['marketing_type']
			data_dict['event_type'] = self.targeting_dict[adset_id]['event_type']
			data_dict['platform'] = self.targeting_dict[adset_id]['platform']
			data_dict['placement'] = self.targeting_dict[adset_id]['placement']
			data_dict['app'] = self.targeting_dict[adset_id]['app']
			self.spend_data.append(data_dict)

	def setCreativeDict(self, ad_id):
		ad = Ad(ad_id)
		creative = ad.get_ad_creatives(fields=[
					AdCreative.Field.title,
					AdCreative.Field.body, 
					])
		creative = creative[0]
		title = creative.get('title', 'Unspecified')
		ad_copy = creative.get('body', 'Unspecified')
		self.creative_dict[ad_id] = \
			{
			'title': title,
			'ad_copy': ad_copy
			}
			
	def setTargetingDict(self, adset_id):
		adset = AdSet(adset_id)
		adset_read = adset.remote_read(fields=['targeting','promoted_object'])
		targeting = adset_read['targeting']
		age_max = targeting['age_max']
		age_min = targeting['age_min']
		user_os = targeting['user_os'][0]
		app_install_state = targeting['app_install_state']
		promoted_object = adset_read['promoted_object']
		store_url = promoted_object['object_store_url']
		app_id = promoted_object['application_id']
		app = fb_app_ids[app_id]
		
		if app_install_state == 'installed':
			marketing_type = 'Remarketing'
		
		if app_install_state == 'not_installed':
			marketing_type = 'UA'
		
		if 'itunes' in store_url:
			platform = 'iOS'
		
		if 'google' in store_url:
			platform = 'Android'
		
		placement = ''
		for row in targeting['publisher_platforms']:
			placement += row + '-'
		placement = placement[:-1]
		event_type = promoted_object.get('custom_event_type', 'Unspecified')
		try: 
			gender = targeting['genders'][0]
			if gender == 1:
				gender = 'M'
			if gender == 2:
				gender = 'F'
		except KeyError:
			gender = 'All'
		self.targeting_dict[adset_id] = \
			{
			'age_max': age_max, 
			'age_min': age_min,
			'gender': gender,
			'user_os': user_os,
			'app_install_state': app_install_state,
			'marketing_type': marketing_type,
			'event_type': event_type,
			'platform': platform,
			'placement': placement,
			'app': app
			}
# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

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

from facebookads.adobjects.user import User
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 = [
]
params = {
}
print User(id).get(
  fields=fields,
  params=params,
)
# Facebook.

# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

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

from facebookads.adobjects.user import User
from facebookads.adobjects.page import Page
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 = []
params = {}
print User(id).get_accounts(
    fields=fields,
    params=params,
)
Beispiel #8
0
config_file = open(config_filename)
config = json.load(config_file)

DAVE = 0
ABACUS = 4

my_app_id = config['app_id']
my_app_secret = config['app_secret']
my_access_token_1 = config['access_token']

session1 = FacebookSession(my_app_id, my_app_secret, my_access_token_1)

api1 = FacebookAdsApi(session1)

FacebookAdsApi.set_default_api(api1)
me = User(fbid='me', api=api1)
my_accounts = list(me.get_ad_accounts())
print(my_accounts)
my_account = my_accounts[ABACUS]

my_account_id = my_account.get_id_assured()
print(my_account_id)

account = AdAccount(my_account_id)
custom_audiences = account.get_custom_audiences(fields=[
    CustomAudience.Field.name, CustomAudience.Field.id,
    CustomAudience.Field.approximate_count
])

our_audiences = []
for audience in custom_audiences:
from facebookads.adobjects.abstractobject import AbstractObject
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)

# Get page access token and page_id
fields = [
    'access_token',
]
params = {}
pages = User(id).get_accounts(
    fields=fields,
    params=params,
)
print 'pages', pages
page_id = pages[0].get_id()
print 'page_id:', page_id, '\n'

# Switch access token to page access token
FacebookAdsApi.init(access_token=pages[0].access_token)
# Page feed create
fields = []
params = {
    'message': 'This is a test value',
}
pagepost = Page(page_id).create_feed(
    fields=fields,
    params=params,