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
 def remote_read(
     self,
     batch=None,
     failure=None,
     fields=None,
     params=None,
     success=None,
     api_version=None,
 ):
     if self[self.__class__.Field.id]:
         _, image_hash = self[self.__class__.Field.id].split(':')
         account = AdAccount(fbid=self.get_parent_id_assured())
         params = {
             'hashes': [
                 image_hash,
             ],
         }
         images = account.get_ad_images(fields=fields, params=params)
         if images:
             self._set_data(images[0]._data)
Example #3
0
app_id = '<APP_ID>'
id = '<AD_ACCOUNT_ID>'
FacebookAdsApi.init(access_token=access_token)

fields = []
params = {
    'name': 'A CPA Ad Set',
    'campaign_id': '<adCampaignLinkClicksID>',
    'daily_budget': '5000',
    'start_time': '2021-04-25T09:42:56-0700',
    'end_time': '2021-05-02T09:42:56-0700',
    'billing_event': 'IMPRESSIONS',
    'optimization_goal': 'REACH',
    'bid_amount': '1000',
    'promoted_object': {
        'page_id': '<pageID>'
    },
    'targeting': {
        'facebook_positions': ['feed'],
        'geo_locations': {
            'countries': ['US']
        }
    },
    'user_os': 'iOS',
    'publisher_platforms': 'facebook',
    'device_platforms': 'mobile',
}
print AdAccount(id).create_ad_set(
    fields=fields,
    params=params,
)
Example #4
0
# 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 facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.campaign import Campaign
from facebook_business.api import FacebookAdsApi

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

fields = []
params = {
    'name': 'My First Campaign',
    'objective': 'PAGE_LIKES',
    'status': 'PAUSED',
}
print AdAccount(id).create_campaign(
    fields=fields,
    params=params,
)
def creation_list():
    FacebookAdsApi.init(access_token=my_access_token)
    fields = ['name', 'video_id']

    return AdAccount(f'act_{ad_account}').get_ad_creatives(fields=fields)
 def api_create(self, parent_id, fields=None, params=None, batch=None, success=None, failure=None, pending=False):
     from facebook_business.adobjects.adaccount import AdAccount
     return AdAccount(api=self._api, fbid=parent_id).create_custom_audience(fields, params, batch, success, failure, pending)
Example #7
0
    def ewah_execute(self, context):
        if not self.test_if_target_table_exists():
            if self.reload_data_from:
                self.data_from = self.reload_data_from

        self.data_from = airflow_datetime_adjustments(self.data_from)
        self.data_until = airflow_datetime_adjustments(self.data_until)

        self.data_from = self.data_from or context['execution_date']
        self.data_until = self.data_until or context['next_execution_date']

        time_range = {
            'since': self.data_from.strftime('%Y-%m-%d'),
            'until': self.data_until.strftime('%Y-%m-%d'),
        }

        FacebookAdsApi.init(**self.credentials)
        params = {
            'time_range': time_range,
            'time_increment': self.time_increment,
            'level': self.level,
            'limit': self.pagination_limit,
        }
        if self.breakdowns:
            params.update({'breakdowns': ','.join(self.breakdowns)})

        for account_id in self.account_ids:
            if self.execution_waittime_seconds:
                self.log.info('Delaying execution by {0} seconds...'.format(
                    str(self.execution_waittime_seconds),
                ))
                now = datetime.now()
                while datetime.now() < \
                    (now + timedelta(seconds=self.execution_waittime_seconds)):
                    time.sleep(1)

            account_object = AdAccount('act_{0}'.format(str(account_id)))
            self.log.info((
                'Requesting data for account_id={0} between {1} and {2}.'
            ).format(
                str(account_id),
                time_range['since'],
                time_range['until'],
            ))

            async_job = account_object.get_insights_async(
                fields=self.insight_fields,
                params=params,
            )
            job_remote_read = async_job.api_get()
            done_status = [
                'Job Completed',
                'Job Failed',
                'Job Skipped',
            ]
            while not (job_remote_read.get('async_status') in done_status):
                self.log.info('Asnyc job completion: {0}% (status: {1})'.format(
                    str(job_remote_read.get('async_percent_completion')),
                    str(job_remote_read.get('async_status')),
                ))
                time.sleep(self.async_job_read_frequency_seconds)
                job_remote_read = async_job.api_get()

            time.sleep(1)
            assert job_remote_read.get('async_status') == 'Job Completed'
            data = self._clean_response_data(async_job.get_result(
                params={'limit': self.pagination_limit},
            ))
            self.upload_data(data)
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()

    #####################
    # Create multiple ads
    #####################

    print('**** Creating multiple ads...')

    # Create my ads (will use batch calling)
    my_ads = ad_creation_utils.create_multiple_website_clicks_ads(
        account=my_account,
        name="Visit Seattle - Many Ads Experiment",
        country='US',
        titles=["Visit Seattle", "Seattle Tourism"],
        bodies=[
            "New York Alki",
Example #9
0
def get_account_ad_performance_for_single_day(
        ad_account: adaccount.AdAccount,
        single_date: datetime) -> adsinsights.AdsInsights:
    """Downloads the ad performance for an ad account for a given day
    https://developers.facebook.com/docs/marketing-api/insights

    Args:
        ad_account: An ad account to download.
        single_date: A single date as a datetime object

    Returns:
        A list containing dictionaries with the ad performance from the report

    """
    fields = [
        'date_start', 'ad_id', 'impressions', 'actions', 'spend',
        'action_values'
    ]

    params = {
        'action_attribution_windows':
        config.action_attribution_windows(),
        # https://developers.facebook.com/docs/marketing-api/insights/action-breakdowns
        'action_breakdowns': ['action_type'],
        # https://developers.facebook.com/docs/marketing-api/insights/breakdowns
        'breakdowns': ['impression_device'],
        'level':
        'ad',
        'limit':
        1000,
        'time_range': {
            'since': single_date.strftime('%Y-%m-%d'),
            'until': single_date.strftime('%Y-%m-%d')
        },
        # By default only ACTIVE campaigns get considered.
        'filtering': [{
            'field':
            'ad.effective_status',
            'operator':
            'IN',
            'value': [
                'ACTIVE', 'PAUSED', 'PENDING_REVIEW', 'DISAPPROVED',
                'PREAPPROVED', 'PENDING_BILLING_INFO', 'CAMPAIGN_PAUSED',
                'ARCHIVED', 'ADSET_PAUSED'
            ]
        }]
    }

    # https://developers.facebook.com/docs/marketing-api/insights/best-practices
    # https://developers.facebook.com/docs/marketing-api/asyncrequests/
    async_job = ad_account.get_insights(fields=fields,
                                        params=params,
                                        is_async=True)
    async_job.remote_read()
    while async_job[
            AdReportRun.Field.async_percent_completion] < 100 or async_job[
                AdReportRun.Field.async_status] != 'Job Completed':
        time.sleep(1)
        async_job.remote_read()
    time.sleep(1)

    ad_insights = async_job.get_result()

    return ad_insights
def main_prog(start_time, end_time, now_time):
    # 起始值
    """
    access_token: 廣告金鑰
    ad_account_id: 廣告帳戶
    data_back: 往前爬多久的資料(幾個月)
    fields: FB_Ads行銷廣告資料
    count: 計算整體while迴圈跑幾次
    stop_flag: 當結束時間已經超過現在時間,使迴圈再跑一次,然後停止迴圈
    """
    access_token = 'EAAJqMzKi2IsBAHrHkHKYzF8Kc1PgskkXweJlxbv2qtNDrIVWdIHPXZBuclZAdFVuCE9tjZAfklwL8JxOmdhcZABjKYJRu9kqXMq3Q2kwBWmdZBjixZCCEkTzMXlrHeW9f3eJoylClpa0FqMUbecNair0MhT74eYZAJtwQxL5aoF4mejBTn2ZBAz6S4FSP6pUy2gZD'
    ad_account_id = 'act_132799196821088'
    count = 0
    stop_flag = 0
    FacebookAdsApi.init(access_token = access_token)

    # Insight API中的fields資料(控制需要的欄位資料)
    fields = [
        'spend',
        'campaign_name',
        'adset_name',
        'campaign_id',
        'ad_name',
        'actions',
        'objective',
        'action_values',  
        'conversions',
        'conversion_values',
        'impressions',
        'ctr',
        'cpm',
    ]

    # 起始資料放置位置
    Campaign_Name = list()
    Adset_Name = list()
    Ad_Name = list()
    Objective = list()
    Amount_Spent = list()
    Amount_Install = list()
    Amount_Purchase = list()
    Purchase_Conversion_Value = list()
    Amount_Subscribe = list()
    Subscribe_Conversion_Value = list()
    Reporting_Date = list()
    CPM = list()
    CTR = list()
    Impressions = list()

    # 起始時間、結束時間、現在爬蟲時間
    start_time, end_time, now_time = start_time, end_time, now_time.date()

    # 比較時間前後順序
    while True:
        # 計算迴圈跑幾次
        count += 1
        # Insight API中的fields資料(控制日期條件、資料的層級)
        # start_time和end_time需要為string(%Y-%m-%d)
        params = {
            'time_range': {
                        'since': start_time.strftime('%Y-%m-%d'),\
                        'until': end_time.strftime('%Y-%m-%d'), 
            }, 
            # level從campaign改成ad
            'level': {'ad'},
            'time_increment': '1',
            # 手動設定的歸因: 7天點擊後(和廣告預設值有落差)
            'action_attribution_windows': {'7d_click'},
        }

        # 廣告帳號獲取廣告Insights資訊
        acc_insights = AdAccount(ad_account_id).get_insights(
            fields = fields,
            params = params,
        )

        # 了解時間怎麼走
        print(start_time.strftime('%Y-%m-%d'))
        print(end_time.strftime('%Y-%m-%d'))
        
        # stop_flag = 0 代表end_time的時間已經超過現在時間(now_time)
        if stop_flag == 0:
        # 起始時間(start_time)和結束時間(end_time),一次取一星期
            start_time = end_time + relativedelta(days = 1)
        else:
            start_time = end_time
        
        # 每次都將結束時間(end_time),往後增加一星期
        end_time = end_time + relativedelta(weeks = 1)

        # 從廣告Inishgts資訊中,清洗、篩選資料
        for acc_insight in acc_insights:     
            campaign_name = ''
            adset_name = ''
            ad_name = ''
            amount_spent = ''
            objective = ''
            amount_subscribe = '' 
            subscribe_conversion_value = ''
            amount_install = '' 
            amount_purchase = ''    
            purchase_conversion_value = ''
            reporting_date = ''          
            cpm = ''
            ctr = ''
            impressions = ''         

            # insights/campaign_name得到 "產品包名稱"
            if 'campaign_name' in acc_insight:
                campaign_name = acc_insight['campaign_name']
                if '⛔️股市爆料同學會' in campaign_name:
                    campaign_name = campaign_name.replace('⛔️', '')

            # insights/adset_name得到 "產品名稱"
            if 'adset_name' in acc_insight:
                adset_name = acc_insight['adset_name']
                
            # insights/adset_name得到 "廣告名稱"
            if 'ad_name' in acc_insight:
                ad_name = acc_insight['ad_name']
            
            # insights/cpm得到 "每一次廣告的曝光成本"
            if 'cpm' in acc_insight:
                cpm = acc_insight['cpm']
                
            # insights/ctr得到 "廣告點擊率"
            if 'ctr' in acc_insight:
                ctr = acc_insight['ctr']

            # insights/ctr得到 "廣告觸及人數"
            if 'impressions' in acc_insight:
                impressions = acc_insight['impressions']
                
            # insights/spend得到 "總支出成本"
            if 'spend' in acc_insight:    
                amount_spent = acc_insight['spend']

            # insights/objective得到 "廣告目標"
            if 'objective' in acc_insight:
                objective = acc_insight['objective']

            # insights/date_stop得到 "報表終止日期"
            if 'date_stop' in acc_insight:
                reporting_date = datetime.strptime(acc_insight['date_stop'], '%Y-%m-%d').strftime('%Y%m%d')

            # insights/actions得到 "軟體下載數/課程購買數"
            if 'actions' in acc_insight:
                for action in acc_insight['actions']:
                    if action['action_type'] == 'mobile_app_install': 
                        amount_install = action['value']
                    if action['action_type'] == 'purchase':
                        amount_purchase = action['value']

            # insights/action_values得到 "購買轉換價值"
            if 'action_values' in acc_insight:
                for ac_values in acc_insight['action_values']:
                    if ac_values['action_type'] == 'omni_purchase':
                        purchase_conversion_value = ac_values['value']

            # insights/conversions得到 "訂閱數"
            if 'conversions' in acc_insight:
                for cv in acc_insight['conversions']:
                    if cv['action_type'] == 'subscribe_total':
                        try:
                            amount_subscribe = cv['7d_click']
                        except:
                            amount_subscribe = cv['value']

            # insights/conversion_values得到 "訂閱轉換價值"             
            if 'conversion_values' in acc_insight:
                for cv_values in acc_insight['conversion_values']:
                    if cv_values['action_type'] == 'subscribe_total':
                        try:
                            subscribe_conversion_value = cv_values['7d_click']
                        except:
                            subscribe_conversion_value = cv_values['value']

            # 將資料以List的形式儲存
            try:
                Campaign_Name.append(campaign_name)
                Adset_Name.append(adset_name)
                Ad_Name.append(ad_name)
                Objective.append(objective)
                Amount_Spent.append(amount_spent)
                Amount_Install.append(amount_install)
                Amount_Purchase.append(amount_purchase)
                Purchase_Conversion_Value.append(purchase_conversion_value)
                Amount_Subscribe.append(amount_subscribe)
                Subscribe_Conversion_Value.append(subscribe_conversion_value)
                Reporting_Date.append(reporting_date)
                CPM.append(cpm)
                CTR.append(ctr)
                Impressions.append(impressions)
                
            except UnicodeEncodeError as e:
                print(e)

# 這裡需要調整一下,想一下演算法,讓這裡能夠完美fit
            # obj_time為目標時間
            # 當目標時間 < 結束時間時,結束時間將為目標時間 
            # if obj_time < end_time:
            #     end_time = obj_time
            #     stop_flag += 1    

            if now_time < end_time:
                end_time = now_time
                stop_flag += 1     

        print('第{}次'.format(count)) 
        # 每次爬蟲完,休息60秒
        time.sleep(60)
        
        # 當成是執行4次時,暫停時間120秒
        if count%4 == 0:
            time.sleep(120)
        
        # 將資料以Dataaframe的方式儲存
        raw_data = {'Campaign_Name': Campaign_Name,
                 'Adset_Name': Adset_Name,
                 'Ad_Name': Ad_Name,
                 'Objective': Objective,
                 'Amount_Spent': Amount_Spent,
                 'Amount_Install': Amount_Install,
                 'Amount_Purchase': Amount_Purchase,
                 'Purchase_Conversion_Value': Purchase_Conversion_Value,
                 'Amount_Subscribe': Amount_Subscribe,
                 'Subscribe_Conversion_Value': Subscribe_Conversion_Value,
                 'CPM': CPM,
                 'CTR': CTR,
                 'Impressions': Impressions,
                 'Reporting_Date': Reporting_Date,}
        df = pd.DataFrame.from_dict(raw_data)
        
        # 當開始時間和結束時間相等時,立即結束程式
        if start_time == end_time:
            break
    return df
Example #11
0
import time

from facebook_business.adobjects.ad import Ad
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.api import FacebookAdsApi

access_token = "EAAHsrmgrz0YBAA9W2ffy3UsB0UgAzkdPaZANA7VYMNHVKZCD80y4CVSGEB33ZCfn367SNB4ogJdLmwwbZAkcyZCpqyubToEUp3QnsZA7Av9rLfhrVFnQqgO9uL6EJQPbTDZA58oqBFjZB2oqVSsECKQP7KnQzlZAdJ1QU4yJVgePz4ZCfK7gvHw5Ay"
account_id = 'act_414637205659315'


api = FacebookAdsApi.init(access_token=access_token)
account = AdAccount(account_id)


def create_ad(name, adset_id, creative_id, status):
    print('Creating Ad: (name={})'.format(name))
    params = {
        Ad.Field.name: name,
        Ad.Field.adset_id: adset_id,
        Ad.Field.creative: {
            'creative_id': creative_id,
        },
        Ad.Field.status: status,
    }

    ad = Ad(parent_id=account_id, api=api)
    # ad = ad.remote_create(params=params)
    # print(ad)
    return ad

ad_list = []
Example #12
0
    def fetch(self, target_date):
        # init FacebookAdsApi
        FacebookAdsApi.init(self.config['APP_ID'], self.config['APP_SECRET'],
                            self.config['ACCESS_TOKEN'])
        my_account = AdAccount('act_' + self.config['AD_ACCOUNT_ID'])

        fields = [
            AdsInsights.Field.impressions,
            AdsInsights.Field.clicks,
            AdsInsights.Field.conversions,
        ]

        target_date_str = target_date.strftime('%Y-%m-%d')
        params = {
            'time_range': {
                'since': target_date_str,
                'until': target_date_str,
            },
        }

        # data fetch
        response = my_account.get_insights(fields=fields, params=params)

        # dummy response for develop
        response = {
            "data": [
                {
                    "impressions": "200",
                    "clicks": "60",
                    "conversions": "20",
                    "date_start": target_date_str,
                    "date_stop": target_date_str,
                },
                {
                    "impressions": "300",
                    "clicks": "90",
                    "conversions": "30",
                    "date_start": target_date_str,
                    "date_stop": target_date_str,
                },
            ],
            "paging": {
                "cursors": {
                    "before": "MAZDZD",
                    "after": "MAZDZD",
                }
            }
        }

        ret = []
        for row in response['data']:
            ret.append({
                'date': row['date_stop'],
                'format': 'format',
                'impression': int(row['impressions']),
                'click': int(row['clicks']),
                'conversion': int(row['conversions']),
                'used_budget': int('10'),
            })

        return FacebookResponse('ok', ret)
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.adset import AdSet
import csv 
from matplotlib import pyplot as plt 
import json
import os
plt.rcParams.update({'figure.max_open_warning': 0})
import calendar
import time
import numpy as np

my_app_id = '2725706687661342'
my_app_secret = '259338521f39f49cacef7db0aae1ae5d'
my_access_token = 'EAAmvBArhRR4BADniGjZCgCluOLCRF7TolKU5UriWVmrBH6OUlBypAQgnx0nyPf2wimk3R4bRRQuuLzCbsR82a3DWtYnFMp8ndYTJbdLZBZBHgQQesfC1WjPYeLAYc4T4WoLZBL70olMwpOZBtH7gU7DWclHfDa2xGaMDZAhFOlw4D1SQZCl43F0'
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
my_account = AdAccount('act_2408768415887341')

params = {
    'level': 'campaign',
    'date_preset': 'this_week_sun_today'
    # 'date_preset': 'this_week_sun_today'
    
}
fields = [
    'campaign_id',
    'campaign_name',
    'impressions',
    'spend',
    'impressions',
    'date_start',
    'date_stop',
    params=params,
)
print 'adaccounts', adaccounts
adaccount_id = adaccounts[0].get_id()
print 'adaccount_id:', adaccount_id, '\n'

# AdCampaign create
fields = []
params = {
    'name': 'My campaign',
    'objective': 'LINK_CLICKS',
    'status': 'PAUSED',
    'special_ad_categories': [],
}
adcampaign = AdAccount(adaccount_id).create_campaign(
    fields=fields,
    params=params,
)
print 'adcampaign', adcampaign
adcampaign_id = adcampaign.get_id()
print 'adcampaign_id:', adcampaign_id, '\n'

# AdSet create
fields = []
params = {
    'name': 'My Reach Ad Set',
    'optimization_goal': 'REACH',
    'billing_event': 'IMPRESSIONS',
    'bid_amount': '2',
    'daily_budget': '1000',
    'campaign_id': adcampaign_id,
    'targeting': {
    return df2


my_app_id = "********"
my_app_secret = "********"
my_access_token = "********"

FacebookAdsApi.init(my_app_id,
                    my_app_secret,
                    my_access_token,
                    api_version='v7.0')

start = "2020-04-22"
end = "2020-05-03"

act = AdAccount('act_********')
params = {
    'time_increment': 1,
    'time_range': {
        'since': start,
        'until': end
    },
    'level': 'ad',
    'breakdowns':
    ['publisher_platform', 'platform_position', 'device_platform']
}

fields = [
    'ad_name', 'adset_name', 'campaign_name', 'impressions', 'clicks',
    'video_thruplay_watched_actions', 'video_continuous_2_sec_watched_actions',
    'video_p25_watched_actions', 'video_p50_watched_actions',
Example #16
0
access_token = ''
app_secret = ''
app_id = ''
ad_account_id = 'act_'
page_id = ''

FacebookAdsApi.init(access_token=access_token)

# create camp
params = {
    'name': 'ENTER CAMPAIGN NAME HERE',
    'objective': 'POST_ENGAGEMENT',
    'status': 'ACTIVE',
}
campaign_result = AdAccount(ad_account_id).create_campaign(params=params)

# create adset
adset = AdSet(parent_id=ad_account_id)
adset.update({
    'name': 'ENTER ADSET NAME HERE',
    'campaign_id': campaign_result["id"],
    'daily_budget': 150,
    'billing_event': 'IMPRESSIONS',
    'optimization_goal': 'REACH',
    'bid_amount': 10,
    'targeting': {
        'geo_locations': {
            'countries': {'TR'}
        },
        'publisher_platforms': 'facebook'
from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.adlabel import AdLabel
from facebook_business.adobjects.adset import AdSet
from facebook_business.adobjects.ad import Ad
from facebook_business.adobjects.adsinsights import AdsInsights
from facebook_business.adobjects.campaign import Campaign

facebook_app_id = '<your facebook app id>'
ad_account_id = '<your facebook ad account id>'
FacebookAdsApi.init(facebook_app_id, facebook_app_secret_ads_management,
                    facebook_access_token_ads_management)
my_account = AdAccount('act_' + ad_account_id)


def daily_campaign_data():
    yesterday = datetime.today() - timedelta(days=1)
    yesterday = datetime.strftime(yesterday, '%Y-%m-%d')
    campaign_fields = {
        'account_id', 'id', 'name', 'updated_time', 'created_time', 'status',
        'daily_budget', 'lifetime_budget'
    }

    logging.info('Pulling the daily campaign data of {}'.format(yesterday))

    campaign_params = {
        'level':
        'campaign',
        'filtering': [{
            'field': 'effective_status',
            'operator': 'IN',
Example #18
0
from facebook_business.adobjects.adreportrun import AdReportRun
from facebook_business.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'}, is_async=True)

# Insights
while True:
    job = i_async_job.api_get()
    print("Percent done: " +
          str(job[AdReportRun.Field.async_percent_completion]))
    time.sleep(1)
    if job:
        print("Done!")
        break

print(i_async_job.get_result())
Example #19
0
def getCampaignInfo(date):

    # Get connected with Facebook
    if os.path.exists('./facebook_credential.json'):
        credentials = json.load(open('facebook_credential.json'))
    else:
        print("Credential file not exist. Please check.")

    access_token = credentials['access_token']
    ad_account_id = credentials['ad_account_id']
    app_secret = credentials['app_secret']
    app_id = credentials['app_id']

    FacebookAdsApi.init(access_token=access_token)

    # Set columns
    fields = [
        'campaign_name',
        'impressions',
        'clicks',
        'spend',
        'cpc',
        'ctr',
        'actions',  #onsite_conversion.lead_grouped = leads on Facebook
        'action_values'
    ]

    # Set filter for both active and inactive campaigns
    active_filter = {
        'field': 'campaign.delivery_info',
        'operator': 'IN',
        'value': ['active']
    }
    inactive_filter = {
        'field': 'campaign.delivery_info',
        'operator': 'NOT_IN',
        'value': ['active']
    }

    # Set parameters
    active_params = {
        'time_range': {
            'since': date,
            'until': date
        },
        'filtering': [active_filter],
        'level': 'campaign',
        'breakdowns': []
    }

    inactive_params = {
        'time_range': {
            'since': date,
            'until': date
        },
        'filtering': [inactive_filter],
        'level': 'campaign',
        'breakdowns': [],
    }

    res_active = AdAccount(ad_account_id).get_insights(fields=fields,
                                                       params=active_params)

    res_inactive = AdAccount(ad_account_id).get_insights(
        fields=fields, params=inactive_params)

    return res_active, res_inactive
Example #20
0

fields = [

]
params = {
    'name': 'Sample Creative',

    'object_story_spec': {'page_id': PAGE_ID_PIETONNI,
                          'link_data': {'image_hash': hashedImage(), 'link': 'https://londonist.com/london/news/oxford-street',
                                        'message': 'Oxford Street is going car-free! The plan is aimed at tackling growing air quality concerns and congestion at peak travel level',
                                        'title': 'Oxford Street is going car-free! The plan is aimed at tackling growing air quality concerns and congestion at peak travel level'}},
}
print('positive')
print(AdAccount(my_account_id).create_ad_creative(
    fields=fields,
    params=params,
))

############################################"Test2_New_Nutri_Ad_Experiment1_L1_D2_negative"####################################################
def hashedImage():
  image = AdImage(parent_id=my_account_id)
  image[AdImage.Field.filename] = 'negative.jpg'
  image.remote_create()
  hashed = image[AdImage.Field.hash]
  return   hashed


# Output image Hash


Example #21
0
from datetime import datetime, timedelta
from functools import partial

import pandas as pd
import numpy as np
from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.ad import Ad
from facebook_business.adobjects.adset import AdSet
from facebook_business.adobjects.adaccount import AdAccount

AD_ACC_ID = os.environ.get("AD_ACC_ID")

# Cell
FacebookAdsApi.init(APP_ID, APP_SECRET, TOKEN)
account = AdAccount(AD_ACC_ID)

# Cell
COLUMNS = [
    "Ad Name", "Ads Followers Change", "% (Clicks)", "% (Impressions)",
    "Cost Per Follow", "Delivery Type", "Clicks (All)", "Link Clicks",
    "CPC (All)", "CPC (Cost per Link Click)", "CTR (All)",
    "CPM (Cost per 1,000 Impressions)", "Amount Spent (USD)", "Impressions",
    "Reach", "Post Reactions", "Post Shares", "Video Average Play Time",
    "Video Plays at 50%", "Video Plays at 75%", "Video Plays at 95%"
]


# Cell
def get_insights(date: str) -> Dict:
    return account.get_insights(fields=[
Example #22
0
def getAds(my_app_id, my_app_secret, my_access_token, account_id):
    FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
    account = AdAccount(account_id)
    ad_set = account.get_ad_sets()
    print(ad_set)
Example #23
0
def get_data_from_api(start_date,end_date):

    Campaign_ID = []
    Page_ID = []
    Amount_Spent = []
    # Page_Name = []
    
    campaigns_all = {"Campaign_id":[],
                    "Page_id":[],
                    "Amount_spent":[],
                    }
    page_id = None
    pixel_id = None


    access_token = 'EAAUbBhxccoEBALbQCDsVMLzwdZBZAZBXApZA0t1Qy3GtjZALfs89EMFhH62f5Kp7FWvshYRTrur41B14vICAgTf1TOba8qx7SBPejdqR4gZBqZCGDo0l0WvsmzubUKKqHncpyqhSpUqcO7O0WJsB1PnSZAMY7t7awukDuIYwrisTYwZDZD'
    bussiness_account_id = '1517651558352959'
    app_secret = '7a3ad485c97dbf45ee83562bc0dcb570'
    app_id = '1437087943127681'
    start_time = datetime.datetime.now()

    FacebookAdsApi.init(app_id, app_secret, access_token)

    business =  Business(bussiness_account_id)

    # Get all ad accounts on the business account
    my_ad_account =business.get_owned_ad_accounts(fields=[AdAccount.Field.id])

    # fields = [
    #     'name',
    #     'objective',
    #     # 'spend',

    # ]
    # params = {
    #     'time_range':{'since':start_date,'until':end_date},
    #     # 'date_preset':'yesterday',
    #     'effective_status': ['ACTIVE','PAUSED'],    

    # }

    # Iterate through the adaccounts
    for account in my_ad_account:
        print(len(my_ad_account))
        # i = 0
        # Create an addaccount object from the adaccount id to make it possible to get insights
        tempaccount = AdAccount(account[AdAccount.Field.id])
        # campaigns_iter = tempaccount.get_campaigns(fields = fields, params = params)
        # CAMPAIGN_UPDATE_BATCH_LIMIT = 5

        # for campaigns in generate_batches(campaigns_iter,CAMPAIGN_UPDATE_BATCH_LIMIT):
        #     api_batch = api.new_batch()
                
        #     for i, campaign in enumerate(campaigns_iter):
        #         adset = AdAccount(campaign[Campaign.Field.id]).get_ad_sets(
        #                                     fields=['id', 'name', 'promoted_object'], 
        #                                     params = {})
        #         print(adset)
        #     api_batch.execute()    
            
            
            # spend_val.append(campaign[Campaign.Field.id])
            # print(campaign, i)
        
        
        # print(spend_val)

        # print(set(spend_val))
        


        # Grab insight info for all ads in the adaccount
        account_data = tempaccount.get_insights(params={
                                                        # 'time_increment':'1',
                                                        'time_range':{'since':start_date, 'until':end_date},
                                                        'level':'campaign',
                                                        },
                                    
                                        fields=[
                                            AdsInsights.Field.campaign_id,
                                            AdsInsights.Field.campaign_name,
                                            AdsInsights.Field.spend,

                                            ]
        )
       
        for campaign in account_data:

            try:
                #Check if you reached 75% of the limit, if yes then back-off for 5 minutes (put this chunk in your 'for ad is ads' loop, every 100-200 iterations)
                # if (check_limit(bussiness_account_id,access_token)>75):
                #     print('75% Rate Limit Reached. Cooling Time 5 Minutes.')
                #     logging.debug('75% Rate Limit Reached. Cooling Time 5 Minutes.')
                #     time.sleep(300)

                #ID OF Campaign
                # if campaign!=[]:
                # print(campaign)
                # print(len(account_data))
                campaign_id = campaign[AdsInsights.Field.campaign_id]
                campaign_spent_val = campaign[AdsInsights.Field.spend]
                # print(campaign_spent_val)
                my_camp = Campaign(campaign_id)
                print(my_camp)
                #Campaign Insights Object
                # campaign_spent_obj = my_camp.get_insights(params={}, fields=[AdsInsights.Field.spend])
                # campaign_spent = campaign_spent_obj[Campaign.Field.spend] 
                # print(campaign_spent_obj)
                #Campaign Spend value
                
                # campaigns_all["Amount_spent"].append(campaign_spent_val)

                #AdSet Object
                adset = AdAccount(my_camp[Campaign.Field.id]).get_ad_sets(
                                                fields=['id', 'name', 'promoted_object'], 
                                                params = {})
                #page and Pixel ID from Adset
                if 'page_id' in adset[0][AdSet.Field.promoted_object]:
                    page_id = adset[0][AdSet.Field.promoted_object][AdPromotedObject.Field.page_id]  
                    campaigns_all["Page_id"].append(page_id)
                    Page_ID.append(page_id)
                    # page_req = rq.head('https://facebook.com/'+page_id)
                    # print(page_req.headers)
                    # # for page in Page_ID:
                    # print(Page(page_id).api_get(fields=['name'],params={}))
                elif 'pixel_id' in adset[0][AdSet.Field.promoted_object]:
                    pixel_id = adset[0][AdSet.Field.promoted_object][AdPromotedObject.Field.pixel_id]
                    campaigns_all["Page_id"].append(pixel_id)
                    Page_ID.append(pixel_id)
                    
                else:
                    continue
 
 
                # Add Values to Dictionary
                campaigns_all["Campaign_id"].append(campaign_id)
                campaigns_all["Amount_spent"].append(campaign_spent_val)
                Campaign_ID.append(campaign_id)
                Amount_Spent.append(campaign_spent_val)                   
                # print(campaigns_all)
                time.sleep(2)  

            except KeyError as e:
                print(e)
                continue

            except Exception as e:
                print(e)
                if FacebookRequestError.api_error_code(e) == 17:
                    print(campaigns_all)
                    print("Limit Reached")
                    print("Wait 5 minutes for cooldown")
                    time.sleep(300)
                    continue
            
                

            finally:
                end_time = datetime.datetime.now()
                diff = end_time - start_time
                print(diff)
        
        tuples_of_data = list(zip(Campaign_ID,Page_ID,Amount_Spent))
        sum_amount = compare_values(tuples_of_data)
        
        print(sum_amount)
        # print(diff.total_seconds())

    return campaigns_all,sum_amount
def list_creative():
    FacebookAdsApi.init(access_token=my_access_token)
    return AdAccount(f'act_{ad_account}').get_ad_creatives()
Example #25
0
def device():
    today = datetime.date.today()
    fields1 = [
        'account_name', 'campaign_name', 'campaign_id', 'reach',
        'cost_per_action_type:post_reaction', 'action:post_reaction',
        'unique_actions:post_reaction', 'inline_link_clicks',
        'action:post_engagement', 'unique_outbound_clicks:outbound_click',
        'cost_per_action_type:post_engagement', 'ctr', 'cost_per_unique_click',
        'action:landing_page_view', 'unique_actions:landing_page_view',
        'action:offsite_conversion.custom.281094269070676',
        'cost_per_action_type:page_engagement',
        'cost_per_unique_action_type:page_engagement', 'device_platform',
        'action:offsite_conversion.custom.280669215754025',
        'cost_per_unique_action_type:link_click', 'website_ctr:link_click',
        'cpc', 'unique_actions:link_click', 'unique_actions:page_engagement',
        'date_stop', 'unique_inline_link_clicks',
        'cost_per_action_type:link_click', 'inline_post_engagement',
        'unique_inline_link_click_ctr',
        'cost_per_unique_action_type:landing_page_view',
        'unique_link_clicks_ctr', 'action:page_engagement',
        'cost_per_inline_post_engagement', 'action:link_click',
        'cost_per_outbound_click:outbound_click', 'unique_ctr',
        'cost_per_action_type:offsite_conversion.custom.280669215754025',
        'impressions', 'unique_actions:post_engagement',
        'cost_per_unique_action_type:post_engagement', 'inline_link_click_ctr',
        'cost_per_action_type:landing_page_view',
        'cost_per_action_type:offsite_conversion.custom.281094269070676',
        'clicks', 'cost_per_unique_inline_link_click',
        'outbound_clicks:outbound_click', 'date_start',
        'instant_experience_clicks_to_open', 'unique_clicks',
        'cost_per_unique_outbound_click:outbound_click', 'frequency',
        'instant_experience_outbound_clicks',
        'outbound_clicks_ctr:outbound_click',
        'unique_outbound_clicks_ctr:outbound_click', 'spend', 'cpp',
        'instant_experience_clicks_to_start', 'cpm', 'objective',
        'cost_per_inline_link_click'
    ]

    for x in range(1, 8):
        date1 = today - datetime.timedelta(days=x)
        date1 = str(date1)
        arr = date1.split("-")
        year = arr[0]
        month = arr[1]
        params = {
            'time_range': {
                'since': date1,
                'until': date1
            },
            'breakdowns': ['device_platform']
        }
        fields = [
            'account_name',
            'campaign_name',
            'campaign_id',
            'reach',
            'frequency',
            'impressions',
            'clicks',
            'cpm',
            'ctr',
            'spend',
            'actions',
            'canvas_avg_view_percent',
            'canvas_avg_view_time',
            'conversion_rate_ranking',
            'conversion_values',
            'conversions',
            'cost_per_action_type',
            'cost_per_conversion',
            'cost_per_estimated_ad_recallers',
            'cost_per_inline_link_click',
            'cost_per_inline_post_engagement',
            'cost_per_outbound_click',
            'cost_per_thruplay',
            'cost_per_unique_action_type',
            'cost_per_unique_click',
            'cost_per_unique_inline_link_click',
            'cost_per_unique_outbound_click',
            'cpc',
            'cpp',
            'engagement_rate_ranking',
            'estimated_ad_recall_rate',
            'estimated_ad_recallers',
            'full_view_impressions',
            'full_view_reach',
            'inline_link_click_ctr',
            'inline_link_clicks',
            'inline_post_engagement',
            'instant_experience_clicks_to_open',
            'instant_experience_clicks_to_start',
            'instant_experience_outbound_clicks',
            'mobile_app_purchase_roas',
            'objective',
            'outbound_clicks',
            'outbound_clicks_ctr',
            'place_page_name',
            'quality_ranking',
            'social_spend',
            'unique_actions',
            'unique_clicks',
            'unique_ctr',
            'unique_inline_link_click_ctr',
            'unique_inline_link_clicks',
            'unique_link_clicks_ctr',
            'unique_outbound_clicks',
            'unique_outbound_clicks_ctr',
            'video_30_sec_watched_actions',
            'video_avg_time_watched_actions',
            'video_p100_watched_actions',
            'video_p25_watched_actions',
            'video_p50_watched_actions',
            'video_p75_watched_actions',
            'video_p95_watched_actions',
            'video_play_actions',
            'video_play_curve_actions',
            'video_thruplay_watched_actions',
            'website_ctr',
        ]

        f = open("account_id",
                 "r")  #importing the account id from external file
        acc = f.read()
        my_account = AdAccount(acc)
        campaignids = my_account.get_campaigns()
        #print(campaignids)
        list_d = []
        l = []
        y = 0
        for i in range(len(campaignids)):
            #print("loop ran ", i)
            try:
                c_id = campaignids[i]["id"]
                campaign = Campaign(c_id)
                camp_insights = campaign.get_insights(fields=fields,
                                                      params=params)
                j = 0
                #print(camp_insights)
                dic_camp = {}
                for item in camp_insights:  #converting to dictionary
                    dic_camp = dict(item)
                    #print("converted to dictionary")
                #print(dic_camp)
                #flattening of data

                try:
                    for each_action in dic_camp["actions"]:
                        dic_camp[
                            "action:" +
                            each_action['action_type']] = each_action['value']
                    del dic_camp["actions"]
                except KeyError:
                    continue

                try:
                    for each_action in dic_camp["cost_per_action_type"]:
                        dic_camp[
                            "cost_per_action_type:" +
                            each_action['action_type']] = each_action['value']
                    del dic_camp["cost_per_action_type"]
                except KeyError:
                    continue
                try:
                    for each_action in dic_camp["cost_per_outbound_click"]:
                        dic_camp[
                            "cost_per_outbound_click:" +
                            each_action['action_type']] = each_action['value']
                    del dic_camp["cost_per_outbound_click"]
                except KeyError:
                    continue
                try:
                    for each_action in dic_camp["cost_per_unique_action_type"]:
                        dic_camp[
                            "cost_per_unique_action_type:" +
                            each_action['action_type']] = each_action['value']
                    del dic_camp["cost_per_unique_action_type"]
                except KeyError:
                    continue
                try:
                    for each_action in dic_camp[
                            "cost_per_unique_outbound_click"]:
                        dic_camp[
                            "cost_per_unique_outbound_click:" +
                            each_action['action_type']] = each_action['value']
                    del dic_camp["cost_per_unique_outbound_click"]
                except KeyError:
                    continue
                try:
                    for each_action in dic_camp["outbound_clicks"]:
                        dic_camp[
                            "outbound_clicks:" +
                            each_action['action_type']] = each_action['value']
                    del dic_camp["outbound_clicks"]
                except KeyError:
                    continue
                try:
                    for each_action in dic_camp["outbound_clicks_ctr"]:
                        dic_camp[
                            "outbound_clicks_ctr:" +
                            each_action['action_type']] = each_action['value']
                    del dic_camp["outbound_clicks_ctr"]
                except KeyError:
                    continue

                try:
                    for each_action in dic_camp["unique_actions"]:
                        dic_camp[
                            "unique_actions:" +
                            each_action['action_type']] = each_action['value']
                    del dic_camp["unique_actions"]
                except KeyError:
                    continue
                try:
                    for each_action in dic_camp["unique_outbound_clicks"]:
                        dic_camp[
                            "unique_outbound_clicks:" +
                            each_action['action_type']] = each_action['value']
                    del dic_camp["unique_outbound_clicks"]
                except KeyError:
                    continue
                try:
                    for each_action in dic_camp["unique_outbound_clicks_ctr"]:
                        dic_camp[
                            "unique_outbound_clicks_ctr:" +
                            each_action['action_type']] = each_action['value']
                    del dic_camp["unique_outbound_clicks_ctr"]
                except KeyError:
                    continue
                try:
                    for each_action in dic_camp["website_ctr"]:
                        dic_camp[
                            "website_ctr:" +
                            each_action['action_type']] = each_action['value']
                    del dic_camp["website_ctr"]
                except KeyError:
                    continue
                #print(dic_camp)

                list_d.append(dic_camp)

            except IndexError:
                continue
        if list_d:
            filename1 = "FacebookAds/landing_device/" + "device_" + date1 + ".csv"
            filename2 = "FacebookAds/processing_device/csv/" + year + "/" + month + "/" + "publisher_device_" + date1 + ".csv"
            importtos3.write_to_s3(list_d, fields1, 'paragon-datalake',
                                   filename1, filename2)
    return list_d
    def test_get_adaccount(self):
        with warnings.catch_warnings(record=True) as warning:
            self.mock_response.status_code = StatusCode.SUCCESS
            self.mock_response._content = str.encode(
                '{'
                '"' + str(FieldName.ACCOUNT_ID) + '":"' +
                str(TestValue.ACCOUNT_ID) + '",'
                '"' + str(FieldName.ACCOUNT_STATUS) + '":' +
                str(TestValue.ACCOUNT_STATUS) + ','
                '"' + str(FieldName.AGE) + '":"' + str(TestValue.AGE) + '",'
                '"' + str(FieldName.AGENCY_CLIENT_DECLARATION) + '":' +
                str(TestValue.AGENCY_CLIENT_DECLARATION) + ','
                '"' + str(FieldName.AMOUNT_SPENT) + '":"' +
                str(TestValue.AMOUNT_SPENT) + '",'
                '"' + str(FieldName.BALANCE) + '":"' + str(TestValue.BALANCE) +
                '",'
                '"' + str(FieldName.BUSINESS) + '":' +
                str(TestValue.BUSINESS) + ','
                '"' + str(FieldName.BUSINESS_CITY) + '":"' +
                str(TestValue.BUSINESS_CITY) + '",'
                '"' + str(FieldName.CAPABILITIES) + '":"' +
                str(TestValue.CAPABILITIES) + '",'
                '"' + str(FieldName.CURRENCY) + '":"' +
                str(TestValue.CURRENCY) + '",'
                '"' + str(FieldName.DISABLE_REASON) + '":' +
                str(TestValue.DISABLE_REASON) + ','
                '"' + str(FieldName.EXTENDED_CREDIT_INVOICE_GROUP) + '":' +
                str(TestValue.EXTENDED_CREDIT_INVOICE_GROUP) + ','
                '"' + str(FieldName.FAILED_DELIVERY_CHECKS) + '":' +
                str(TestValue.FAILED_DELIVERY_CHECKS) + ','
                '"' + str(FieldName.HAS_PAGE_AUTHORIZED_ADACCOUNT) + '":"' +
                str(TestValue.HAS_PAGE_AUTHORIZED_ADACCOUNT) + '",'
                '"' + str(FieldName.TOS_ACCEPTED) + '":' +
                str(TestValue.TOS_ACCEPTED) + ''
                '}')

            self.mock_request.return_value = self.mock_response

            fields = [
                FieldName.ACCOUNT_ID,
                FieldName.ACCOUNT_STATUS,
                FieldName.AGE,
                FieldName.AGENCY_CLIENT_DECLARATION,
                FieldName.BALANCE,
                FieldName.BUSINESS,
                FieldName.BUSINESS_CITY,
                FieldName.CAPABILITIES,
                FieldName.CURRENCY,
                FieldName.DISABLE_REASON,
                FieldName.EXTENDED_CREDIT_INVOICE_GROUP,
                FieldName.FAILED_DELIVERY_CHECKS,
                FieldName.HAS_PAGE_AUTHORIZED_ADACCOUNT,
                FieldName.TOS_ACCEPTED,
            ]
            params = {}

            account = AdAccount(TestValue.ACCOUNT_ID).api_get(
                fields=fields,
                params=params,
            )

            self.assertEqual(len(warning), 0)
            self.assertTrue(isinstance(account, AdAccount))
            self.assertEqual(account[FieldName.ACCOUNT_ID],
                             TestValue.ACCOUNT_ID)
            self.assertEqual(account[FieldName.ACCOUNT_STATUS],
                             TestValue.ACCOUNT_STATUS)
            self.assertEqual(account[FieldName.AGE], TestValue.AGE)
            self.assertTrue(
                isinstance(account[FieldName.AGENCY_CLIENT_DECLARATION],
                           AgencyClientDeclaration))
            self.assertEqual(account[FieldName.BALANCE], TestValue.BALANCE)
            self.assertTrue(isinstance(account[FieldName.BUSINESS], Business))
            self.assertEqual(account[FieldName.BUSINESS_CITY],
                             TestValue.BUSINESS_CITY)
            self.assertEqual(account[FieldName.CAPABILITIES],
                             [TestValue.CAPABILITIES])
            self.assertEqual(account[FieldName.CURRENCY], TestValue.CURRENCY)
            self.assertEqual(account[FieldName.DISABLE_REASON],
                             TestValue.DISABLE_REASON)
            self.assertTrue(
                isinstance(account[FieldName.EXTENDED_CREDIT_INVOICE_GROUP],
                           ExtendedCreditInvoiceGroup))
            self.assertEqual(account[FieldName.FAILED_DELIVERY_CHECKS],
                             [json.loads(TestValue.FAILED_DELIVERY_CHECKS)])
            self.assertEqual(account[FieldName.HAS_PAGE_AUTHORIZED_ADACCOUNT],
                             TestValue.HAS_PAGE_AUTHORIZED_ADACCOUNT)
            self.assertEqual(account[FieldName.TOS_ACCEPTED],
                             json.loads(TestValue.TOS_ACCEPTED))
Example #27
0
# 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 facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.adcreative import AdCreative
from facebook_business.api import FacebookAdsApi

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

fields = []
params = {
    'name': 'Sample Promoted Post',
    'object_story_id': '<pageID>_<postID>',
}
print AdAccount(id).create_ad_creative(
    fields=fields,
    params=params,
)
Example #28
0
    'Test Product Audience',
    'product_set_id':
    '<productSetID>',
    'inclusions': [{
        'retention_seconds': 86400,
        'rule': {
            'event': {
                'eq': 'AddToCart'
            }
        }
    }, {
        'retention_seconds': 72000,
        'rule': {
            'event': {
                'eq': 'ViewContent'
            }
        }
    }],
    'exclusions': [{
        'retention_seconds': 172800,
        'rule': {
            'event': {
                'eq': 'Purchase'
            }
        }
    }],
}
print AdAccount(id).create_product_audience(
    fields=fields,
    params=params,
)
 def api_create(self, parent_id, fields=None, params=None, batch=None, pending=False):
     from facebook_business.adobjects.adaccount import AdAccount
     return AdAccount(api=self._api, fbid=parent_id).create_ad_set(fields, params, batch, pending)
# 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 facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.adpreview import AdPreview
from facebook_business.api import FacebookAdsApi

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

fields = []
params = {
    'creative': {
        'object_story_id': '<pageID>_<postID>'
    },
    'ad_format': 'DESKTOP_FEED_STANDARD',
}
print AdAccount(id).get_generate_previews(
    fields=fields,
    params=params,
)
                    }]
                }
            }]
        },
        'exclusions': {
            'operator':
            'or',
            'rules': [{
                'event_sources': [{
                    'id': '<pageID>',
                    'type': 'page'
                }],
                'retention_seconds': 31536000,
                'filter': {
                    'operator':
                    'and',
                    'filters': [{
                        'field': 'event',
                        'operator': 'eq',
                        'value': 'page_cta_clicked'
                    }]
                }
            }]
        }
    },
    'prefill': '1',
}
print AdAccount(id).create_custom_audience(
    fields=fields,
    params=params,
)
Example #32
0
    sys.exit(1)

output_filename = raw_input(
    "Enter the name of your output (example: meredith.tsv)\n$: ")

if output_filename == '':
    print("Invalid file name")
    sys.exit(1)

json_file = '[]'

# Facebook ADS Api Initialization
FacebookAdsApi.init(app_id, app_secret, access_token)

# Ad Accounts Initialization ( with all the campaigns )
account = AdAccount(ad_account)

fields = ['name', 'status', 'account_id', 'campaign_id', 'created_time']

params = {'date_presets': 'lifetime'}

# TODO: Clean up this part and create methods / class with verification

File.write(
    "../data/" + output_filename,
    arrayToTSVLine([
        "ad_name".upper(), "ad_id".upper(), "campaign_id".upper(),
        "account_id".upper(), "adset_id".upper(), "status".upper(),
        "clicks".upper(), "cpc".upper(), "cpm".upper(), "cpp".upper(),
        "ctr".upper(), "spend".upper(), "relevance_score".upper(),
        "date_start".upper(), "date_end".upper()