예제 #1
0
    def __init__(self, resource_path):
        config_filename = os.path.join(resource_path, 'config.json')
        config_file = open(config_filename)
        config = json.load(config_file)
        config_file.close()

        session = FacebookSession(
            config['app_id'],
            config['app_secret'],
            config['access_token'],
        )
        api = FacebookAdsApi(session)
        FacebookAdsApi.set_default_api(api)

        self.resource_path = resource_path
        self.api = api
        self.account_id = config['act_id']
        self.business_id = config['business_id']
        self.pageId = config['page_id']
예제 #2
0
config_filename = os.path.join(this_dir, 'config.json')

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

### 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:')
    pp.pprint(me.remote_read(fields=[AdUser.Field.permissions]))

    ### Get first account connected to the user
    my_account = me.get_ad_account()

    ### Read connections (in this case, the accounts connected to me)
예제 #3
0
파일: api.py 프로젝트: rcallen89/airbyte
 def __init__(self, account_id: str, access_token: str):
     self._account_id = account_id
     # design flaw in MyFacebookAdsApi requires such strange set of new default api instance
     self.api = MyFacebookAdsApi.init(access_token=access_token,
                                      crash_log=False)
     FacebookAdsApi.set_default_api(self.api)
config_filename = os.path.join(this_dir, 'config.json')

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

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

    # Get my account (first account associated with the user associated with the
    #                 session of the default api)
    my_account = AdAccount.get_my_account()

    print('**** Pausing all active ad campaigns...')

    active_campaigns_iterator = my_account.get_ad_campaigns(
        fields=[
            AdCampaign.Field.status,
            AdCampaign.Field.name,
        ],
        params={
            AdCampaign.Field.status: [AdCampaign.Status.active],
        }
예제 #5
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)
from facebook_business.adobjects.advideo import AdVideo

config_filename = os.path.join(sdk_path, './config.json')

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

### Setup session and api objects
session = FacebookSession(
    config['app_id'],
    config['app_secret'],
    config['access_token'],
)

FacebookAdsApi.set_default_api(FacebookAdsApi(session))

if __name__ == '__main__':
    # create video object
    video = AdVideo(parent_id=config['act_id'])

    video_path = os.path.join(os.path.dirname(__file__), os.pardir,
                              'facebook_business/test/misc/video.mp4')

    # set video fields
    video[AdVideo.Field.filepath] = video_path

    # remote create
    video.remote_create()
    video.waitUntilEncodingReady()