Exemple #1
0
def getFBData(item, topics, locations):
    intrests = {}
    geo = set()
    account = AdAccount(my_add_account_id)
    for t in topics:
        params = {
            'type': 'adinterest',
            'q': t,
        }
        resp = TargetingSearch.search(params=params)
        if not len(resp):
            continue
        intr = resp[0]
        intrest = intr.export_all_data()
        intrests[intrest['id']] = {
            'id': intrest['id'],
            'name': intrest['name']
        }
        pb_intrest = keywee_pb2.FacebookIntrest()
        pb_intrest.name = intrest['name']
        pb_intrest.id = intrest['id']
        item.facebook_intrests.extend([pb_intrest])
        logger.debug("Processed [%s] with Facebook TargetingSearch", t)

    for t in locations:
        params = {
            'type': 'adcountry',
            'q': t,
        }
        resp = TargetingSearch.search(params=params)
        if not len(resp):
            continue
        intr = resp[0]
        intrest = intr.export_all_data()
        geo.add(intrest['country_code'])
        logger.debug("Processed [%s] with Facebook TargetingSearch", t)

    user_adcluster = list(intrests.values())
    targeting_spec = {
        'geo_locations': {
            'countries': list(geo),
        },
        'user_adclusters': user_adcluster
    }

    params = {
        'targeting_spec': targeting_spec,
    }
    account_reach_estimate = account.get_reach_estimate(params=params)
    logger.debug("Got esstimate %d from facebook", len(account_reach_estimate))
    if len(account_reach_estimate) > 0:
        item.estimate_ready = account_reach_estimate[0]['estimate_ready']
        item.audiance_size = account_reach_estimate[0]['users']
        return True
    return False
def result_list():
    interest_list = [item for sublist in request.form.listvalues() for item in sublist]
    app.logger.debug(interest_list)

    # Obtain a large list of interests
    results = []
    stored = []
    for it in range(0,3):
        nb_keywords = 1
        for idx in range(0,len(interest_list),nb_keywords):
            items = TargetingSearch.search(params={
                'interest_list': interest_list[idx:idx+nb_keywords],
                'type': TargetingSearch.TargetingSearchTypes.interest_suggestion,
                'limit': 8,
            })

            results += [interest for interest in items if interest['name'] not in stored]
            stored += [interest['name'] for interest in items if interest['name'] not in stored]
        random.shuffle(stored)
        interest_list = stored

    results.sort(key=targeting_search_audience_size)
    results = list(map(lambda x: {
        'name': x.get('name'),
        'audience_size': x.get('audience_size')
    }, results))

    response = app.response_class(
        response = json.dumps(results),
        status = 200,
        mimetype = 'application/json'
    )
    return response
Exemple #3
0
    def fetch_countries_list(self):
        """
		Fetch the current list of countries.
		In practice this will rarely change but any change to the list will be handled without requiring code changes.
		"""
        # TODO should retry this a few times if it fails
        try:
            self.countries = TargetingSearch.search(params={
                'q':
                '',
                'type':
                TargetingSearch.TargetingSearchTypes.country,
                'limit':
                1000,
            },
                                                    api=self.backup_api)
        except FacebookRequestError as e:
            if e.api_error_code() == 190:
                logger.error(
                    '(API Error 190) Backup account credentials expired, cannot continue'
                )
                # TODO email error email
                raise SystemExit
            else:
                logger.exception(
                    'Unknown Marketing API error while fetching countries list, cannot continue'
                )
                # TODO email error email
                raise SystemExit
        except Exception:
            # TODO try to enumerate some possible errors but we may want to retry in all circumstances
            logger.exception(
                'Unknown Marketing API error while fetching countries list, cannot continue'
            )
Exemple #4
0
def get_location():
    location_query = request.form['location_query']

    # reference: https://developers.facebook.com/docs/marketing-api/targeting-search#geo
    params = {
        'q': location_query,
        'type': 'adgeolocation',
        'location_types': ['city'],  # only city results
        'limit': 5,
        "country_code": "US",  # only search results from US
    }
    FacebookAdsApi.init(access_token=g.user['access_token'],
                        api_version='v3.3')
    data = TargetingSearch.search(params=params)

    list = []
    for i in range(len(data)):
        #{'name':"Charleston, SC, United States", 'type': 'city'}
        str = data[i]["name"] + ", " + data[i]["region"] + ", " + data[i][
            "country_code"]
        list.append({
            'name': str,
            'type': data[i]["type"],
            'key': data[i]["key"]
        })

    return jsonify(list)
Exemple #5
0
    def collect_targeting_specs(self):
        """Collect some lists of targeting specs to help choose new targeting parameters."""
        user_devices = TargetingSearch.search(params={
            'q':
            'user_device',
            'type':
            TargetingSearch.TargetingSearchTypes.targeting_category,
            'limit':
            1000,
        },
                                              api=self.backup_api)
        print(user_devices)
        with open(os.path.join(data_path, 'devices.json'),
                  'w') as file, open(os.path.join(data_path, 'devices.csv'),
                                     'w',
                                     newline='') as csvfile:
            d = list(
                filter(lambda x: x['type'] == 'user_device',
                       map(lambda x: x._data, user_devices)))
            # d2 = list(filter(lambda x: x['type'] == 'user_device', d))
            d3 = {"root": d}
            json.dump(d3, file)
            csvwriter = csv.DictWriter(csvfile, fieldnames=d[0].keys())
            csvwriter.writeheader()
            csvwriter.writerows(d)

        user_os = TargetingSearch.search(params={
            'q':
            'user_os',
            'type':
            TargetingSearch.TargetingSearchTypes.targeting_category,
            'limit':
            1000,
        },
                                         api=self.backup_api)
        print(user_os)
        with open(os.path.join(data_path, 'os.json'),
                  'w') as file, open(os.path.join(data_path, 'os.csv'),
                                     'w',
                                     newline='') as csvfile:
            d = list(
                filter(lambda x: x['type'] == 'user_os',
                       map(lambda x: x._data, user_os)))
            json.dump({"root": d}, file)
            csvwriter = csv.DictWriter(csvfile, fieldnames=d[0].keys())
            csvwriter.writeheader()
            csvwriter.writerows(d)
    def search_targeting_interests(self, query):
        params = {
            'q': query,
            'type': 'adinterest',
        }

        interests = TargetingSearch.search(params=params)
        return interests
def search_target_id(keyword=None):
    from facebook_business.adobjects.targetingsearch import TargetingSearch
    params = {
        'q': str(keyword),
        'type': TargetingSearch.TargetingSearchTypes.interest,
    }
    resp = TargetingSearch.search(params=params)
    current_resp = resp[0]
    return resp['id']
Exemple #8
0
 def geo_target_search(geos):
     all_geos = []
     for geo in geos:
         params = {
             'q': geo,
             'type': 'adgeolocation',
             'location_types': [Targeting.Field.country],
         }
         resp = TargetingSearch.search(params=params)
         all_geos.extend(resp)
     return all_geos
Exemple #9
0
    def searchForTargetingInterests(self, category_names):
        interests = []

        for category_name in category_names:
            params = {
                'q': category_name,
                'type': 'adinterest',
            }
            response = TargetingSearch.search(params)
            for result in response:
                if result['name'] == category_name:
                    interests.append(result)
        return interests
def adinterest():
    term = request.args.get('term')

    items = TargetingSearch.search(params={
        'q': term,
        'type': TargetingSearch.TargetingSearchTypes.interest,
        'limit': 10,
    })

    results = list(map(lambda x: x.get('name'), items))

    response = app.response_class(
        response = json.dumps(results),
        status = 200,
        mimetype = 'application/json'
    )
    return response
Exemple #11
0
 def target_search(targets_to_search):
     all_targets = []
     for target in targets_to_search[1]:
         params = {
             'q': target,
             'type': 'adinterest',
         }
         resp = TargetingSearch.search(params=params)
         if not resp:
             logging.warning(target + ' not found in targeting search.  ' +
                             'It was not added to the adset.')
             continue
         if targets_to_search[0] == 'interest':
             resp = [resp[0]]
         new_tar = [dict((k, x[k]) for k in ('id', 'name')) for x in resp]
         all_targets.extend(new_tar)
     return all_targets
def migrantMX2USA(state, age_min=13, age_max=65, gender=None):
    """
    Return the estimated number of migrants form Mexico to the United States.

    :param state: string, full name of a state, capital first letter.
    :param age_min: int, numeric minimum age to search but >= 13.
    :param age_max: int, numeric minimum age to search but <= 65.
    :param gender: string, either male or female or None for both.
    """
    assert state in states, "state must be a first letter capital valid state"
    stateKey = TargetingSearch.search({
        'q': state,
        'type': 'adgeolocation',
        'location_types': ['region']
    })
    stateKey = [x for x in stateKey if x["country_code"] == "US"]
    stateKey = stateKey[0]["key"]
    call = ("https://graph.facebook.com/v3.0/act_" + fbkeys['ads_id'] +
            "/delivery_estimate?access_token=" + fbkeys['access_token'] +
            "&optimization_goal=AD_RECALL_LIFT&targeting_spec=" +
            '{"flexible_spec":[{"behaviors":[{' +
            '"id":"6015559470583","name":"Ex-pats (Mexico)"}]}],' +
            '"geo_locations":{"regions":[{' + '"key":"' + stateKey + '",' +
            '"name":"' + state + '"' + '}]},"facebook_positions":["feed"],' +
            '"age_min":' + str(age_min) + ',"age_max":' + str(age_max) +
            ',"device_platforms":["mobile","desktop"],' +
            '"publisher_platforms":["facebook"]')
    if gender is None:
        call += '}'
    else:
        gassert = "gender param must be male or female."
        assert gender in ("male", "female"), gassert
        call += ',"genders":[' + str(1 if gender == "male" else 2) + "]}"
    response = requests.get(url=call)
    data = response.json()
    data["age_min"] = age_min
    data["age_max"] = age_max
    data["gender"] = gender
    data["state"] = state
    data["time"] = str(datetime.datetime.now()).split('.')[0]
    return data
Exemple #13
0
  'objective': 'LINK_CLICKS',
  'status': 'PAUSED',
}
newcampaign = AdAccount(id).create_campaign(
  fields=fields,
  params=params,
)

print(newcampaign["id"])

params = {
    'q': 'baseball',
    'type': 'adinterest',
}

resp = TargetingSearch.search(params=params)
# print(resp[1])

targeting = {
    Targeting.Field.geo_locations: {
        Targeting.Field.countries: ['US'],
    },
    Targeting.Field.interests: [{'id':resp[1]["id"],'name':resp[1]["name"]}]  # https://developers.facebook.com/docs/marketing-api/buying-api/targeting#interests
}
# print(targeting)


# create ad set - v2.0 - https://github.com/facebook/facebook-python-business-sdk/blob/master/examples/AdAccountAdSetsPostReach.py
fields = [
]
params = {