Example #1
0
 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)
Example #2
0
def main():
    # Initialize API access
    FacebookAdsApi.set_default_api(initialize_facebook())

    # Authorize credentials with Google Drive
    gc = initialize_drive()

    # Get account connected to the user
    # [3] may not be your account, find the right account, try [0] first
    my_account = AdAccountUser(fbid = 'me').get_ad_accounts()[3]

    # Download existing or make dataframe and the last week
    existing_totals, start_date_totals = download_df(WORKSHEETS[0])
    existing_details, start_date_details = download_df(WORKSHEETS[1])

    # Getting the sweet data
    all_data_totals = loop_adding_weeks_totals(my_account, existing_totals, start_date_totals, INSIGHT_FIELDS)
    all_data_details = loop_adding_weeks_details(my_account, existing_details, start_date_details, INSIGHT_FIELDS)

    # Upload the transformed data to Google Sheets
    d2g.upload(
        df = all_data_totals, 
        gfile = SPREADSHEET, 
        wks_name = WORKSHEETS[0]
        )
    d2g.upload(
        df = all_data_details, 
        gfile = SPREADSHEET, 
        wks_name = WORKSHEETS[1]
        )
Example #3
0
	def __init__(self, conf):
		self.app_id = conf.get('FB_Authentication', 'app_id')
		self.app_secret = conf.get('FB_Authentication', 'app_secret')
		self.access_token = conf.get('FB_Authentication', 'access_token')
		self.session = FacebookSession(self.app_id, self.app_secret, self.access_token)
		self.api = FacebookAdsApi(self.session)
		FacebookAdsApi.set_default_api(self.api)
 def __init__(self, account=None, table='customers'):
     FacebookAdsApi.set_default_api(self.__api)
     if account:
         self._account = 'act_{}'.format(account)
         self.__api.set_default_account_id = self._account
         self._audiences = AdAccount(self._account).get_custom_audiences(
             fields=[CustomAudience.Field.name, CustomAudience.Field.id])
         self._responses = []
 def __init__(self, app_id, app_secret, access_token):
     self.app_id = app_id
     self.app_secret = app_secret
     self.access_token = access_token
     self.fb_session = FacebookSession(self.app_id, self.app_secret,
                                       self.access_token)
     self.fb_api = FacebookAdsApi(self.fb_session)
     """ 设置一个默认的API对象 """
     FacebookAdsApi.set_default_api(self.fb_api)
def main():
    FacebookAdsApi.set_default_api(api)
    print("Hello world")
    # facebook = Face
    # campaign = create_campaign()

    # campaign = read_campaign(6048231054913)
    # print(campaign)
    # ad_set = create_adset(campaign.get_id())
    # ad_set = read_adset(ad_set.get_id())
    audience = get_customer_audicence()
    estimate = reach_esitmate()
Example #7
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)
this_dir = os.path.dirname(__file__)
config_filename = os.path.join(this_dir, 'my_app_session.cfg')

with open(config_filename) as config_file:
    config.readfp(config_file)

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

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

    print('**** Creating ad...')

    # Create my ad
    my_ad = ad_creation_utils.create_website_clicks_ad(
        account=my_account,

        name="Visit Seattle",
        country='US',

        title="Visit Seattle",                             # How it looks
# 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 import test_config, FacebookAdsApi
from examples.docs import fixtures
from facebookads.objects import AdImage

page_id = test_config.page_id
app_id, app_store_url = fixtures.get_promotable_ios_app()
product_link = ''
app_secret = test_config.app_secret
thumbnail_url = fixtures.create_image()[AdImage.Field.url]
video_path = test_config.video_path
FacebookAdsApi.set_default_api(fixtures.get_page_api())

# _DOC open [PAGE_POST_CREATE_VIDEO_VIRTUAL_GOODS]
# _DOC vars [page_id, thumbnail_url:s, app_store_url:s, video_path:s, product_link:s]
from facebookads import FacebookAdsApi

params = {
    'name': 'My Video',
    'massage': 'Buy coins now!',
    'thumbnail': thumbnail_url,
    'published': 0,
    'call_to_action': {
        'type': 'BUY_NOW',
        'value': {
            'link': app_store_url,
            'product_link': product_link,
Example #10
0
	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)
Example #11
0
def process_fb_change(change):
    fan_page = FacebookFanPage.objects.get(fan_page_id=change['page_id'])
    my_session = FacebookSession(FB_APP_ID, FB_APP_SECRET, fan_page.token)
    my_api = FacebookAdsApi(my_session)
    FacebookAdsApi.set_default_api(my_api)

    try:
        leadgen = Lead(change['leadgen_id'])
        lead_response = leadgen.remote_read()
    except FacebookRequestError as e:
        print("Leadgen_id ({0})- FacebookRequestError: {1}".format(
            change['leadgen_id'], e))
        return HttpResponse(json.dumps({
            'status': 'error',
            'code': 400
        }),
                            content_type='application/json')

    lead_response = lead_response['field_data']

    try:
        form = FacebookAdCode.objects.select_related('formulario').get(
            code=change['ad_id']).formulario
    except FacebookAdCode.DoesNotExist as e:
        print("Ad_id ({0})- FacebookRequestError: {1}".format(
            change['ad_id'], e))
        return HttpResponse(json.dumps({
            'status': 'error',
            'code': 400
        }),
                            content_type='application/json')

    processed_lead = {}
    cont = Context()
    for pair in lead_response:
        key = slugify(pair['name']).replace("-", "_")
        value = pair['values'][0]
        processed_lead[key] = value
        cont.update({key: value})

    processed_lead = json.dumps(processed_lead)

    tracking = TrackingFormularioDinamico(site=Site.objects.get_current(),
                                          sender=form.name[:200],
                                          utm_source='Facebook',
                                          utm_medium='',
                                          utm_campaign='',
                                          object_form=form,
                                          sent_by_mail=False)

    tracking.data = processed_lead
    tracking.save()

    recipients = stringIO.StringIO(form.recipient_list)
    recipient_lines = [line.strip('\n\r') for line in recipients.readlines()]
    recipient_list = []

    for line in recipient_lines:
        recipient = line.strip('\n\r')
        name, email = re.split('\s*,\s*', recipient)
        recipient_list.append(force_text((email.strip('\n\r')).strip(' ')))

    cont.update({'now': datetime.datetime.now()})
    form.send_notification_email(ctx=cont,
                                 recipient_list=recipient_list,
                                 adf_recipient_list=[form.adf_recipient],
                                 ignore_limit=True)
    tracking.sent_by_mail = True
    tracking.save()
Example #12
0
def facebook_campaign_stats(adcampaign,
                            start_date_str,
                            end_date_str,
                            allow_cache=False):
    session = FacebookSession(BUSINESS_APP_ID, BUSINESS_APP_SECRET,
                              adcampaign.ad_account.access_token)
    api = FacebookAdsApi(session)
    FacebookAdsApi.set_default_api(api)
    params = {
        'time_range': {
            'since': start_date_str,
            'until': end_date_str,
        },
        'fields': [
            AdsInsights.Field.impressions,
            AdsInsights.Field.clicks,
            AdsInsights.Field.spend,
            AdsInsights.Field.actions,
            AdsInsights.Field.ctr,
            AdsInsights.Field.inline_link_clicks,
            AdsInsights.Field.inline_link_click_ctr,
            AdsInsights.Field.cpc,
        ],
    }

    cache_file = '/tmp/%s-%s-%s.json' % (adcampaign.fbid, start_date_str,
                                         end_date_str)
    if allow_cache and os.path.isfile(cache_file):
        last_modified = datetime.fromtimestamp(os.path.getmtime(cache_file))
        if last_modified > datetime.now() - timedelta(hours=1):
            with open(cache_file, 'r') as cache_file:
                return json.load(cache_file)

    last_err = None

    # TODO(chesterwu): verify the API rate limit not exceeded. Ref -
    # developers.facebook.com/docs/marketing-api/api-rate-limiting
    for i in xrange(3):
        try:
            campaign = Campaign(adcampaign.fbid)
            campaign_api_response = campaign.remote_read(fields=[
                Campaign.Field.effective_status, Campaign.Field.spend_cap
            ])
            insights = campaign.get_insights(params=params)
        except FacebookError as e:
            last_err = e
        else:
            break
    else:
        raise Exception(
            'Failed to retrieve Facebook data for Adcampaign %s: %s' %
            (adcampaign, str(last_err)))

    if insights:
        insight = insights[0]
        campaign_stats = {
            'status': campaign_api_response.get('effective_status'),
            'spend_cap': campaign_api_response.get('spend_cap'),
            'impressions': insight['impressions'],
            'clicks': insight['clicks'],
            'spent': float(insight['spend']) * 100,
            'ctr': insight['ctr'],
            'link_clicks': insight['inline_link_clicks'],
            'website_ctr': insight['inline_link_click_ctr'],
            'cpc': insight['cpc'],
        }
    else:
        campaign_stats = {
            'status': campaign_api_response.get('effective_status'),
            'spend_cap': campaign_api_response.get('spend_cap'),
            'impressions': 0,
            'clicks': 0,
            'link_clicks': 0,
            'spent': 0,
            'ctr': None,
            'website_ctr': None,
            'cpc': None,
        }

    with open(cache_file, 'w') as cache_file:
        json.dump(campaign_stats, cache_file)
    return campaign_stats