Ejemplo n.º 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)
Ejemplo n.º 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]
        )
Ejemplo n.º 3
0
def main_impl():
    args = utils.parse_args(REQUIRED_CONFIG_KEYS)
    account_id = args.config['account_id']
    access_token = args.config['access_token']

    CONFIG.update(args.config)

    FacebookAdsApi.init(access_token=access_token)
    user = fb_user.User(fbid='me')
    accounts = user.get_ad_accounts()
    account = None
    for acc in accounts:
        if acc['account_id'] == account_id:
            account = acc
    if not account:
        raise TapFacebookException(
            "Couldn't find account with id {}".format(account_id))

    if args.discover:
        do_discover()
    elif args.properties:
        catalog = Catalog.from_dict(args.properties)
        do_sync(account, catalog, args.state)
    else:
        LOGGER.info("No properties were selected")
Ejemplo n.º 4
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()
Ejemplo n.º 8
0
    def __init__(self):
        """
        Initialising the FacebookAdsApi
        """
        try:
            app_id = os.environ['APPID']
            app_secret = os.environ['APPSECRET']
            access_token = os.environ['ACCESSTOKEN']

            FacebookAdsApi.init(app_id, app_secret, access_token)

        except KeyError as ke:
            logger.error(
                'You need to set the following environment variable \n {}'.
                format(ke))
    def __init__(self, account_id):
        self.account_id = account_id
        try:
            app_id = os.environ["APPID"]
            app_secret = os.environ['APPSECRET']
            access_token = os.environ['ACCESSTOKEN']

            FacebookAdsApi.init(app_id, app_secret, access_token)
            logger.info('FB INIT')

        except KeyError as ke:
            logger.error('You need to set the following environ variables:\n'
                         'APPID, APPSECRET, ACCESSTOKEN {}'.format(ke))

        except ValueError as ve:
            logger.error(ve)
Ejemplo n.º 10
0
def initialize_facebook():
    """Initializes a Facebook API session object.

    Returns:
        An authorized Facebook API session object.
    """
    session = FacebookSession(APP_ID, APP_SECRET, ACCESS_TOKEN)
    return FacebookAdsApi(session)
Ejemplo n.º 11
0
 def call(self, access_token='', method='', path=(), params={}):
     caller = FacebookAdsApi.init(self.app_id, self.app_secret,
                                  access_token)
     try:
         return caller.call(method, path, params).json()
     except FacebookRequestError as fberror:
         return fberror.body()
     except Exception as es:
         raise es
Ejemplo n.º 12
0
def main():
    args = utils.parse_args(REQUIRED_CONFIG_KEYS)
    start_date = args.config['start_date']
    account_id = args.config['account_id']
    access_token = args.config['access_token']
    state = State(start_date, args.state)

    FacebookAdsApi.init(access_token=access_token)
    user = objects.AdUser(fbid='me')
    accounts = user.get_ad_accounts()
    account = None
    for acc in accounts:
        if acc['account_id'] == account_id:
            account = acc
    if not account:
        raise Exception("Couldn't find account with id {}".format(account_id))

    if args.discover:
        do_discover()
    elif args.properties:
        do_sync(account, args.properties, state)
    else:
        LOGGER.info("No properties were selected")
Ejemplo n.º 13
0
    def obtain_fb_api(self):
        """
        Returns FB api in order to use the services from the FB sdk.
        :return:
        FB api
        """
        try:

            print("     >>> Abriendo archivo de credenciales...")

            cred_file = 'credentials.json'
            with open('/home/sebasgona/Documents/proyecto_fintech/fintech' +
                      cred_file) as credentials_json:
                credentials = json.load(credentials_json)

            session = FacebookSession(credentials['app_id'],
                                      credentials['app_secret'],
                                      credentials['access_token'])
            api = FacebookAdsApi(session)
            print("     >>> Obteniendo FB API...")
            return api
        except Exception as e:
            print("     >>> ERROR al obtener FB API: \n\n" + str(e))
            return None
Ejemplo n.º 14
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)
    def get_ad_sets(self, account_id, include_archived, limit):
        """
        Retrieves and displays a list of ad sets of a given account,
        and analyze how likely a similar ad for Instagram can be created.

        Params:

        * `account_id` is your Facebook Ad Account id.
        * `include_archived` specifies whether archived ad sets should be
          analyzed.
        * `limit` is how many ad sets to analyze. This script will analyze the
          first `limit` ad sets as in the response, not including those which
          use Instagram placement already. The more this limit is, the longer
          it takes to run. If you run the script directly and are willing
          to wait for a while, you can drop the lines of code around it.

        For more information see the [Instagram Ads document](
        https://developers.facebook.com/docs/marketing-api/guides/instagramads/)
        """
        locale.setlocale(locale.LC_ALL, '')
        if include_archived:
            params = {
                'limit':
                limit,
                AdSet.Field.configured_status: [
                    'PENDING', 'ACTIVE', 'PAUSED', 'PENDING_REVIEW',
                    'DISAPPROVED', 'PREAPPROVED', 'PENDING_BILLING_INFO',
                    'CAMPAIGN_PAUSED', 'CAMPAIGN_GROUP_PAUSED', 'ARCHIVED'
                ],
            }
        else:
            params = {'limit': limit}
        account = AdAccount(account_id)
        ad_sets = account.get_ad_sets(fields=[
            AdSet.Field.id,
            AdSet.Field.campaign_id,
            AdSet.Field.name,
            AdSet.Field.configured_status,
            AdSet.Field.targeting,
        ],
                                      params=params)
        cache = {}
        count = 0
        results = []
        for ad_set in ad_sets:
            if count >= limit:
                break
            count += 1

            result = {}
            result['id'] = ad_set['id']
            result['name'] = ad_set['name']
            logger.error(ad_set)

            # Get targeting from ad set
            targeting = ad_set.get(AdSet.Field.targeting, None)
            logger.error(targeting)
            if targeting is not None:
                publisher_platforms = targeting.get('publisher_platforms',
                                                    None)
                pp_str = ''
                if publisher_platforms is None:
                    result['publisher_platforms'] = '<li>DEFAULT</li>'
                else:
                    for pp in publisher_platforms:
                        pp_str += ('<li>' + self.translate_placement_publisher(
                            str(pp)) + '</li>')
                    result['publisher_platforms'] = pp_str

                params = {
                    'currency': 'USD',
                    'targeting_spec': targeting,
                    'optimize_for': AdSet.OptimizationGoal.impressions,
                }

                if publisher_platforms is not None and "instagram" in \
                        publisher_platforms:
                    count -= 1
                    continue

                reach_fb = account.get_reach_estimate(params=params)[0].get(
                    'users', 0)

                targeting['publisher_platforms'] = ["instagram"]
                targeting['facebook_positions'] = None
                params = {
                    'currency': 'USD',
                    'targeting_spec': targeting,
                    'optimize_for': AdSet.OptimizationGoal.impressions,
                }
                reach_ig = account.get_reach_estimate(params=params)[0].get(
                    'users', 0)

                self.add_check_result(result,
                                      self.check_audience(reach_fb, reach_ig))
                result["audience"] = reach_ig * 100 / reach_fb
                result["ig_audience"] = locale.format("%d",
                                                      reach_ig,
                                                      grouping=True)
            # Get objective and status from Campaign
            campaign_id = ad_set[AdSet.Field.campaign_id]
            campaign = self.get_ad_campaign(cache, campaign_id)
            result["c_objective"] = \
                campaign[Campaign.Field.objective].replace("_", " ")
            result["c_status"] = campaign[Campaign.Field.configured_status]
            check = self.check_objective(result["c_objective"])
            if check['eligibility'] == 5:
                result['objective_supported'] = 1
            elif check['eligibility'] == 1:
                result['objective_supported'] = 0
            else:
                result['objective_supported'] = 2

            self.add_check_result(result, check)

            # Get creative and check the media
            if campaign[Campaign.Field.objective] == 'PRODUCT_CATALOG_SALES':
                result['preview_url'] = \
                    'Images from product catalog are not supported.'
                results.append(result)
                result['creative_ready'] = False
                continue

            creatives = ad_set.get_ad_creatives([
                AdCreative.Field.object_story_id,
            ])
            result['creative_ready'] = False
            if not creatives:
                comment = 'No creative found in this ad set.'
                self.add_check_result(result, {
                    "eligibility": 3,
                })
                result['preview_url'] = comment
                results.append(result)
                continue
            creative = creatives[0]
            story_id = creative.get(AdCreative.Field.object_story_id, 0)
            if story_id == 0:
                comment = 'No post fround in the first creative of this ad set.'
                self.add_check_result(result, {
                    "eligibility": 3,
                })
                result['preview_url'] = comment
                results.append(result)
                continue

            # Check whether the creative's post is IG ready
            try:
                # This Graph API call is not a part of Ads API thus no SDK
                post = FacebookAdsApi.get_default_api().call(
                    'GET',
                    (story_id, ),
                    params={
                        'fields': 'is_instagram_eligible,child_attachments'
                    },
                )
                post_ig_eligible = post.json()['is_instagram_eligible']
            except FacebookRequestError:
                post_ig_eligible = False
            result['creative_ready'] = post_ig_eligible
            if post_ig_eligible:
                self.add_check_result(result, {
                    "eligibility": 5,
                })

                # Generate preview
                # As we do not know which IG account you will use,
                # just use a hardcoded one for preview.
                jasper_ig_account = "1023317097692584"
                ad_format = 'INSTAGRAM_STANDARD'
                creative_spec = {
                    'instagram_actor_id': jasper_ig_account,
                    'object_story_id': story_id,
                }
                params = {
                    AdPreview.Field.creative: creative_spec,
                    AdPreview.Field.ad_format: ad_format,
                }
                preview = account.get_generate_previews(params=params)
                result['preview_url'] = preview[0].get_html() \
                    .replace('width="320"', 'width="340"', 1)
            else:
                comment = 'The creative needs to be modified for Instagram.'
                self.add_check_result(result, {
                    "eligibility": 3,
                })
                result['preview_url'] = comment
            results.append(result)
        return list(
            sorted(results,
                   key=lambda result: result['eligibility'],
                   reverse=True))
Ejemplo n.º 16
0
from facebookads.objects import (
    AdImage,
    AdCreative,
    AdGroup,
)

import os
import pprint

pp = pprint.PrettyPrinter(indent=4)
this_dir = os.path.dirname(__file__)
config = Config().get_config()

FacebookAdsApi.init(
    config['api_app_id'],
    config['app_secret'],
    config['access_token'],
)


class AdCreativeModel:
    def __init__(self, param, filename):
        self.param = param
        self.filename = filename

    def create_ad_creative(self):
        parent_id = config['act_id'][self.param['account']]
        page_id = config['page_id'][self.param['account']]
        link_url = config['link_url'][self.param['account']][self.param['os']]

        # Upload an image to an account.
Ejemplo n.º 17
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
# 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 examples.docs import fixtures
from facebookads import test_config, FacebookAdsApi
from facebookads.objects import AdImage

page_id = test_config.page_id
image_url = fixtures.create_image()[AdImage.Field.url]

FacebookAdsApi.set_default_api(fixtures.get_page_api())

# _DOC oncall [pruno]
# _DOC open [PAGE_POST_CREATE_GET_DIRECTIONS]
# _DOC vars [image_url:s, page_id]
from facebookads import FacebookAdsApi

link = 'fbgeo://37.48327, -122.15033, "1601 Willow Rd Menlo Park CA"'

params = {
    'message': 'Come check out our new store in Menlo Park!',
    'link': 'https://www.facebook.com/' + str(page_id),
    'picture': image_url,
    'published': 0,
    'call_to_action': {
        'type': 'GET_DIRECTIONS',
from facebookads import FacebookAdsApi
from facebookads.objects import AdAccount, AdVideo

import os
import configparser
config = configparser.RawConfigParser()
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)

FacebookAdsApi.init(
    config.get('Authentication', 'app_id'),
    config.get('Authentication', 'app_secret'),
    config.get('Authentication', 'access_token'),
)

if __name__ == '__main__':
    my_account = AdAccount(config.get('Defaults', 'ad_account'))

    # create video object
    video = AdVideo(parent_id=my_account.get_id_assured())

    # set video fields
    video[AdVideo.Field.filepath] = os.path.join(this_dir, 'test_video.mp4')

    # remove create
    video.remote_create()
    video.waitUntilEncodingReady()
# 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.

from examples.docs import fixtures
from facebookads import FacebookAdsApi

FacebookAdsApi.set_default_api(fixtures.get_page_api())

# _DOC oncall [pruno]
# _DOC open [PAGE_GET_LEADGENQUALIFIERS]
from facebookads import FacebookAdsApi

accounts = FacebookAdsApi.get_default_api()\
    .call('GET', ('/me/leadgen_qualifiers',))
# _DOC close [PAGE_GET_LEADGENQUALIFIERS]
Ejemplo n.º 21
0
import os

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

### 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)
Ejemplo n.º 22
0
# 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 oncall [pruno]
# _DOC open [ME_GET_ACCOUNTS]
from facebookads import FacebookAdsApi

accounts = FacebookAdsApi.get_default_api().call('GET', ('/me/accounts',))
# _DOC close [ME_GET_ACCOUNTS]
Ejemplo n.º 23
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()
Ejemplo n.º 24
0
def api_get(path, api=None, url=default_api_url):
    if api is None:
        api = FacebookAdsApi.get_default_api()
    response = api.call('GET', url + path)
    return response.json()
Ejemplo n.º 25
0
def api_post(path, params={}, api=None, url=default_api_url, **kwargs):
    if api is None:
        api = FacebookAdsApi.get_default_api()
    response = api.call('POST', url + path, params=params, **kwargs)
    return response.json()
Ejemplo n.º 26
0
)

from facebookads import objects
import configparser
import os
import time
import pprint
import fb_helper


config = fb_helper.open_config('fb_config.cfg')

app_id = '826090954086728'
app_secret = 'bcaf6d6eb26bbc824fa33a6527863ea7'
access_token = 'CAALvU0ne2UgBAOZCLefaNxbx7qjnOLfRttKOVZCDRMsscZABTjumWDW4ogyDvA7KWYUfk8dH0NMbTxXRz0iSI8S8Y7MLy5JdtM2ZCtWb6ZCxq6EONpX5neTU6nwDZCCZA1hzmH6vbIgqfCLgD6p4JYTC5uZANiTxQ64ENZA5eLpAOXo3hJSF71QATbfgS9lVmt6ZAHZCa92nP7oV6pIJ9Dygd0B'
FacebookAdsApi.init(app_id, app_secret, access_token)

pp = pprint.PrettyPrinter(indent=4)

act_id = config.get('Defaults', 'ad_account')

csvfilename = posixpath.join('c:', 'Users', 'Christopher Scanlin', 'python_scripts', 'assorted_python', 'csvfilename.csv')

input_file = open(csvfilename, 'rb')

input_fields = (
'CLUSTER',
'PARENT_URL',
'CAPTION',
'NAME_ONE',
'DESCRIPTION_ONE',
# 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.

from examples.docs import fixtures
from facebookads import FacebookAdsApi

FacebookAdsApi.set_default_api(fixtures.get_page_api())

# _DOC oncall [pruno]
# _DOC open [PAGE_GET_SUBSCRIBEDAPPS]
from facebookads import FacebookAdsApi

accounts = FacebookAdsApi.get_default_api()\
    .call('GET', ('/me/subscribed_apps',))
# _DOC close [PAGE_GET_SUBSCRIBEDAPPS]
Ejemplo n.º 28
0
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
pp = pprint.pprint

this_dir = os.path.dirname(__file__)
config_filename = os.path.join(this_dir, 'config.json')

### Setup session and api objects
config_file = open(config_filename)
config = json.load(config_file)
config_file.close()

auth_info = (
    config['app_id'],
    config['app_secret'],
    config['access_token'])

FacebookAdsApi.init(*auth_info)

### Get account from config file
my_account = AdAccount(config['act_id'])

def ListCustomAudiences(**kwargs):
    audiences = my_account.get_custom_audiences(fields=[
        CustomAudience.Field.name,
        CustomAudience.Field.description])
    if(audiences):
        print(">>> Account")
        print(my_account[CustomAudience.Field.id])
        print(">>> Audiences")

    for audience in audiences:
        print(audience[CustomAudience.Field.id] + ': ' +
Ejemplo n.º 30
0
pp = pprint.PrettyPrinter(indent=4)
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()

### 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()
Ejemplo n.º 31
0
from facebookads.adobjects.adaccount import AdAccount
from facebookads.adobjects.adset import AdSet
from facebookads.adobjects.ad import Ad
from facebookads.adobjects.adpreview import AdPreview
from facebookads.session import FacebookSession
from facebookads import FacebookAdsApi

access_token = 'EAAcpfNkWwLIBAJ8TvDkZBhgMBggvJOZCKj2LqlP1XxRiZCujuZCyln1Y78NZC7I2HkazMDZCjFZAv7YHiEY9LusRNUtEHzgkHQgO1ZAx5drFBdAPynxpSzBNAmfA35xE0s4fJFjZAsPZApv4IKYNmcSsA7dbgAUoBy6NiRmnmELXVR5m6F5n2qq3GU47J77WAfh1kvEeZCWtZAdk4Uj7X1IdZAlfhnbDFNBGZC6YcZD'
ad_account_id = 'act_202042424038719'
app_secret = 'c6730bc343cdefecc28c894e8db18d16'
app_id = '2015941031805106'

FacebookAdsApi.init(access_token=access_token)

fields = [
    'account_id',
    'account_name',
    'campaign_group_name',
    'campaign_group_id',
    'campaign_name',
    'campaign_id',
    'adgroup_id',
    'adgroup_name',
]
params = {
    'level': 'campaign',
    'filtering': [],
    'breakdowns': [],
    'time_range': {
        'since': '2018-11-11',
        'until': '2018-12-11'
Ejemplo n.º 32
0
def get_page_api():
    page_token = get_page_access_token()
    session = FacebookSession(test_config.app_id,
                              test_config.app_secret,
                              page_token)
    return FacebookAdsApi(session)
class Adapter:
    """ An object designed to make managing custom audiences a little easier.
    
    :params account: str, account id
    :params table: str, table name from database
    
    return :: container.Adapter object
    """
    __session = FacebookSession(config.APP_ID, config.APP_SECRET,
                                config.ACCESS_TOKEN)
    __api = FacebookAdsApi(__session)

    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 _get_audience(self, audience_name):
        """ This retrieves an audience object based on a string name.
        
        :params audience_name: str, name of audience
        """
        for audience in list(self.audiences):
            if audience['name'] == audience_name:
                audience_id = audience['id']

        target = CustomAudience(audience_id)

        return target

    def _batch_users(self, obj, size=2500):
        """ This returns a generator that returns a list 
        of lists of a specific size.
        
        :params obj: list, users list that needs to be batched
        :params size: int, the batch size
        """
        for chunk in range(0, len(obj), size):
            try:
                yield obj[chunk:chunk + size]
            except IndexError:
                yield obj[chunk:len(obj)]

    def create_audience(self, name, desc=None):
        """ This creates an audience object.
        
        :params name: str, name of audience
        :params desc: str, description of audience
        """
        if name in [audience['name'] for audience in self.audiences]:
            raise ValueError(
                'Attempted to add audience. Audience with same name exists.')

        audience = CustomAudience(parent_id=self._account)
        audience[CustomAudience.Field.subtype] = CustomAudience.Subtype.custom
        audience[CustomAudience.Field.name] = '{}'.format(name)

        if desc:
            audience[CustomAudience.Field.description] = desc
        audience.remote_create()

    def delete_audience(self, name):
        """ This deletes an audience object.
        
        :params name: str, name of audience
        """
        if name not in [audience['name'] for audience in self.audiences]:
            raise ValueError(
                'Attempted to remove audience. Audience does not exist.')

        for audience in list(self.audiences):
            if audience['name'] == name:
                delete_id = audience['id']

        audience = CustomAudience(delete_id)
        audience.remote_delete()

    def add_users(self, name, users):
        """ This bulk adds users to an audience object.
        
        :params name: str, name of audience
        :params users: list, list of users
        """
        if not len(users):
            return print('Attempted to add users. No users in the list.')

        print('Adding {} users to {}'.format(len(users), name))

        if not isinstance(users, list):
            raise TypeError

        target = self._get_audience(name)

        if len(users) > 10000:  # User add limit is ~10000.
            batches = self._batch_users(users)
            for batch in batches:
                post_ = target.add_users(CustomAudience.Schema.email_hash,
                                         batch,
                                         is_raw=True)
                pprint.pprint(post_._body)
        else:
            post_ = target.add_users(CustomAudience.Schema.email_hash,
                                     users,
                                     is_raw=True)

    def remove_users(self, name, users):
        """ This bulk deletes users from an audience object.
        
        :params name: str, name of audience
        :params users: list, list of users
        """
        if not len(users):
            return print('Attempted to remove users. No users in the list.')

        print('Removing {} users to {}'.format(len(users), name))

        if not isinstance(users, list):
            raise TypeError

        target = self._get_audience(name)

        if len(users) > 500:  # User delete limit is 500 < x < 1000.
            batches = self._batch_users(users, size=500)
            for batch in batches:
                target.remove_users(CustomAudience.Schema.email_hash, batch)
        else:
            target.remove_users(CustomAudience.Schema.email_hash, users)

    @property
    def audiences(self):
        return AdAccount(self._account).get_custom_audiences(
            fields=[CustomAudience.Field.name, CustomAudience.Field.id])

    def __str__(self):
        return '<[Adapter Object]>'

    def __repr__(self):
        return '<Adapter Object [{}]>'.form(self._account)
from facebookads import FacebookAdsApi
from facebookads.objects import AdAccount, AdVideo

import configparser
import os

config = configparser.RawConfigParser()
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)

FacebookAdsApi.init(
    config.get('Authentication', 'app_id'),
    config.get('Authentication', 'app_secret'),
    config.get('Authentication', 'access_token'),
)

if __name__ == '__main__':
    my_account = AdAccount('act_<AD_ACCOUNT_ID>')

    # create video object
    video = AdVideo(parent_id=my_account.get_id_assured())

    # set video fields
    video[AdVideo.Field.filepath] = os.path.join(this_dir, 'test_video.mp4')

    # remove create
    video.remote_create()
    video.waitUntilEncodingReady()
# 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,
# 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 facebookads import test_config, FacebookAdsApi
from examples.docs import fixtures
from facebookads.objects import AdImage

page_id = test_config.page_id
app_url = test_config.app_url
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_DESKTOP]
# _DOC vars [page_id, thumbnail_url:s, app_url:s, video_path:s]
from facebookads import FacebookAdsApi

params = {
    'name': 'My Video',
    'massage': 'Check out this app!',
    'thumbnail': thumbnail_url,
    'published': 0,
    'call_to_action': {
        'type': 'PLAY_GAME',
        'value': {
            'link': app_url,
        },
Ejemplo n.º 37
0
import os

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

### 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)
# 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 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()
app_deep_link = "facebook://"
app_secret = test_config.app_secret
image_url = fixtures.create_image()[AdImage.Field.url]
FacebookAdsApi.set_default_api(fixtures.get_page_api())

# _DOC open [PAGE_POST_CREATE_IMAGE_WITH_DEEP_LINK]
# _DOC vars [page_id, image_url:s, app_store_url:s, app_deep_link:s]
from facebookads import FacebookAdsApi

params = {
    "massage": "Download Facebook today. Available on iTunes.",
    "picture": image_url,
    "published": 1,
    "call_to_action": {"type": "LEARN_MORE", "value": {"link": app_store_url, "app_link": app_deep_link}},
}

path = "/{}/feed".format(page_id)
data = FacebookAdsApi.get_default_api().call("POST", (path,), params=params)
# _DOC close [PAGE_POST_CREATE_IMAGE_WITH_DEEP_LINK]
import pprint
import sys

pp = pprint.pprint

this_dir = os.path.dirname(__file__)
config_filename = os.path.join(this_dir, 'config.json')

### Setup session and api objects
config_file = open(config_filename)
config = json.load(config_file)
config_file.close()

auth_info = (config['app_id'], config['app_secret'], config['access_token'])

FacebookAdsApi.init(*auth_info)

### Get account from config file
my_account = AdAccount(config['act_id'])


def ListCustomAudiences(**kwargs):
    audiences = my_account.get_custom_audiences(
        fields=[CustomAudience.Field.name, CustomAudience.Field.description])
    if audiences:
        print(">>> Account")
        print(my_account[CustomAudience.Field.id])
        print(">>> Audiences")

    for audience in audiences:
        print(audience[CustomAudience.Field.id] + ': ' +
Ejemplo n.º 40
0
    AdConversionPixel,
    ConnectionObject,
    LeadgenForm,
    ProductAudience,
    ProductCatalog,
    ProductSet,
    Page,
    AdPlacePageSet)

from facebookads.specs import LinkData, ObjectStorySpec

import time
import atexit

default_url = 'https://graph.facebook.com/' + FacebookAdsApi.API_VERSION
default_api = FacebookAdsApi.get_default_api()


def api_get(path, params=None, api=default_api, url=default_url):
    if params is None:
        params = {}
    response = api.call('GET', url + path)
    return response.json()


def api_delete(path, params=None, api=default_api, url=default_url):
    if params is None:
        params = {}
    response = api.call('DELETE', url + path, params=params)
    return response.json()