Set customer ID for Google Adwords API - python

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.

Related

Google Calendar API drops "conferenceData" nested object

EDIT: This is has been identified as a bug here.
I am trying to make a Google Meet along with a new calendar event. However, for some reason the returning event does not include any conferenceData, not even one with status fail.
Here is my code. I have omitted the authentication step as I do not get an authentication error.
def generateMeet(emails=None, fake=False):
if emails is None:
emails = []
if fake:
return "https://www.google.com", get_random_string(10)
now = datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
inonehour = (datetime.utcnow() + timedelta(hours=1)).isoformat() + 'Z'
event = {
'summary': 'Orb Meeting',
'start': {
'dateTime': now,
'timeZone': 'America/New_York',
},
'end': {
'dateTime': inonehour,
'timeZone': 'America/New_York',
},
'sendUpdates': "none",
'reminders': {
'useDefault': False,
},
'attendees': [{'email': x} for x in emails],
'conferenceDataVersion': 1,
'conferenceData': {
'createRequest': {
'requestID': get_random_string(10),
'conferenceSolutionKey': {
'type': 'hangoutsMeet'
},
}
}
}
ret = service.events().insert(calendarId='primary', body=event).execute()
return ret['conferenceData']['entryPoints'], ret['id']
This returns a key error, as conference data does not exist. Here is the full 'ret' object before I run the return:
{'kind': 'calendar#event', 'etag': '"3197938620273000"', 'id': '5fb6epfe93sceba9scjt1nevsk', 'status': 'confirmed',
'htmlLink': 'https://www.google.com/calendar/event?eid=NWZiNmVwZmU5M3NjZWJhOXNjanQxbmV2c2sgZm9ycmVzdG1pbG5lckBt',
'created': '2020-09-01T14:08:30.000Z', 'updated': '2020-09-01T14:08:30.162Z', 'summary': 'Orb Meeting',
'creator': {'email': '[my email]', 'self': True},
'organizer': {'email': '[my email]', 'self': True},
'start': {'dateTime': '2020-09-01T10:08:28-04:00', 'timeZone': 'America/New_York'},
'end': {'dateTime': '2020-09-01T11:08:28-04:00', 'timeZone': 'America/New_York'},
'iCalUID': '5fb6epfe93sceba9scjt1nevsk#google.com', 'sequence': 0,
'attendees': [{'email': '[my other email]', 'displayName': 'Forrest Milner', 'responseStatus': 'needsAction'}],
'reminders': {'useDefault': False}}
Can anyone tell me why the conferenceData part of my request might be dropped? I am setting the conferenceDataVersion to 1, and using a random string.
I have tried adding dummy "invitees". In this trial, I invited my second gmail account, and in other trials I have invited several dummy accounts with domain "example.com". This updates the attendees, but does not make the conference data appear.
I have also tried waiting a few minutes and then listing all my events. Even after waiting, the conference data was not filled in. When I check my calendar on the GUI (https://calendar.google.com/calendar/r) it also does not have a Google Meet attached.
Thank you for any help.
Yes, it is a bug, if it's high priority you can 'patch' your created event with something like this:
const eventPatch = {
conferenceData: {
createRequest: { requestId: "yourRandomString" },
},
};
let response = await calendar.events.patch({
calendarId: 'primary',
eventId: "createdEventID",
resource: eventPatch,
sendNotifications: true,
conferenceDataVersion: 1,
});
Reference: https://developers.google.com/calendar/create-events#conferencing
The conferenceDataVersion It's not a part of requestBody anymore. Must be passed inside your insert method.
On NodeJS it's something like this:
calendar.events.insert({
calendarId: 'calendarIdHere',
requestBody: yourOldRequestBodyObject,
conferenceDataVersion: 1
});
#André Eccel is correct. Here's a working Python example of how to add a google meet link to your event:
import uuid
request_id = str(uuid.uuid1())
event = {'summary': "My Birthday Party",
'description': "There will be flamingos.",
'start': start,
'end': end,
'recurrence':recurrence,
'attendees': attendees,
'conferenceData': {'createRequest': {
'requestId': request_id,
"conferenceSolutionKey": {"type": "hangoutsMeet"}}}
}
service.events().insert(calendarId=cal_id,body=event,conferenceDataVersion=1).execute()

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'
}

Add custom audiences to an Ad Group with Adwords API

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)

How to specify device fingerprint id in Cybersource REST API?

I'm trying to integrate CyberSource's REST API into a Django (Python) application. I'm following this GitHub example example.
It works like a charm but it is not clear to me from the example or from the documentation how to specify the device's fingerprint ID.
Here's a snippet of the request I'm sending in case it comes useful (note: this is just a method that lives inside a POPO):
def authorize_payment(self, card_token: str, total_amount: Money, customer: CustomerInformation = None,
merchant: MerchantInformation = None):
try:
request = {
'payment_information': {
# NOTE: REQUIRED.
'card': None,
'tokenized_card': None,
'customer': {
'customer_id': card_token,
},
},
'order_information': {
'amount_details': {
'total_amount': str(total_amount.amount),
'currency': str(total_amount.currency),
},
},
}
if customer:
request['order_information'].update({
'bill_to': {
'first_name': customer.first_name,
'last_name': customer.last_name,
'company': customer.company,
'address1': customer.address1,
'address2': customer.address2,
'locality': customer.locality,
'country': customer.country,
'email': customer.email,
'phone_number': customer.phone_number,
'administrative_area': customer.administrative_area,
'postalCode': customer.zip_code,
}
})
serialized_request = json.dumps(request)
data, status, body = self._payment_api_client.create_payment(create_payment_request=serialized_request)
return data.id
except Exception as e:
raise AuthorizePaymentError from e

Categories