Exemplo n.º 1
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    token = 'EAAatqMY9YeQBAKo2WiunzO8xaxA0YwqQXfflxCLKuZAZA75i44dndFAYrXP1wwiaDnNElMPy28HalSgz52vI8qkSyW45u8C96o8MZA0hPQU8SA9ZCOhFKoySma4HZAtMR7JLZB262BEY6jDMIEPaKe2P4tTIsdllZBsrmWPyJjCh3of5Tl1hXRZBMG8kZBtM6ViNapBVpbrHw0tSqVPcwe9a9'
    FacebookAdsApi.init(access_token=token)

    params = {
        'q': name,
        'limit': 10000000,
        'locate': 'pt_br',
        'type': 'adinterest',
    }

    name = TargetingSearch.search(params=params)

    if name:
        return func.HttpResponse(f"Hello {name}!")
    else:
        return func.HttpResponse(
            "Please pass a name on the query string or in the request body",
            status_code=400)
Exemplo n.º 2
0
def getInterestsByKeyword(keyword):
    params ={
        'q': keyword,
        'type': 'adinterest'
    }
    resp = TargetingSearch.search(params=params)
    return resp
Exemplo n.º 3
0
def getInterestSuggestionByInterestList(keywords):
    params = {
    'type': 'adinterestsuggestion',
    'interest_list': keywords,
    }
    resp = TargetingSearch.search(params=params)
    return resp
Exemplo n.º 4
0
def getAllCategories():
    params = {
        'type': 'adTargetingCategory',
        'class': 'interests',
    }
    resp = TargetingSearch.search(params=params)
    return resp
Exemplo n.º 5
0
def get_country_ids():
    params = {
        'q': 'indonesia',
        'type': 'adgeolocation',
        'location_types': ['country'],
    }
    resp = TargetingSearch.search(params=params)
    print(resp)
Exemplo n.º 6
0
def validateInterests(keywords):
    params = {
        'type': 'adinterestvalid',
        'interest_list': keywords
    }

    resp = TargetingSearch.search(params=params)
    return resp
def validateInterestIdByInterest(api, list_interests):
    params = {
        'type': 'adinterestvalid',
        #             'interest_list': list_interests,
        'interest_fbid_list': list_interests,
    }
    resp = TargetingSearch.search(params=params, api=api)
    return resp
Exemplo n.º 8
0
 def getInterestIDFromText(self, text):
     params = {
         'q': text,
         'type': 'adinterest',
         'limit': 1000,
     }
     resp = TargetingSearch.search(params=params, api=self.api)
     return resp
Exemplo n.º 9
0
def get_interest_ids():
    params = {
        'q': 'puppy',
        'type': 'adinterest'
    }

    resp = TargetingSearch.search(params=params)
    print(resp)
Exemplo n.º 10
0
    def getSuggestions(self, element):
        params = {
            'type': TargetingSearch.TargetingSearchTypes.interest_suggestion,
            'interest_list': list(element),
            'limit': 1000
        }

        resp = TargetingSearch.search(params=params, api=self.api)
        return resp
def get_cities(name):
    params = {
        'q': name,
        'type': 'adgeolocation',
        'location_types': ['city'],
    }

    resp = TargetingSearch.search(params=params)
    print(resp)
    return resp
def getInterestIDFromText(api, text):

    #     print text.decode('utf-8')
    params = {
        'q': text,
        'type': 'adinterest',
        'limit': 1000,
    }
    resp = TargetingSearch.search(params=params, api=api)
    return resp
def add_to_adinterests(interest,cursor):
	logging.info('Searching Facebok for adinterest '+interest)
	params = {
		'q': interest,
		'type': 'adinterest'
	}

	resp = TargetingSearch.search(params=params)[0]
	resp=json.loads(str(resp).replace('<TargetingSearch> ',''))
	cursor.execute("insert into adinterests (interest_name,interest_id) values ('"+interest.replace('\'','')+"','"+resp['id']+"')")
	return resp['id']
def getBehavior(query):
    api = getFacebookAPI(100)
    #     api = getFacebookAPI()
    params = {
        'q': query,
        'type': 'adTargetingCategory',
        'class': 'behaviors'
        #     TargetingSearch.DemographicSearchClasses.generation
    }

    resp = TargetingSearch.search(params=params, api=api)
    print(resp)
Exemplo n.º 15
0
 def getLocationElement(self, element, location_type="country"):
     # type=adgeolocation&location_types=['region']:
     params = {
         'q': element,
         'type': 'adgeolocation',
         # 'location_types': ['city'],
         # 'location_types': ['region'],
         'location_types': [location_type],
         # 'countries': ['US']
         # 'match_country_code' :True
     }
     responses = TargetingSearch.search(params=params, api=self.api)
     return responses
Exemplo n.º 16
0
def handle_error(interest_):
    number_tries = 0
    while number_tries < 5:
        try:
            params = {
                'type': 'adinterestsuggestion',
                'interest_list': [interest_],
            }
            resp = TargetingSearch.search(params=params)
            return resp
        except:
            number_tries += 1
            time.sleep(SLEEP_TIME * number_tries)
    return None
Exemplo n.º 17
0
def define_targeting(q):
    from facebookads.adobjects.targetingsearch import TargetingSearch
    from facebookads.adobjects.targeting import Targeting

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

    interests = TargetingSearch.search(params=params)

    targeting = {
        Targeting.Field.geo_locations: {
            Targeting.Field.countries: ['US'],
        },
        Targeting.Field.interests: interests,
    }
    return targeting
def mine_suggestions(suggestion_data, max_suggestions=2000):
    """
    Mine suggestions for all interests provided, add suggestions
    to queue, keep mining until we hit the max.
    
    :param suggestion_data: list of suggested interest names
    :param max_suggestions: max number of suggestions to mine
    :return:: new_suggestion_data: Name, ID info for all new suggestions.
    """
    access_token, user_id, app_id, app_secret = load_facebook_auth()
    session = FacebookSession(app_id, app_secret, access_token)
    api = FacebookAdsApi(session)
    new_suggestion_data = pd.DataFrame()
    suggestion_queue = []
    suggestion_queue += suggestion_data
    suggestions_per_query = 1
    relevant_cols = ['id', 'name', 'topic', 'path', 'audience']
    while(new_suggestion_data.shape[0] < max_suggestions and 
          len(suggestion_queue) > 0):
        s = suggestion_queue[:suggestions_per_query]
        print('total data=%d; processing suggestions %s'%
              (new_suggestion_data.shape[0], ','.join(s)))
        suggestion_queue = suggestion_queue[suggestions_per_query:]
        params = {
                'type' : 'adinterestsuggestion',
                'interest_list' : s,
                }
        s_results = TargetingSearch.search(params=params, api=api)
        s_df = pd.DataFrame(s_results)
        s_df = s_df.loc[:, set(relevant_cols) & set(s_df.columns)]
        # temp: restrict to top-k results to stay on-topic
        s_df = s_df.iloc[:25, :]
        # remove duplicates
        if(s_df.shape[0] > 0):
            if(new_suggestion_data.shape[0] > 0):
                s_df = s_df[~s_df.loc[:, 'id'].isin(new_suggestion_data.loc[:, 'id'])]
            new_suggestion_data = new_suggestion_data.append(s_df)
            # add new names to suggestion data
            suggestion_queue += s_df.loc[:, 'name'].values.tolist()
    return new_suggestion_data
Exemplo n.º 19
0
def search_interest(request):

    if (request.method == "POST"):
        new_data = request.POST['term']
        arr = new_data.split(' , ')
        new_location = InterestModel(
            id=arr[0],
            name=arr[1],
            path=arr[2],
            topic=arr[3],
            audience_size=arr[4],
        )
        new_location.save()

        return HttpResponse("success")
    params = get_interest_params(request.GET['term'])
    resp = TargetingSearch.search(params=params)
    resp = list(
        map(
            lambda x: str(x["id"]) + " , " + x["name"] + " , " + x["path"][0] +
            " , " + x["topic"] + ' , ' + str(x["audience_size"]), list(resp)))
    return HttpResponse(json.dumps(resp))
Exemplo n.º 20
0
def search_location(request):

    if (request.method == "POST"):
        new_data = request.POST['term']
        arr = new_data.split(' , ')
        new_location = LocationModel(key=arr[0],
                                     name=arr[1],
                                     region_id=arr[2],
                                     region=arr[3],
                                     country=arr[4],
                                     country_code=arr[5])
        new_location.save()

        return HttpResponse("success")

    params = get_location_params(request.GET['term'])
    resp = TargetingSearch.search(params=params)

    resp = list(
        map(
            lambda x: str(x["key"]) + " , " + x["name"] + " , " + str(x[
                "region_id"]) + " , " + x["region"] + " , " + x["country_name"]
            + " , " + str(x["country_code"]), list(resp)))
    return HttpResponse(json.dumps(resp))
Exemplo n.º 21
0
 def targeting_search(self, ad_interest):
     params = {'q': ad_interest, 'type': 'adinterest'}
     resp = TargetingSearch.search(params=params)
     return resp
Exemplo n.º 22
0
from facebookads.adobjects.targetingsearch import TargetingSearch
params = {
    'type': 'adTargetingCategory',
    'class': 'interests',
}

resp = TargetingSearch.search(params=params)
print(resp)

#https://graph.facebook.com/2.1/search/type=adTargetingCategory&class=interests
#https://graph.facebook.com/2.1/search/type=adTargetingCategory&class=behaviors
'''
try to use requests package

'''
Exemplo n.º 23
0
def run():
    resp = TargetingSearch.search(params)
    print(resp)
Exemplo n.º 24
0
from facebookads.adobjects.targetingsearch import TargetingSearch
import initialization
params = {
    'q': 'un',
    'type': 'adgeolocation',
    'location_types': ['country'],
}

resp = TargetingSearch.search(params=params, api=None)
print(resp)
Exemplo n.º 25
0
def create_adset():
    choice = raw_input(
        "Please enter yes to create a new campaign and anything else to to enter id for existing campaign.\n"
    ).lower()
    print choice
    if 'yes' in choice:
        campaign_id = campaign.create_campaign()
    else:
        campaign_id = raw_input("Please enter campaign id.\n")
    query = raw_input("Enter query for targeting customer type.\n")
    params = {
        'q': query,
        'type': 'adinterest',
    }

    resp = TargetingSearch.search(params=params)
    print resp
    resp = json.loads(str(resp).replace('<TargetingSearch> ', ''))
    print(resp)

    number_of_interests = int(raw_input("Please enter number of interests.\n"))
    interest_list = []
    for i in xrange(number_of_interests):
        a = int(raw_input("Enter Interest Ids.\n"))
        interest_list.append(a)

    number_of_countries = int(
        raw_input("Please enter number of countries for targeting.\n"))
    country_list = []
    for i in xrange(number_of_countries):
        a = raw_input("Enter Country Codes.\n")
        country_list.append(a)
    age_min = raw_input("Please enter minimum targeting age.\n")
    age_max = raw_input("Please enter maximum targeting age.\n")
    targeting = {
        Targeting.Field.geo_locations: {
            Targeting.Field.countries: country_list,
        },
        Targeting.Field.interests: interest_list,
        Targeting.Field.age_min: age_min,
        Targeting.Field.age_max: age_max,
    }

    adset_name = raw_input("Please enter a name for the adset.\n")
    daily_budget = int(raw_input("Please enter daily_budget(in paise).\n"))
    bid_amount = int(raw_input("Please enter bid_amount(in paise).\n"))
    start_time = raw_input(
        "Please enter start date for AdSet format(YYYY-MM_DD).\n")
    end_time = raw_input(
        "Please enter end date for AdSet format(YYYY-MM_DD).\n")

    adset = AdSet(parent_id=header.my_account['id'])
    adset.update({
        AdSet.Field.name: adset_name,
        AdSet.Field.campaign_id: campaign_id,
        AdSet.Field.daily_budget: daily_budget,
        AdSet.Field.billing_event: AdSet.BillingEvent.impressions,
        AdSet.Field.optimization_goal: AdSet.OptimizationGoal.reach,
        AdSet.Field.bid_amount: bid_amount,
        AdSet.Field.targeting: targeting,
        AdSet.Field.start_time: start_time,
        AdSet.Field.end_time: end_time,
    })

    adset.remote_create(params={
        'status': AdSet.Status.paused,
    })
    adset = json.loads(str(adset).replace('<AdSet> ', ''))
    return adset['id']
Exemplo n.º 26
0
params_disneyprincess = {       # Interest: Disney Princesses
    'q': 'Disney Princess',
    'type': 'adinterest'
}
params_frozenmovie = {          # Interest: Frozen Movie
    'q': 'Frozen (2013 film)',
    'type': 'adinterest'
}
params_frozenfranchise = {      # Interest: Frozen Franchise
    'q': 'Frozen (franchise)',
    'type': 'adinterest'
}

# Run TargetingSearch.searc(params) to get the actual interests corresponding
#   to the queries above. 
int_charity = TargetingSearch.search(params=params_charity)
int_commissues = TargetingSearch.search(params=params_commissues)
int_volunteering = TargetingSearch.search(params=params_volunteering)
int_nonprofitorg = TargetingSearch.search(params=params_nonprofitorg)

int_animal = TargetingSearch.search(params=params_animal)
int_disneychannel = TargetingSearch.search(params=params_disneychannel)
int_disneyprincess = TargetingSearch.search(params=params_disneyprincess)
int_frozenmovie = TargetingSearch.search(params=params_frozenmovie)
int_frozenfranchise = TargetingSearch.search(params=params_frozenfranchise)

# Specify Targeting
targeting = {
    # Specify radius of 12 miles around New Delhi
    'geo_locations': {
        'cities' : [{'key':'1037239', 'radius':12, 'distance_unit':'mile'}]
Exemplo n.º 27
0
#Llamadas Interesess

####
from facebookads.api import FacebookAdsApi
from facebookads.adobjects.targetingsearch import TargetingSearch

FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)

params = {
    'q': 'veganos',
    'type': 'adinterest',
    'limit': 80,
}

resp = TargetingSearch.search(params=params)
print(resp)

import pandas as pd

Intereses = pd.DataFrame(resp)
Intereses.columns
Intereses = Intereses.sort_values(by='audience_size', ascending=False)

####
results = TargetingSearch.search(
    params={
        'q': 'United States',
        'type': TargetingSearch.TargetingSearchTypes.country,
        'limit': 2,
    })
Exemplo n.º 28
0
ad_set[AdSet.Field.name] = variable + ' ' + target_location
ad_set[
    AdSet.Field.optimization_goal] = AdSet.OptimizationGoal.offsite_conversions
ad_set[AdSet.Field.destination_type] = "WEBSITE"
ad_set[AdSet.Field.promoted_object] = {
    'pixel_id': 'YOURPIXELID',
    'custom_event_type': 'PURCHASE',
}
ad_set[AdSet.Field.billing_event] = AdSet.BillingEvent.impressions
ad_set[AdSet.Field.is_autobid] = True
ad_set[AdSet.Field.daily_budget] = daily_budget
ad_set[AdSet.Field.start_time] = datetime.datetime.now()
targeting = {}

params_location = {'q': target_location, 'type': 'adgeolocation'}
location = TargetingSearch.search(params=params_location)

if is_target_city:
    targeting[Targeting.Field.geo_locations] = {
        "cities": {
            "key": location[0]['key']
        },
    }
else:
    targeting[Targeting.Field.geo_locations] = {
        "countries": location[0]['country_code'].split()
    }

params_interest = {
    'q': variable,
    'type': 'adinterest',