Google Calendars API - Insert Event - Notify organizer by email - google-api

Using Google Calendars API /events/insert, I create an event in a user's calendar on their behalf and set them as the organizer. I also invite one guest.
I want the organizer to receive an email notification similar to what a guest might receive. I tried using the sendUpdates parameter but it only notifies guests.
Is there a way to notify the organizer that an event was created in their calendar on their behalf?

That is outside of what even Google Calendar can do. So this problem is unrelated to the API itself. Google calendar assumes that the organizer is the one creating the event so already knows it is being created so there is no reason to notify them.
You have access via Oauth2, there is no way the api knows that this is not the user themselves as your application has permission to preform actions on behalf of the user. So google calendar thinks you are the user so no reason to notify you.
Here's a work around I have used in the past.
As you already have write access on the calendar you should have access to see who the owner is by doing an acl.list this will get you their email address.
You could then have your application email them.
You can also invite them using an allies email address, however i have found some clients don't like this solution as they then appear twice.

One work around you can do is to add a another version of the owners email to the attendees. For example, if their normal email is test#gmail.com you can convert it to test+1#gmail.com. They'll receive an invite at their normal email. Keep in mind this will add an additional attendee to the event. When they click accept in the email it will mark their original email as accepted, not the one with +1 appended to it.
See this basic function for adding a +1 the email in JS:
function changeEmail(email) {
let splitEmail = email.split('#');
return splitEmail[0] + '+1#' + splitEmail[1];
}
Note you can add any text after the email. It doesn't have to be +1.

Answer:
As DaImTo has said, the API will not provide an email to the user who has created the event, which is exactly what your application is doing via OAuth2.
You can however take the event information from the response and manually send the user an Email using the Gmail API.
Example Code:
I do not know what language you are using, but as a python example, after getting the Gmail service with your service account credentials:
subject = "email#example.com"
delegated_credentials = service_account.Credentials.from_service_account_file(key_file_location, scopes=scopes, subject=subject)
gmail_service = discovery.build(api_name, api_version, credentials=delegated_credentials)
You can use the Sending Email tutorial to create and send an email on behalf of the user that created the event:
# Copyright 2020 Google LLC.
# SPDX-License-Identifier: Apache-2.0
def create_message(sender, to, subject, message_text):
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
return {'raw': base64.urlsafe_b64encode(message.as_string())}
def send_message(service, user_id, message):
try:
message = (service.users().messages().send(userId=user_id, body=message)
.execute())
print 'Message Id: %s' % message['id']
return message
except errors.HttpError, error:
print 'An error occurred: %s' % error
And then simply send the information to the user via email using the data already defined for the event insert call:
emailText = "Title: " + summary + "\nStart: " + startTime + "\nEnd: " + endTime
msg = create_message(subject, # the sub for the service account
subject, #to and from are the same
"A Calendar Event has been created on your behalf",
emailText)
send_message(gmail_service, calendar_response['creator']['email']
References:
Sending Email | Gmail API | Google Developers

Related

How to send a message to google hangouts with python?

I am trying to create a simple "chat bot" for google hangouts that sends regular messages on a chat. I found this documentation but I find it tremendously complicated.
It contains a "Complete example" but I am not sure about how to find the "space" ID for an existing google hangout chat. This is nowhere explained. How do I find the "space" ID for an existing google chat?
And in addition: Is there a SIMPLE (!!!) documentation somewhere how to just simply post a message to an existing chat?
Answer:
You can either use spaces.list to get a list of spaces the bot is a member of followed by spaces.get for additional information on the space, or alternatively set up a room-specific Webhook.
Additional Information:
To send messages to a room without a respond trigger, you must use a service account
Bot-initiated message documentation can be found here.
Important Note: You can only use the Google Hangouts Chat API if you have a Google Workspace account - it will not work with Gmail alone. The second solution, which uses a Webhook, requires access to https://chat.google.com which is only available to Google Workspace domains. Unfortunately this is not at all possible using a consumer #gmail.com account.
Using the Hangouts Chat API:
Once you have a service account set up as per Step 1 on this page, you can download the credentials for the service account from the Google Cloud Project UI, by clicking on the ⋮ button to the right of the service account name, and following the Create key button and selecting JSON as the key type. Make sure to save this file well as there is only one copy of this key.
With this JSON file downloaded, you can use it in your python code as the credentials when setting up your service object:
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
scopes = 'https://www.googleapis.com/auth/chat.bot'
credentials = ServiceAccountCredentials.from_json_keyfile_name(
'credentials.json', scopes)
chat_service = build('chat', 'v1', http=credentials.authorize(Http()))
To make the spaces.list request, you can use this newly built chat_service, and extract hte list of spaces from the response:
def extract(n):
return n['name']
spaces_list = chat_service.spaces().list().execute()
all_spaces = map(extract, spaces_list['spaces'])
You can then use one of these spaces to send a message from the python program:
response = chat_service.spaces().messages().create(
parent=all_spaces[0],
body={'text': 'Test message'}).execute()
print(response)
Things to Remember:
Make sure the Hangouts Chat API is enabled for your project at https://console.cloud.google.com
Once enabled, make sure the bot is configured with a name, logo and description.
The Connection settings for the bot must also be set up; the method is not so important; you can for example choose Apps Script project and enter the deployment ID for an empty deployed project.
Using a Webhook:
Instead of directly using the API, you can instead set up a webhook for a specific chat and with a hardcoded URL, you can send messages to a room from an external script.
The full steps are set out on this page but I'll go through it here also.
Go to the room to which you wish to send a message at https://chat.google.com, and from the dropdown menu next to the room's name, select Manage Webhooks.
Enter a name and an optional avatar for your bot, and press SAVE. This will give you a webhook URL to use in your python script.
Locally, make sure you have httplib2 installed in your environment, and copy the following script into a new .py file:
from json import dumps
from httplib2 import Http
def main():
"""Hangouts Chat incoming webhook quickstart."""
url = 'webhook-url'
bot_message = {
'text' : 'Hello from a Python script!'}
message_headers = {'Content-Type': 'application/json; charset=UTF-8'}
http_obj = Http()
response = http_obj.request(
uri=url,
method='POST',
headers=message_headers,
body=dumps(bot_message),
)
print(response)
if __name__ == '__main__':
main()
Manking sure to replace the webhook-url string with the webhook provided in the Chat UI in the previous step.
Now you can just save the file and run it - this will send a message automatically to the aforementioned chat space:
References:
Creating new bots | Google Chat API | Google Developers
Method: spaces.list | Google Chat API | Google Developers
Method: spaces.get | Google Chat API | Google Developers
REST Resource: spaces | Google Chat API | Google Developers
See this API, it's very interesting:
https://pypi.org/project/hangups/
There is some projects who uses Hangups, among then, HangupsBot:
https://github.com/xmikos/hangupsbot

Edit Google Calendar "From" and "Organizer"

I want to create event via google calendar api using Go. I found out that the sender (From) is whoever responsible in client_id I provide in the google API, in this case me. Can I edit this sender, so that it is not sent from me? At least I can edit the display name of the sender, the email I think will always be my email
Also about editing the organizer, I tried to use move action but it only moves the event, not change the organizer. Is there other way to edit organizer?
To address your questions:
1. Can I create an event from another address?
What you want can be done by creating a service account and performing domain-wide-delegation
What is a service account?
A service account is a special type of Google account intended to represent a non-human user that needs to authenticate and be authorized to access data in Google APIs - in your situation the Calendar API.
After creating the above mentioned service account, you will have to perform domain-wide-delegation and impersonate a user in your domain in order to be able to create the event wanted.
Now, when writing the code for your application, you will have the use the credentials that were created for this account in order to authorize the requests.
OR
If you want to specifically edit only the display name of the creator of the event, you can perform an update request:
PUT https://www.googleapis.com/calendar/v3/calendars/calendarId/events/eventId
And add in the request body this:
"creator": {
"displayName": "UPDATED DISPLAY NAME"
}
2. Can I edit the organizer?
According to the Calendar API Documentation:
organizer > The organizer of the event. If the organizer is also an attendee, this is indicated with a separate entry in attendees with the organizer field set to True. To change the organizer, use the move operation. Read-only, except when importing an event.
Therefore, the organizer can be changed/updated only when importing the event in question.
Reference
Authorizing Requests to the Google Calendar API
;
Creating A Service Account;
Calendar API Events Resource;
Calendar API Events:Update.

how to get email label from email id with gmail API?

i have a problem how to get label email (promotions, updates, forums etc) with Gmail API with low cost computational.
my app used IMAP-idle for getting a new email.
a was search and get that IMAP not support label (promotions, update etc)
the other way is using Gmail API
i know i can get a list of email id by label
but that too much computational
'new id from IMAP -> search that id in every list of label (4 label)->get the label'
it's that possible to get the label of the message with one call?
thanks
In the gmail web app you can search for lables label:friends in the Gmail api you can also search for messages
GET https://www.googleapis.com/gmail/v1/users/me/messages?q="label:friends"
the message.list method will then return all the messages within that label. If you have the message id which i am not sure is the same from imap to the gmail api you then you can do a message.get which will return the label as well

Getting Slack user email address for AWS Lex bot

I am creating a bot in aws-lex and will integrate it with Slack, FB Workplace and Yammer to start with.
I need to read the Slack user email address, then validate that against our webservice to ensure the user is registered. This will return some data about the users organisation that I need for further execution in lex.
I have no idea how to pass/extract the Slack user email (the one that is engaging in conversation with my Bot).
Any ideas?? Examples please! New to bot dev.
At least for slack you could do:
Under requestAttributes (from event) you can check the presence of x-amz-lex:channel-type. The value will be Slack if the user comes from slack.
You can then extract the user slack id from the event that is submitted to your lambda under the key userId
With that id, go to Slack API and call the method users.info. Now you can get the user email from the response.

How to know who send the invite?

I'm using the iOS Glympse SDK to send email invites.... and it works fine.
The email destination user is receiving a glympse invite but no indication of the user nickname sending the invite. The invitation title is "A friend share a glympse with you".
I would like to have "Fred share a glympse with you"
How to do that ?
Sounds like you're on the right track, the sender's nickname is used in the invite email's subject line.
Make sure the sender's nickname is being set at the correct time. It can only be set after the client app has synced with the Glympse server as described here: https://developer.glympse.com/docs/core/client-sdk/guides/common/programming-guide#configuring-user-profile
As described in that document, make sure to listen for the GE.PLATFORM_SYNCED_WITH_SERVER event and set the nickname for the sender at that time (or anytime after). This rule exists so that if the nickname or avatar was set on another device, the client will have up to date information before it tries to apply a new nickname.
Once the sync has occurred, the nickname of the sender is set like this
GUser user = glympse->getUserManager()->getSelf();
user->setNickname(CoreFactory::createString("Fred"));

Resources