簡體   English   中英

Facebook 營銷 API - 獲取洞察的 Python - 達到用戶請求限制

[英]Facebook Marketing API - Python to get Insights - User Request Limit Reached

所以我正在盡我最大的努力通過 Facebook API 導航我的方式。 我需要編寫一個腳本,每天將我的業務活動信息下載為 csv 文件,以便我可以使用另一個腳本輕松地將信息上傳到我們的數據庫。

我終於有了可以將信息打印到日志的代碼,但是我達到了用戶請求限制,因為我必須為每個單獨的活動單獨調用 get_insights()。 我想知道是否有人知道如何幫助我做到這一點,這樣我就不必經常調用 facebook API。

如果找到一個可以獲得每日支出的字段,我想做什么,這樣我就不必在 for 活動循環的每次迭代中都調用 API,但我終生無法找到這樣做的方法.

#Import all the facebook mumbo jumbo
from facebookads.api import FacebookAdsApi
from facebookads.adobjects.adset import AdSet
from facebookads.adobjects.campaign import Campaign
from facebookads.adobjects.adsinsights import AdsInsights
from facebookads.adobjects.adreportrun import AdReportRun
from facebookads.adobjects.adaccount import AdAccount
from facebookads.adobjects.business import Business
import time

#Set the login info
my_app_id = '****'
my_app_secret = '****'
my_access_token = '****'

#Start the connection to the facebook API
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)

business = Business('****')

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

#iterate through all accounts in the business account
for account in accounts:
    tempaccount = AdAccount(account[AdAccount.Field.id])
    #get all campaigns in the adaccount
    campaigns = tempaccount.get_campaigns(fields=[Campaign.Field.name,Campaign.Field])
    #iterate trough all the campaigns in the adaccount
    for campaign in campaigns:
        print(campaign[Campaign.Field.name])
        #get the insight info (spend) from each campaign
        campaignsights = campaign.get_insights(params={'date_preset':'yesterday'},fields=[AdsInsights.Field.spend])
        print (campaignsights)

花了一些時間來挖掘 API 和猜測,但我明白了! 這是我的最終腳本:

# This program downloads all relevent Facebook traffic info as a csv file
# This program requires info from the Facebook Ads API: https://github.com/facebook/facebook-python-ads-sdk

# Import all the facebook mumbo jumbo
from facebookads.api import FacebookAdsApi
from facebookads.adobjects.adsinsights import AdsInsights
from facebookads.adobjects.adaccount import AdAccount
from facebookads.adobjects.business import Business

# Import th csv writer and the date/time function
import datetime
import csv

# Set the info to get connected to the API. Do NOT share this info
my_app_id = '****'
my_app_secret = '****'
my_access_token = '****'

# Start the connection to the facebook API
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)

# Create a business object for the business account
business = Business('****')

# Get yesterday's date for the filename, and the csv data
yesterdaybad = datetime.datetime.now() - datetime.timedelta(days=1)
yesterdayslash = yesterdaybad.strftime('%m/%d/%Y')
yesterdayhyphen = yesterdaybad.strftime('%m-%d-%Y')

# Define the destination filename
filename = yesterdayhyphen + '_fb.csv'
filelocation = "/cron/downloads/"+ filename

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

# Open or create new file 
try:
    csvfile = open(filelocation , 'w+', 0777)
except:
    print ("Cannot open file.")


# To keep track of rows added to file
rows = 0

try:
    # Create file writer
    filewriter = csv.writer(csvfile, delimiter=',')
except Exception as err:
    print(err)

# Iterate through the adaccounts
for account in accounts:
    # Create an addaccount object from the adaccount id to make it possible to get insights
    tempaccount = AdAccount(account[AdAccount.Field.id])

    # Grab insight info for all ads in the adaccount
    ads = tempaccount.get_insights(params={'date_preset':'yesterday',
                                           'level':'ad'
                                          },
                                   fields=[AdsInsights.Field.account_id,
                       AdsInsights.Field.account_name,
                                           AdsInsights.Field.ad_id,
                                           AdsInsights.Field.ad_name,
                                           AdsInsights.Field.adset_id,
                                           AdsInsights.Field.adset_name,
                                           AdsInsights.Field.campaign_id,
                                           AdsInsights.Field.campaign_name,
                                           AdsInsights.Field.cost_per_outbound_click,
                                           AdsInsights.Field.outbound_clicks,
                                           AdsInsights.Field.spend
                                          ]
    );

    # Iterate through all accounts in the business account
    for ad in ads:
        # Set default values in case the insight info is empty
        date = yesterdayslash
        accountid = ad[AdsInsights.Field.account_id]
        accountname = ""
        adid = ""
        adname = ""
        adsetid = ""
        adsetname = ""
        campaignid = ""
        campaignname = ""
        costperoutboundclick = ""
        outboundclicks = ""
        spend = ""

        # Set values from insight data
        if ('account_id' in ad) :
            accountid = ad[AdsInsights.Field.account_id]
        if ('account_name' in ad) :
            accountname = ad[AdsInsights.Field.account_name]
        if ('ad_id' in ad) :
            adid = ad[AdsInsights.Field.ad_id]
        if ('ad_name' in ad) :
            adname = ad[AdsInsights.Field.ad_name]
        if ('adset_id' in ad) :
            adsetid = ad[AdsInsights.Field.adset_id]
        if ('adset_name' in ad) :
            adsetname = ad[AdsInsights.Field.adset_name]
        if ('campaign_id' in ad) :
            campaignid = ad[AdsInsights.Field.campaign_id]
        if ('campaign_name' in ad) :
            campaignname = ad[AdsInsights.Field.campaign_name]
        if ('cost_per_outbound_click' in ad) : # This is stored strangely, takes a few steps to break through the layers
            costperoutboundclicklist = ad[AdsInsights.Field.cost_per_outbound_click]
            costperoutboundclickdict = costperoutboundclicklist[0]
            costperoutboundclick = costperoutboundclickdict.get('value')
        if ('outbound_clicks' in ad) : # This is stored strangely, takes a few steps to break through the layers
            outboundclickslist = ad[AdsInsights.Field.outbound_clicks]
            outboundclicksdict = outboundclickslist[0]
            outboundclicks = outboundclicksdict.get('value')
        if ('spend' in ad) :
            spend = ad[AdsInsights.Field.spend]

        # Write all ad info to the file, and increment the number of rows that will display
        filewriter.writerow([date, accountid, accountname, adid, adname, adsetid, adsetname, campaignid, campaignname, costperoutboundclick, outboundclicks, spend])
        rows += 1


csvfile.close()

# Print report
print (str(rows) + " rows added to the file " + filename)

然后我有一個 php 腳本,它接收 csv 文件並將其上傳到我的數據庫。 關鍵是將所有洞察數據集中到一起。 然后您可以根據需要將其分解,因為每個廣告都包含有關其廣告集、廣告帳戶和廣告系列的信息。

添加幾個小功能以改進 LucyTurtle 的答案,因為它仍然容易受到 Facebook 的速率限制的影響

import logging
import requests as rq

#Function to find the string between two strings or characters
def find_between( s, first, last ):
    try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
    except ValueError:
        return ""

#Function to check how close you are to the FB Rate Limit
def check_limit():
    def check_limit():
    check=rq.get('https://graph.facebook.com/v3.3/act_'+account_number+'/insights?access_token='+my_access_token)
    call=float(find_between(check.headers['x-business-use-case-usage'],'call_count":','}'))
    cpu=float(find_between(check.headers['x-business-use-case-usage'],'total_cputime":','}'))
    total=float(find_between(check.headers['x-business-use-case-usage'],'total_time":',','))
    usage=max(call,cpu,total)
    return usage

#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()>75):
    print('75% Rate Limit Reached. Cooling Time 5 Minutes.')
    logging.debug('75% Rate Limit Reached. Cooling Time 5 Minutes.')
    time.sleep(300)

我只想說謝謝。 正如馬克斯安德烈所說 - 你讓我開心! FB SDK 文檔是詳盡的,但它完全缺乏像這樣的日常任務的實際實現示例。 書簽已設置 - 頁面將很快被重新訪問。

因此,我實際上可以為其他患者做出貢獻的唯一一件事:似乎使用較新的 facebook_business SDK,您可以簡單地將導入語句中的“facebookads”完全替換為“facebook_business”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM