Exemplo 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)
Exemplo n.º 2
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)
 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)
Exemplo n.º 4
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
Exemplo n.º 5
0
import json
import os
import pprint

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]))
import ad_creation_utils
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)

### 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(
Exemplo n.º 7
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()
Exemplo n.º 8
0
import json
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(
    my_app_id,
    my_app_secret,
    my_access_token,
)
api = FacebookAdsApi(session)

if __name__ == '__main__':
    FacebookAdsApi.set_default_api(api)

    my_business = Business(fbid=my_business_id)
    # print("my_business:", my_business)
    my_accounts = list(my_business.get_assigned_ad_accounts())
    # print("All accounts:", my_accounts)

    selected_adaccount = my_accounts[1]

    # Get my account (first account associated with the user associated with the
Exemplo n.º 9
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)
Exemplo n.º 10
0
import os
import conf
from pprint import pprint as pp
from facebookads import FacebookAdsApi
from facebookads import FacebookSession
from facebookads.adobjects.adaccount import AdAccount
from facebookads.adobjects.adset import AdSet
from facebookads.adobjects.campaign import Campaign
from facebookads.adobjects.targeting import Targeting
from facebookads.adobjects.ad import Ad
from facebookads.adobjects.adimage import AdImage
from facebookads.adobjects.adcreative import AdCreative
from facebookads.adobjects.targetinggeolocation import TargetingGeoLocation
from example import example_dict

session = FacebookSession(conf.MY_APP_ID, conf.MY_APP_SECRET, conf.MY_ACCESS_TOKEN)
api = FacebookAdsApi(session)
ACCOUNT = 'act_' + conf.AD_ACCOUNT_ID
FacebookAdsApi.set_default_api(api)


def get_image_files():
    """Returns a list of paths of all the images in the current directory

    Returns:
        list: absolute paths of images in current directory
    """
    current_dir = os.path.dirname(os.path.abspath(__file__))
    images = [img for img in os.listdir(current_dir) if img[-3:] in ['jpg', 'png']]
    image_paths = [os.path.join(current_dir, img) for img in images]
    return image_paths
Exemplo n.º 11
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
Exemplo n.º 12
0
import datetime
import json
import time

print("Begin process...")
with open("Fim.txt", "a") as text_file:
    print("Inicio at: {}".format(datetime.datetime.now().time()),
          file=text_file)
respiro = 0
cred = Credenciais()
#inicializacao
### Setup session and api objects
session = FacebookSession(
    cred.MY_APP_ID,
    cred.MY_APP_SECRET,
    cred.MY_APP_ACCESS_TOKEN,
)
#session.timeout = 1000000
api = FacebookAdsApi(session)
FacebookAdsApi.set_default_api(api)

listaConfig = FbConfiguracoes().ListarTodos(pActived=True)
FBInsights().LimparPeriodo()


def ReportDiario(campaign, config):
    """
    Salva os Insights de um dia(dia atual)
    """
    global respiro
Exemplo n.º 13
0
        if len(prevList) > markovLength:
            prevList.pop(0)
        if (curr not in ".,!?;"):
            sent += " "  # Add spaces between words (but not punctuation)
        sent += curr
    return sent


def generate_pitch(filename, markovLength):
    buildMapping(wordlist(filename), markovLength)
    return genSentence(markovLength)


def generate_pitches():
    for i in xrange(100):
        pitches.append(generate_pitch("assets/dataset.txt", (i % 3) + 1))


if __name__ == "__main__":
    generate_pitches()
    for pitch in pitches:
        print(pitch)
    session = FacebookSession(
        secrets.my_app_id,
        secrets.my_app_secret,
        secrets.my_access_token,
    )
    api = FacebookAdsApi(session)
    FacebookAdsApi.set_default_api(api)
    my_account = AdAccount.get_my_account()