Add custom audiences to an Ad Group with Adwords API - python

I am using the python librairy for Adwords and I need to select the audiences that I want to link to a given ad group. I need to select audiences that are either remarketing and similar, custom intent or affinity.
How can I set the audiences when creating an ad group?

So after some testing here is how to do it:
create the ad group and get its id
add the audience using AdGroupCriterionService
Here is my code for the 3 types of audiences I wanted to use (self.client is initiating adwords.AdWordsClient.LoadFromStorage):
ad_group_criterion_service = self.client.GetService('AdGroupCriterionService', version='v201809')
audience_custom_affinity = {
'xsi_type': 'BiddableAdGroupCriterion',
'adGroupId': 'my_ad_group_id',
'criterion': {
'xsi_type': 'CriterionCustomAffinity',
'type': 'CUSTOM_AFFINITY',
'customAffinityId': 'my_audience_id'
}
}
audience_custom_intent = {
'xsi_type': 'BiddableAdGroupCriterion',
'adGroupId': 'my_ad_group_id',
'criterion': {
'xsi_type': 'CriterionCustomIntent',
'type': 'CUSTOM_INTENT',
'customIntentId': 'my_audience_id'
}
}
audience_remarketing = {
'xsi_type': 'BiddableAdGroupCriterion',
'adGroupId': 'my_ad_group_id',
'criterion': {
'xsi_type': 'CriterionUserList',
'type': 'USER_LIST',
'userListId': 'my_audience_id'
}
}
operations = [
{'operator': 'ADD',
'operand': audience_custom_affinity},
{ 'operator': 'ADD',
'operand': audience_custom_intent},
{'operator': 'ADD',
'operand': audience_remarketing}
]
ad_group_criterion_service.mutate(operations)

Related

Python Google Analytics Active users list

I have a lot of potential users for my website (not open to the public).
I do have a Google Analytics account and everything is working well.
I don't want to iterate through all potential users because calling for each individual user will take a very long time (I have about 1200 users).
Instead, I want a list of only active users in the given time period.
Surely this must be possible
(Simple problem, I am happy to answer any questions as I know this is a very brief question I am asking)
EDITED:
I am working in python and need to write code to achieve this
If you're looking for a list of user ids that you can use with the user activity API, the analytics API has a dimension called 'ga:clientId' that you can call and then filter using the standard parameters - there's a list of options of what you can filter on here:
https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet#reportrequest
Depending on how you are describing 'active users', below is an example calling the REST API from python:
import requests
import json
credentials = #{ 'your credentials as a dict' }
r = requests.post("https://www.googleapis.com/oauth2/v4/token", data = {
"client_id": credentials["client_id"],
"client_secret": credentials["client_secret"],
"refresh_token": credentials["refresh_token"],
"grant_type": "refresh_token"
}
)
access_token =json.loads(r.text)
body = {
"reportRequests": [
{
'viewId': # "your ga view ID",
'pageSize': 100000,
"includeEmptyRows": True,
"samplingLevel": "LARGE",
'dateRanges': [
{
'startDate': "7DaysAgo",
'endDate': "yesterday"
}
],
'metrics': [
{
'expression': "ga:sessions"
}
],
'filtersExpression': "ga:sessions>2",
'dimensions': [
{
'name': "ga:clientId"
}
]
}
]
}
resp = requests.post("https://analyticsreporting.googleapis.com/v4/reports:batchGet",
json=body,
headers = {"Authorization" : "Bearer " + access_token["access_token"]}
)
resp = resp.json()
print(json.dumps(resp, indent = 4))
clientIds = [ x["dimensions"][0] for x in resp["reports"][0]["data"]["rows"] ]
print(clientIds)
To build on the answer above, you need to use a combination of the above plus the useractivity.list method.
I have written a full blog post on it https://medium.com/#alrowe/how-to-pull-out-the-user-explorer-report-with-python-useractivity-search-369bc5052093
Once you have used the above to get a list of client ids, you then need to iterate through those.
My 2 api calls look like this:
return analytics.reports().batchGet(
body = {
"reportRequests": [
{
'viewId': VIEW_ID,
'pageSize': 100000,
'includeEmptyRows': True,
'samplingLevel': 'LARGE',
'dateRanges': [
{
'startDate': '30DaysAgo',
'endDate': 'yesterday'
}
],
'metrics': [
{
'expression': 'ga:sessions'
}
],
'filtersExpression': 'ga:sessions>2',
'dimensions': [
{
'name': "ga:clientId"
}
]
}
]
}
).execute()
and then
def get_client_list_report(analytics,client_id):
return analytics.userActivity().search(
body = {
'user': {
'type': 'CLIENT_ID',
'userId': client_id
},
'dateRange':
{
'startDate': '30DaysAgo',
'endDate': 'yesterday'
},
'viewId': VIEW_ID,
'pageSize': 100000,
}
).execute()

Google Drive Export (Google Vault) for Specific User

Following the docs, there's an example to export all for a specific OU
def create_drive_ou_all_data_export(service, matter_id):
ou_to_search = 'ou id retrieved from admin sdk'
drive_query_options = {'includeSharedDrives': True}
drive_query = {
'corpus': 'DRIVE',
'dataScope': 'ALL_DATA',
'searchMethod': 'ORG_UNIT',
'orgUnitInfo': {
'org_unit_id': ou_to_search
},
'driveOptions': drive_query_options,
'startTime': '2017-03-16T00:00:00Z',
'endTime': '2017-09-23T00:00:00Z',
'timeZone': 'Etc/GMT+2'
}
drive_export_options = {'includeAccessInfo': False}
wanted_export = {
'name': 'My first drive ou export',
'query': drive_query,
'exportOptions': {
'driveOptions': drive_export_options
}
}
return service.matters().exports().create(
matterId=matter_id, body=wanted_export).execute()
However, it does not show how to just export for a given user, is this possible? Also, where are all of the different body options for creating an export? The examples do not seem to show all of the parameters available.
You'd want to use searchMethod:account
Reference Query: https://developers.google.com/vault/reference/rest/v1/Query
Reference searchmethod: https://developers.google.com/vault/reference/rest/v1/Query#SearchMethod
Reference AccountInfo: https://developers.google.com/vault/reference/rest/v1/Query#AccountInfo
drive_query = {
'corpus': 'DRIVE',
'dataScope': 'ALL_DATA',
'searchMethod': 'ACCOUNT', # This is different
'accountInfo': { # This is different
'emails': ['email1#company.com', 'email2#company.com', 'email3#company.com']
},
'driveOptions': drive_query_options,
'startTime': '2017-03-16T00:00:00Z',
'endTime': '2017-09-23T00:00:00Z',
'timeZone': 'Etc/GMT+2'
}

Eve: how to use different endpoints to access the same collection with different filters

I have an Eve app publishing a simple read-only (GET) interface. It is interfacing a MongoDB collection called centroids, which has documents like:
[
{
"name":"kachina chasmata",
"location":{
"type":"Point",
"coordinates":[-116.65,-32.6]
},
"body":"ariel"
},
{
"name":"hokusai",
"location":{
"type":"Point",
"coordinates":[16.65,57.84]
},
"body":"mercury"
},
{
"name":"caƱas",
"location":{
"type":"Point",
"coordinates":[89.86,-31.188]
},
"body":"mars"
},
{
"name":"anseris cavus",
"location":{
"type":"Point",
"coordinates":[95.5,-29.708]
},
"body":"mars"
}
]
Currently, (Eve) settings declare a DOMAIN as follows:
crater = {
'hateoas': False,
'item_title': 'crater centroid',
'url': 'centroid/<regex("[\w]+"):body>/<regex("[\w ]+"):name>',
'datasource': {
'projection': {'name': 1, 'body': 1, 'location.coordinates': 1}
}
}
DOMAIN = {
'centroids': crater,
}
Which will successfully answer to requests of the form http://hostname/centroid/<body>/<name>. Inside MongoDB this represents a query like: db.centroids.find({body:<body>, name:<name>}).
What I would like to do also is to offer an endpoint for all the documents of a given body. I.e., a request to http://hostname/centroids/<body> would answer the list of all documents with body==<body>: db.centroids.find({body:<body>}).
How do I do that?
I gave a shot by including a list of rules to the DOMAIN key centroids (the name of the database collection) like below,
crater = {
...
}
body = {
'item_title': 'body craters',
'url': 'centroids/<regex("[\w]+"):body>'
}
DOMAIN = {
'centroids': [crater, body],
}
but didn't work...
AttributeError: 'list' object has no attribute 'setdefault'
Got it!
I was assuming the keys in the DOMAIN structure was directly related to the collection Eve was querying. That is true for the default settings, but it can be adjusted inside the resources datasource.
I figured that out while handling an analogous situation as that of the question: I wanted to have an endpoint hostname/bodies listing all the (unique) values for body in the centroids collection. To that, I needed to set an aggregation to it.
The following settings give me exactly that ;)
centroids = {
'item_title': 'centroid',
'url': 'centroid/<regex("[\w]+"):body>/<regex("[\w ]+"):name>',
'datasource': {
'source': 'centroids',
'projection': {'name': 1, 'body': 1, 'location.coordinates': 1}
}
}
bodies = {
'datasource': {
'source': 'centroids',
'aggregation': {
'pipeline': [
{"$group": {"_id": "$body"}},
]
},
}
}
DOMAIN = {
'centroids': centroids,
'bodies': bodies
}
The endpoint, for example, http://127.0.0.1:5000/centroid/mercury/hokusai give me the name, body, and coordinates of mercury/hokusai.
And the endpoint http://127.0.0.1:5000/bodies, the list of unique values for body in centroids.
Beautiful. Thumbs up to Eve!

What "operations" do I use to get keyword search volume from the googleads api? (TargetingIdeaService)

I am trying to get a search volume metric from the Google Ads API. I am running into trouble when I using the "SearchVolumeSearchParameter" argument. This argument requires an "operation" field and the documentation does not do a great job on explaining what these operations can be. Preferably, I would like the script to return a list of keywords and their respective search volumes for the previous month.
adwords_client = adwords.AdWordsClient.LoadFromStorage()
targeting_idea_service = adwords_client.GetService(
'TargetingIdeaService', version='v201809')
selector = {
'ideaType': 'KEYWORD',
'requestType': 'STATS'
}
selector['requestedAttributeTypes'] = [
'KEYWORD_TEXT',
'SEARCH_VOLUME',
# 'TARGETED_MONTHLY_SEARCHES',
]
offset = 0
PAGE_SIZE = 500
selector['paging'] = {
'startIndex': str(offset),
'numberResults': str(PAGE_SIZE)
}
selector['searchParameters'] = [{
'xsi_type': 'SearchVolumeSearchParameter',
'operation': []
}]
page = targeting_idea_service.get(selector)
You use maximum, minimum like so:
selector['searchParameters'] = [
{
'xsi_type': 'RelatedToQuerySearchParameter',
'queries': search_keywords
},
{
'xsi_type': 'LocationSearchParameter',
'locations': [
{'id': location_id}
]
},
{
'xsi_type': 'SearchVolumeSearchParameter',
'operation': [
{'minimum': 100}
]
}
]

Set customer ID for Google Adwords API

I try to use the Google Adwords API, with the official library here : https://github.com/googleads/googleads-python-lib
I use an Manager Account on Google Adwords and want to work with my client's accounts.
I can get all the the Adwords account ID (like 123-456-7891) but I don't know how to pass the account ID to my Google Adwords functions as a parameter.
Here's my main function :
def main(argv):
adwords_client = adwords.AdWordsClient.LoadFromStorage(path="googleads.yaml")
add_campaign(adwords_client)
I see any Account ID parameter in the official samples, as :
import datetime
import uuid
from googleads import adwords
def add_campaign(client):
# Initialize appropriate services.
campaign_service = client.GetService('CampaignService', version='v201809')
budget_service = client.GetService('BudgetService', version='v201809')
# Create a budget, which can be shared by multiple campaigns.
budget = {
'name': 'Interplanetary budget #%s' % uuid.uuid4(),
'amount': {
'microAmount': '50000000'
},
'deliveryMethod': 'STANDARD'
}
budget_operations = [{
'operator': 'ADD',
'operand': budget
}]
# Add the budget.
budget_id = budget_service.mutate(budget_operations)['value'][0][
'budgetId']
# Construct operations and add campaigns.
operations = [{
'operator': 'ADD',
'operand': {
'name': 'Interplanetary Cruise #%s' % uuid.uuid4(),
# Recommendation: Set the campaign to PAUSED when creating it to
# stop the ads from immediately serving. Set to ENABLED once you've
# added targeting and the ads are ready to serve.
'status': 'PAUSED',
'advertisingChannelType': 'SEARCH',
'biddingStrategyConfiguration': {
'biddingStrategyType': 'MANUAL_CPC',
},
'endDate': (datetime.datetime.now() +
datetime.timedelta(365)).strftime('%Y%m%d'),
# Note that only the budgetId is required
'budget': {
'budgetId': budget_id
},
'networkSetting': {
'targetGoogleSearch': 'true',
'targetSearchNetwork': 'true',
'targetContentNetwork': 'false',
'targetPartnerSearchNetwork': 'false'
},
# Optional fields
'startDate': (datetime.datetime.now() +
datetime.timedelta(1)).strftime('%Y%m%d'),
'frequencyCap': {
'impressions': '5',
'timeUnit': 'DAY',
'level': 'ADGROUP'
},
'settings': [
{
'xsi_type': 'GeoTargetTypeSetting',
'positiveGeoTargetType': 'DONT_CARE',
'negativeGeoTargetType': 'DONT_CARE'
}
]
}
}, {
'operator': 'ADD',
'operand': {
'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(),
'status': 'PAUSED',
'biddingStrategyConfiguration': {
'biddingStrategyType': 'MANUAL_CPC'
},
'endDate': (datetime.datetime.now() +
datetime.timedelta(365)).strftime('%Y%m%d'),
# Note that only the budgetId is required
'budget': {
'budgetId': budget_id
},
'advertisingChannelType': 'DISPLAY'
}
}]
campaigns = campaign_service.mutate(operations)
How can I tell Adwords API in which account I want to add this campaign ?
Thanks for your help !
OK my bad, I missed a documentation method (http://googleads.github.io/googleads-python-lib/googleads.adwords.AdWordsClient-class.html#SetClientCustomerId).
# ID of your customer here
CUSTOMER_SERVICE_ID = '4852XXXXX'
# Load customer account access
client = adwords.AdWordsClient.LoadFromStorage(path="googleads.yaml")
client.SetClientCustomerId(CUSTOMER_SERVICE_ID)
And the customer ID is now associate with the AdwordsClient variable as "client" set as parameters for other functions.

Categories