Google Calendar API drops "conferenceData" nested object - python

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()

Related

python script to create the cloud function

We have written python script to create the cloud function , the trigger is Https. We need to invoke fetch the output of the function , So for that we are using the environment variables but some how that is not getting stored ?
def generate_config(context):
""" Entry point for the deployment resources. """
name = context.properties.get('name', context.env['name'])
project_id = context.properties.get('project', context.env['project'])
region = context.properties['region']
resources = []
resources.append(
{
'name': 'createfunction',
'type': 'gcp-types/cloudfunctions-v1:projects.locations.functions',
'properties':
{
'function': "licensevalidation",
'parent': 'projects//locations/',
'sourceArchiveUrl': 'gs://path',
'entryPoint':'handler',
'httpsTrigger': {"url": "https://.cloudfunctions.net/licensevalidation","securityLevel": "SECURE_ALWAYS"},
'timeout': '60s',
'serviceAccountEmail' : '.iam.gserviceaccount.com',
'availableMemoryMb': 256,
'runtime': 'python37' ,
'environmentvaiable' :
}
}
)
call ={
'type': 'gcp-types/cloudfunctions-v1:cloudfunctions.projects.locations.functions.call',
'name': 'call',
'properties':
{
'name':'/licensevalidation',
'data': '{""}'
},
'metadata': {
'dependsOn': ['createfunction']
}
}
resources.append(call)
return{
'resources': resources,
'outputs':
[
{
'name': 'installationtoken',
'value': 'os.environ.get(environment_variable)'
},
]
}

Google calendar API get to update keep on giving 404

I am trying to get the calendar event so I can then update it as the document shows.
My assumption was that an event with such JSON:
{
'kind': 'calendar#event',
'etag': '"32...000"',
'id': '6oo....jsa',
'status': 'confirmed',
'htmlLink': 'https://www.google.com/calendar/event?eid=Nm...YjhAZw',
'created': '2021-02-25T20:13:18.000Z',
'updated': '2021-02-28T01:21:43.762Z',
'summary': 'code',
'creator': {
'email': 'example#gmail.com'
},
'organizer': {
'email': 'abc#group.calendar.google.com',
'displayName': 'Website',
'self': True
},
'start': {
'dateTime': '2021-02-27T23:30:00-05:00'
},
'end': {
'dateTime': '2021-02-28T00:00:00-05:00'
},
'iCalUID': 'xyz#google.com',
'sequence': 27,
'reminders': {
'useDefault': True
},
'eventType': 'default'
}
The calendarId would be iCalUID & the eventId would be id or even the id after the calendar url. However, trying both of those interchangeably from the google API platform keeps on giving:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "Not Found"
}
],
"code": 404,
"message": "Not Found"
}
}
What should I do different?
My ultimate goal is to modify the event's summary, startTime & endTime for any event with a calendarID and eventID, hence my code:
def modifying():
credentials = google.oauth2.credentials.Credentials(
**flask.session['credentials'])
flask.session['credentials'] = credentials_to_dict(credentials)
service = build('calendar', 'v3', credentials=credentials)
event = {
'summary': 'modified',
'location': '',
'description': '',
'start': {
'dateTime': '2021-02-27T17:09:25.993663-05:00',
'timeZone': 'America/Los_Angeles',
},
'end': {
'dateTime': '2021-02-27T21:09:25.993663-05:00',
'timeZone': 'America/Los_Angeles',
}
}
try:
events_result =service.calendarList().list().execute()
events = events_result.get('items', [])
Ids = [item['id'] for item in events] #do this so it can search across all calendars & not just 'primary'
service.events().update(calendarId=Ids, eventId='6oo....jsa', body=event).execute()
return 200
except Exception as err:
print(err)
return {"message":"Server under maintenance"}
P.S: I have already tried all the solutions in the SO post as shown.
First off you are doing a calendarlist.list
events_result =service.calendarList().list().execute()
Which Returns the calendars on the user's calendar list.
The response from that being a list of calendar resources
You then appear to be trying to update a static event id '6oo....jsa' on the first calendar that is returned by the calendar list response.
service.events().update(calendarId=Ids, eventId='6oo....jsa', body=event).execute()
How exactly do you know that this static event id is even part of that calendar? Which is why you are getting a 404 it does not exist.
Why not do a events.list in order to get a list of the events on the calendar. Or even better if you don't mind getting an error just do a event.get on the calendar for your static event id.
BTW event.list wont return a calendar id in the response as its assumed that you already know the calendar id since you used it go get the events in the first place.
Solution
To update an event with Python you need to use the method update of the calendar service:
service.events().update(calendarId=calendarId, eventId=eventId, body=body).execute()
The request body must contain the start and end dates of the event.
How to update an event having the summary
List all the events on a specific calendar (primary for the default calendar)
Check the summary of all the events until you find one that matches your search
Keep the id, start and end dates
summarySearch = 'old summary'
events = service.events().list(calendarId=calendarId).execute()
for ev in events['items']:
try:
print(ev['summary'])
if ev['summary'] == summarySearch:
eventId = ev['id']
startDate = ev['start']['date']
endDate = ev['end']['date']
except:
print('empty summary')
Define the new summary (and all the fields to update)
Define the body request. It can be easily constructed with Try this API
Update the event
#startDate = '2021-02-16' # uncomment to overwrite
#endDate = '2021-02-18' # uncomment to overwrite
summary = 'new summary'
body = {
'start': {'date': startDate},
'end': {'date': endDate},
'summary': summary
}
result = service.events().update(calendarId=calendarId, eventId=eventId, body=body).execute()
Print the result to check that the event has been updated successfully
Some notes
I keep the start and end dates because they are mandatory to update an event. If you want to overwrite them is okay and you don't have to store them previously, but I wanted to give a solution that can fit in more situations.
Reference
Events: update
Events: list

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

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.

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