Skip to content

Instantly share code, notes, and snippets.

@gesslar
Last active April 13, 2021 20:41
Show Gist options
  • Save gesslar/bb7201a035974e827adfa6cce92a0e63 to your computer and use it in GitHub Desktop.
Save gesslar/bb7201a035974e827adfa6cce92a0e63 to your computer and use it in GitHub Desktop.
Gmail Notifications to Chat - Notify on Google Chat when new messages/threads specified labels appear
/**
* Email Notifications to Chat
*
* Attach this script to a Sheet with two columns
* Column A - Label
* Column B - Webhook
*
* NOTE: This script will skip the first row and only use the first two columns.
*
* In column A (Label), list all of the labels for which you would like to receive notifications in Chat.
* In column B (Webhook), list the corresponding webhook to which you would like those notifications to be sent.
*
* Messages will be detected by these labels and ultimately these labels will be removed once processing is completed.
*
* Setup a time trigger to run the script to excute the run function.
*/
const run = () => {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
const sheets = spreadsheet.getSheets()
const config = sheets[0];
const range = config.getDataRange()
const values = range.getValues()
// Remove first row which has column labels Label and Webhook
values.shift()
values.forEach( value => {
const label = value[0];
const webhook = value[1];
if(label === "" || webhook === "") return
const query = `label:${label}`
const threads = GmailApp.search(query)
threads.forEach( thread => {
const threadLabels = thread.getLabels()
threadLabels.forEach( threadLabel => {
if(threadLabel.getName() === label) {
thread.removeLabel(threadLabel)
}
})
sendChatMessage( label, thread, webhook)
})
})
}
const sendChatMessage = (label, thread, webhook) => {
const payload =
{
sender:
{
displayName: "Robot",
avatarUrl: "https://goo.gl/8oz4jG"
},
cards:
[
{
header:
{
title: thread.getFirstMessageSubject(),
subtitle: "New Message in Gmail Conversation"
},
sections:
[
{
widgets:
[
{
keyValue:
{
topLabel: "Label",
content: label
}
},
{
buttons:
[
{
textButton:
{
text: "Take me to the Thread",
onClick:
{
openLink:
{
url: thread.getPermalink()
}
}
}
}
]
}
]
}
]
}
]
}
const response = UrlFetchApp.fetch(webhook, {
headers: {
'Content-Type': 'application/json; charset=UTF-8'
},
method: "POST",
payload: JSON.stringify(payload)
})
Logger.log(response.getContentText())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment