def get_businesses(self): """ Retrieves business account of the user's ad accounts. """ me = AdUser(fbid='me') businesses = me.remote_read(fields=['businesses']) return businesses['businesses']['data']
def get_ad_account_id(fbid): ''' returns the account ID of the first user account ''' usr = AdUser(fbid=fbid) my_account_id = usr.get_ad_accounts()[0]['id'] return my_account_id
def get_ids(): me = AdUser(fbid='me') my_account=me.get_ad_accounts(fields=[AdAccount.Field.name,AdAccount.Field.id]) id_list={} for i in xrange(len(my_account)): id_list[str(my_account[i][AdAccount.Field.id])] = str(my_account[i][AdAccount.Field.name]) logger.info(id_list) return id_list
def get_accounts(self): """ Retrieves and displays a list of the user's ad accounts. """ me = AdUser(fbid='me') return list( me.get_ad_accounts(fields=[ 'id', 'name', 'timezone_name', 'amount_spent', 'currency' ]))
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!')
def _get_ad_accounts() -> [AdAccount]: """Retrieves the ad accounts of the user whose access token was provided and returns them as a list. Returns: A list of ad accounts """ system_user = AdUser(fbid='me') ad_accounts = system_user.get_ad_accounts(fields=[ 'account_id', 'name', 'created_time', 'timezone_offset_hours_utc' ]) return list(ad_accounts)
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")
class FBI(object): """ 包装Facebook Python API的调用接口 """ me = AdUser(fbid='me') # user account def __init__(self, conf): self.app_id = conf.get('FB_Authentication', 'app_id') self.app_secret = conf.get('FB_Authentication', 'app_secret') self._max_repeat_fbi_num = conf.getint('fbi', 'MAX_REPEAT_FBI_NUM') self._max_adset_num_in_one_batch = conf.getint( 'fbi', 'MAX_ADSET_NUM_IN_ONE_BATCH') self._max_bid_ratio = conf.getint('fbi', 'MAX_BID_RATIO') self._wait_seconds = conf.getint('fbi', 'WAIT_SECONDS') def set_session(self, access_token): """' 构造Session,创建API""" self.session = FacebookSession(self.app_id, self.app_secret, access_token) self.api = FacebookAdsApi(self.session) self.access_token = access_token FacebookAdsApi.set_default_api(self.api) def release(self, logger): pass def do_ad_work(self, ad_id, logger): try: pass except Exception as e: logger.exception(e)
def getCurrentAccountId(): return AdUser(fbid='me').remote_read()['id']
# Copyright 2014 Facebook, Inc. # You are hereby granted a non-exclusive, worldwide, royalty-free license to # use, copy, modify, and distribute this software in source code or binary # form for use in connection with the web services and APIs provided by # 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. # _DOC open [ADUSER_GET_ADACCOUNTGROUPS] from facebookads.objects import AdUser me = AdUser(fbid='me') accountgroups = me.get_ad_account_groups() # Output account ID for accountgroup in accountgroups: print(accountgroup) # _DOC close [ADUSER_GET_ADACCOUNTGROUPS]
### Setup session and api objects session = FacebookSession( config.get("Authentication", "app_id"), config.get("Authentication", "app_secret"), config.get("Authentication", "access_token"), ) api = FacebookAdsApi(session) if __name__ == "__main__": FacebookAdsApi.set_default_api(api) print("\n\n\n********** Reading objects example. **********\n") ### Setup user and read the object from the server me = AdUser(fbid="me") ### Read user permissions print(">>> Reading permissions field of user:"******">>> Reading accounts associated with user")
'time_range': { 'since': query_date.strftime(date_fmt), 'until': query_date.strftime(date_fmt) }} # This endpoint does not support querying deleted campaign_parameters = {Campaign.Field.effective_status:[Campaign.Status.archived, Campaign.Status.paused, Campaign.Status.active], 'time_range': { 'since': query_date.strftime(date_fmt), 'until': query_date.strftime(date_fmt), }} ### Setup user and read the object from the server me = AdUser(fbid='me') ### Get all accounts connected to the user my_accounts = me.get_ad_accounts(fields=account_fields) ### List of campaigns that need to be grabed campaigns_list = list() print "Integration data for date %s" % (query_date.strftime(date_fmt)) if grab_campaign: print("Creating campaigns list") for account in my_accounts: if grab_account: print("Retrieving account %s spending") % (account.get('name','Error'))
### Setup session and api objects session = FacebookSession( config['app_id'], config['app_secret'], config['access_token'], ) api = FacebookAdsApi(session) if __name__ == '__main__': FacebookAdsApi.set_default_api(api) print('\n\n\n********** Ad Creation example. **********\n') ### Setup user and read the object from the server me = AdUser(fbid='me') ### Get first account connected to the user my_account = me.get_ad_account() ### Create a Campaign campaign = AdCampaign(parent_id=my_account.get_id_assured()) campaign.update({ AdCampaign.Field.name: 'Seattle Ad Campaign', AdCampaign.Field.objective: AdCampaign.Objective.website_clicks, AdCampaign.Field.status: AdCampaign.Status.paused, }) campaign.remote_create() print("**** DONE: Campaign created:") pp.pprint(campaign)
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) me = AdUser(fbid='me') fields = [ AdAccount.Field.age, #amount of time it's been open, in days AdAccount.Field.name, AdAccount.Field.amount_spent, AdAccount.Field.owner, ] my_accounts = me.get_ad_accounts(fields=fields) # print(my_accounts) num = 1 for acct in my_accounts: print(num) print(acct['name']) print(acct['owner']) print(acct['id']) print("id num: %s" % acct['id']) num += 1
### Setup session and api objects session = FacebookSession( config.get('Authentication', 'app_id'), config.get('Authentication', 'app_secret'), config.get('Authentication', 'access_token'), ) api = FacebookAdsApi(session) if __name__ == '__main__': FacebookAdsApi.set_default_api(api) print('\n\n\n********** Ad Creation example. **********\n') ### Setup user and read the object from the server me = AdUser(fbid='me') ### Get first account connected to the user my_account = me.get_ad_account() ### Create a Campaign campaign = AdCampaign(parent_id=my_account.get_id_assured()) campaign.update({ AdCampaign.Field.name: 'Seattle Ad Campaign', AdCampaign.Field.objective: AdCampaign.Objective.website_clicks, AdCampaign.Field.status: AdCampaign.Status.paused, }) campaign.remote_create() print("**** DONE: Campaign created:") pp.pprint(campaign)
this_dir = os.path.dirname(__file__) repo_dir = os.path.join(this_dir, os.pardir, os.pardir) sys.path.insert(1, repo_dir) from facebookads.objects import * from facebookads.api import * from facebookads.exceptions import * config_file = open(os.path.join(this_dir, 'config.json')) config = json.load(config_file) config_file.close() 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 [ADUSER_GET_ADACCOUNTS] from facebookads.objects import AdUser from facebookads.objects import AdAccount me = AdUser(fbid='me') accounts = me.get_ad_accounts() # Output account ID for account in accounts: print(account) # _DOC close [ADUSER_GET_ADACCOUNTS]
# Copyright 2014 Facebook, Inc. # You are hereby granted a non-exclusive, worldwide, royalty-free license to # use, copy, modify, and distribute this software in source code or binary # form for use in connection with the web services and APIs provided by # 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. # _DOC open [ADUSER_GET_ADACCOUNTS] from facebookads.objects import AdUser me = AdUser(fbid='me') accounts = me.get_ad_accounts() # Output account ID for account in accounts: print(account) # _DOC close [ADUSER_GET_ADACCOUNTS]
### Setup session and api objects session = FacebookSession( config['app_id'], config['app_secret'], config['access_token'], ) api = FacebookAdsApi(session) if __name__ == '__main__': FacebookAdsApi.set_default_api(api) print('\n\n\n********** Reading objects example. **********\n') ### Setup user and read the object from the server me = AdUser(fbid='me') ### Read user permissions print('>>> Reading permissions field of user:'******'>>> Reading accounts associated with user')
from facebookads.api import FacebookAdsApi from facebookads.objects import AdAccount, Ad, Insights, AdUser import datetime my_app_id = '859559060882432' my_app_secret = '814003e084c93a5ac471f6cf49419742' my_access_token = 'EAAMNw7B8xAABALEzf2PEMGcpcVxpZBrcDHYfWUhL1ME9Yx9NkJxq63fowCZAZAOdvZC9oSD4jUFSd8mWUCtPP9osiokkZCcsj9yR0NNtnlNIX5cZCZC6CsR1KNT42WdQKIbFJh94Ag6XWEAn7iHNSIjgGIpzLh1pusZD' FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token) me = AdUser(fbid='me') my_accounts = list(me.get_ad_accounts()) my_account = my_accounts[0] fields = [Insights.Field.campaign_name, Insights.Field.spend] params = { 'time_range': { 'since': str(datetime.date(2015, 1, 1)), 'until': str(datetime.date.today()) }, 'level': 'campaign', 'limit': 1000 }