In this tutorial, we follow the adventures of Captain Webhook and his crew in their insatiable desire to report their latest booty conquest to me via Google Chat webhooks…
That, dear readers, did not come out right.
Webhooks are HTTP POST requests that are usually generated by a triggered event. The event could come from any third-party source within Google Workspace like:
When a user submits a form or clicks a button on a WebApp.
Patreon when another awesome supporter shows you some love.
Or when a rather rambunctious figment of my imagination insists on updating me when his latest haul of treasure has come in… live.
Sigh.
Chat App webhooks will need an intermediary step for them to be compiled in a way that the Google Chat API can understand. We’ve chosen Google Apps Script here to do this, but you can choose to use any other language to convert your data into Chat API readable JSON or even build in a CLI to post your webhook request.
Have you ever wanted to convert currencies instantly while in Google Chat with colleagues and clients? In this tutorial, we are going to build a Currency Converter Google Chat App with Google Apps Script to do just that.
This tutorial is a multi-media series containing step-by-step video instructions for each stage of the process along with code snippets for each stage, important links and some further details on the more unusual parts of the code.
We start off our project adventure having already made a copy of the Google Apps Script Chat App project, connecting it to a Google Cloud Platform (GCP) project and deploying it for the first time. You can find out how to set up this stage by heading over to the Google Chat Apps for Google Apps Script Developers tutorial or directly to the YouTube tutorial.
It is important to note that Chat Apps and their development are only available for Google Workspace paid accounts.
Table of Contents
What we are Building
In this tutorial, we will be creating a Currency Converter chat app that generates a currency conversion based on a slash command inside Google Chat or Space. The syntax will be:
/xe amount from_currency_code:to_currency_code
For example:
/xe 1,230.95AUD:USD
This will return
1,230.95 AUD = 795.2 USD
1 AUD = 0.64601 USD
1 USD = 1.54798 AUD
(Last updated: 2022-10-07)
We will also provide two more slash commands:
/xe-help – This will provide instructions for the user on how to enter a conversion.
/xe-list – This will provide a list of all currency codes.
Need help with Google Workspace development?
My team of experts can help you with all of your needs, from custom app development to integrations and security. We have a proven track record of success in helping businesses of all sizes get the most out of Google Workspace.
In this first part of the tutorial series, we need to create two main slash commands /xe and /xe-help. To do this we will update the onMessage() trigger function. Then we will connect the slash commands in the GCP Google Chat API configuration GUI.
We will also update the Google Apps Script Chat App template to return messages more specific to our currency converter.
message=message+" and you said: \""+event.message.text+"\" \n\n"+errorInstructions;
}
return{"text":message};
}
/**
* Responds to a REMOVED_FROM_SPACE event in Google Chat.
*
* @param {Object} event the event object from Google Chat
*/
functiononRemoveFromSpace(event){
console.info("Currency Converter Bot removed from ",
(event.space.name?event.space.name:"this chat"));
}
CurrencyGlobals.gs
CurrencyGlobals.gs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* Error instrucions applied to Errors returned to the user.
*/
consterrorInstructions=`Tomakeaconversion:
1.Type */xe*
2.Select the amount toconvert.
3.The origin currency asa3-letter code.
4.Addacolon:
5.The currency toconvert toasa3letter code.
e.g._/xe1,000.00USD:EUR_
You can always retrieve thishelp at any time by using the */xe-help*slash command.
`
SlashCommands.gs
SlashCommands.gs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Attempts to convert amounts and currency codes that the users submits to
* the chatbot after validating.
* @param {String} text input from user in chat after add the /xe slash command.
* @returns {String} Either currency conversion or Error text.
*/
functionattemptConversion(text){
// NOTE just a placemarker for this stage of the tutorial we will update this soon.
return`xe text="${text}"`
};
/**
* Returns a string containing usage instructions for the currency converter chat app.
* @returns {String} Help title plus error instructions.
*/
functionconversionHelp(){
returnerrorInstructions;
}
appsscript.json
In your appsscript.json file, add the following:
Example chat property inclusion for AppsScript.json
1
2
3
"chat":{
"addToSpaceFallbackMessage":"Chat App now added. Thanks!"
}
For me this would look like this:
appsscript.json
1
2
3
4
5
6
7
8
9
{
"timeZone":"Australia/Sydney",
"dependencies":{},
"exceptionLogging":"STACKDRIVER",
"runtimeVersion":"V8",
"chat":{
"addToSpaceFallbackMessage":"Chat App now added. Thanks!"
}
}
2. Connecting our Google Apps Script to the Exchange Rates Data API
At this stage of the tutorial, we will build our connector to our currency exchange API. We will create a quasi-class (CurrencyAPI()) with a method to get a list of all currencies (.getCurrencyList()) and retrieve a currency conversion (.convertCurrency()).
.getContentText() – The returned text from the fetch. For us, this will be a stringified JSON.
.getResponseCode() – The response code. 200 to indicate a good response and the rest of the codes are errors. You can see the full list of error codes from the API here.
After that, we will need a way to check for any error codes that our fetch request may generate. We will create a private function for this to return either the text if the request is successful or error information.
We will be connecting to the Exchange Rates Data API. The API has a free tier of 250 requests each month. There is no requirement for a credit card or anything.
3. Connecting our Google Apps Script to the Exchange Rates Data API
Before sending our slash command info from our Google Chat App to the API to retrieve the currency conversion, we need to ensure that the user has provided valid input.
Note! Before we dive into our validation, it’s important for me to point out that I am basing my validation rule on the UK and US English separator convention of 1,000,000.00 or 1000000.00. Please modify the rules to meet your own country’s requirements.
What we will allow
It’s okay, particularly when working with text inputs, to be a little flexible in how a user might input their currency conversion.
If you have ever gone on Google search and run a currency conversion, you know that you can make a number of combinations to generate a currency conversion.
While coding out the full extent of Google’s allowable types would be far too complex and perhaps, dare I say, boring, we can provide a little help. Here is what we can do to support user input variation:
Allow for any number before the currency code section. E.g. 1 or 1,110,00 or $2300.00.
Allow for the use of commas or no commas in the amount that users input. E.g. 1,000,000,000.00 or even mistakes 1,1,1,222,1,.00.
Provide some spacing flexibility between:
The amount and the currency code section. E.g. 20 AUD:USD or 20AUD:USD.
The source currency code and the colon ( Up to 3 spaces should be enough). E.g. 20AUD :USD or 20AUD :USD or 20AUD:USD.
The colon and the destination currency code (Again, up to 3 spaces should be adequate). E.g. 20AUD: USD or 20AUD: USD or 20AUD:USD
Permit lowercase currency code or mixed case code. It costs us nothing to convert everything using the toUpperCase() JavaScript method. E.g. 20aud:UsD.
What will generate an error
On the other hand, there are some necessary items for us to send to the API in order for it to respond successfully with currency conversion. This means we should handle:
Missing number. No number no conversion. Error e.g. /xe or /xe AUD:EUR
Multiple decimal places. It is hard for us to guess where the user intended to add their decimal place so we need to return an error here. Error e.g. 2,333.21.24 or E.g. 2..34.561.01.
Ridonculous amount. 🤯 Extreme amounts may be difficult for the API to handle are likely someone is being a little silly. We should respond in kind. Error e.g. 1126545465165198998118991981891.1656116165165156165165161651165
Non-3 letter currency codes. All currency codes are 3 letters in length. Error e.g. 2A:USD or 4AUD:US
Missing source and destination currency code or colon. If we don’t have a source or a destination code we can’t convert anything. Error e.g. 2:EUR or 2AUD or 2AUD:.
Erroneous currency codes. We should check with our stored CurrencyCodes list before we waste valuable requests with the Currency Exchange API. Error e.g. 2XXX:USD or 2AUD:YYY.
Setting up the code
We will create the validateAndRetrieveCurrenciesAndAmount(text) function to handle our validation. This will be called from the attemptConversion() function after it receives the text from the /xe slash command.
Inside our validation function, we will extract our amount and currencies separately. This is because they require us to look at different things to ensure that they are accurate and ready to be sent to the API. This also helps us vary the spacing between the amount and the currency codes should they add a space.
It is much less costly and more efficient for us to run validation Apps Script-side rather than lose a request credit and let the API handle the error.
If we discover an error in the user’s input, we will return a text string to then containing information about the nature of the error. We will also include our instruction information contained in the errorInstructions variable.
If the user successfully enters their currency code, then our validation function will return an object containing the amount as a float, the source currency code and the destination currency code.
conversion = {source, destination, amount}
Regular Expressions
We will be using a variety of regular expression rules to achieve the majority of our validation here.
Because they can be a little tricky we will explain them here in a little more detail:
Extract the amount: /([\d.,]+)/:
[] – Indicates a character class or range to look for.
\d – Search for any digit.
., – Search for any decimal (.) or comma (,)
() – Ensures that all elements are captured in a group where we can apply a quantifier to it like we have with the plus symbol.
+ – matches one or more occurrences of the selected characters.
All periods or decimal symbols:/\./g:
\. – Search for a period.
/g – The global flag matching all occurrences of the selected search.
From and to currency code range: /[A-Za-z]{3}[\s]{0,3}:[\s]{0,3}[A-Za-z]{3}/
[A-Za-z] – Character class searching for any character within the alphabet with either upper or lower case.
{3} – Curly braces indicate a match of a specific number of times. If the braces have one argument it must strictly meet that number of occurrences.
[\s] – Character class search for spaces.
{0,3} – Matching a range of the preceding character or character class between two values.
: – Match a colon.
Get each currency code: /[A-Za-z]{3}/g:
[A-Za-z]{3}– The 3-letter code containing any letter from A to Z in any case.
Please check the */xe-list*tosee what currencies are available\n\n`+errorInstructions;
}
returncurrency;
})();
if(typeof currencies==="string")returncurrencies;
constconversion={...currencies,amount}
returnconversion;
};
4. Connecting /xe slash command to the API and validation
Now we finally get to deploy our /xe slash command and get some results.
First, we need to update the returned item in our attemptConversion() function with the currencyConversion() function (see code below).
The currency conversion function will call the Exchange Rate API via our CurrencyAPI().convertCurrency() method. If successful, it will return the currency based on the inputs we have validated and send it as part of the payload to the API.
We could simply return a value (e.g. xe/ 10AUD:USD = 6.19865 ) but that does not provide a lot of context for our users instead we want to provide something with a bit more valuable that will include:
The returned result: 10 AUD = 6.19865 USD
1 source value = n destination value:1 AUD = 0.619865 USD
1 destination value = n source value:1 USD = 1.613254 AUD
The date the exchange rate was found:(Last updated: 2022-10-16)
We can retrieve all but one bit of these from the object that is returned from our request:
Exchange Rate response object
1
2
3
4
5
{success:true,
query:{from:'AUD',to:'EUR',amount:22.5},
info:{timestamp:1665622924,rate:0.647157},
date:'2022-10-13',
result:14.561033}
The only thing we need to work out is the conversion of 1 destination value base to the source. We can do this by dividing 1 by the exchange rate.
1/result.info.rate
However, there is a spanner in our works…
JavaScript Decimal Rounding Errors
The Problem
Our exchange rate returns a value up to 6 decimal places (e.g. 1.123456). This is more than enough to get a fine-grained indication of the exchange rate. Besides, it would look pretty message with a huge string of trailing decimal digits.
Let’s say we have the number, 5.5555555, and we want to round up from 7 decimal places to 6. Our primary school education taught us that this should be 5.555556. However, using the toFixed() method we get. 5.555555. If we were to increase the number in the seventh decimal position to 6, 7, 8, or 9 all would be right in the world and it will round up as expected.
I found a really good solution shared by George Birbilis in StackOverflow. It does, however, warrant some explanation. Here is my version of the code:
+(Math.round(Number(weirdNum + "e+6")) + "e-6")
The ‘e’ here represents the exponent value. You will often see this when you are logging a huge number in JavaScript. It’s a kind of short-hand version.
For example, 5e6 would be:
= 5 * 10^6 (or to be more granular 5 * 10^+6)
= 5 * 10 * 10 * 10 * 10 * 10
= 5 * 1,000,000
= 5,000,000
So when we convert our weirdNumber variable plus “e+6” with the Number constructor we are moving it left 6 decimal places.
5. A Google Chat App Card for the list of currency codes
There are hundreds of currency codes that the users may wish to draw from and we can’t expect them to memorise them all. The easiest approach we have to support our users here is to provide them with a /xe-list slash command in their Google Chat or Space.
When the user returns the slash command, they will get a stylised card response:
This looks a lot nicer than listing all the currency codes in a message.
This time around instead of returning a text object property we will be returning a card version 2 property.
In our project, we style our header with a title, subtitle and image. Also, note that cards can contain stylable headers as well if you choose to use them.
The section sub-object contains an array of all of the sections that you want to add. Sections provide visual separation in the card and are useful for us to separate our currency codes by letters of the alphabet for ease of reading.
From the widgets list, we used the Decorated Text widget. It has a wide range of uses from button clicks and better styling to adding icons and even switch controls.
We only needed to use the top label property to add our letter and then generate our list of currency codes and their descriptions for that letter using the text property.
Image link
If you want to use the same image in your project you can find it here:
let letter="A";// A is the first letter set to create as a section top label.
let listByLetter="";// e.g. "AFN | Afghan Afghani\nALL: Albanian Lek\n..."
let counter=1;
constsize=Object.keys(CurrencyCodes).length;
// Separate each section by starting letter.
for(varcur inCurrencyCodes){
// THIS IS THE NEW SECTION CONDITION
// If the first letter of the key does not match the current 'letter' create a new section.
// Of if we are the last item in the object. (Will grab "z" and add the section header and add the listByLetter items.)
if(cur[0]!==letter||size===counter){
constwidget={
"decoratedText":{
"topLabel":letter,
"text":listByLetter,
"wrapText":true
}
}
sections.push({"widgets":[widget]})
letter=cur[0];// Set the new letter.
listByLetter="";// Refresh the list by letter.
}
// If there is not change to the letter keep adding to list
listByLetter+=`${cur}|${CurrencyCodes[cur]}\n`
counter++;
};
// Returns the basic outer structure with varialbes to the header and sections
return{
cards_v2:[{
cardId:"currencyList",
card:{
header,
sections
}
}]
};
};
Conclusion
That wraps up our Currency Converter Google Chat App built-in Google Apps Script.
There are a bunch of further directions we could go with the chatbot. We could add an API key input dialogue for each user to add their own API key for the Exchange Rage API.
Alternatively, we could create a customisation dialogue that will allow the user to create a custom display format and input type for their specific region. After all, not all currencies are written the same in different countries.
Another thing we could do is to create a dialogue when users just add /xe instead of appending an amount, source and destination code. Then we could rely on selection boxes for users to choose their currencies, and even add a date.
What else can you think of to improve this project? I would love to hear in the description below.
This was an enormous project to put together taking up several months of preparation, content writing and video creation. I hope you got something out of it.
If you have tried to seamlessly subscribe a user to a Google Calendar as part of an automation workflow in Google Apps Script and discovered that all that happens is that the user gets an automated email request to join, and then it is up to them to accept the calendar invitation to add it to their live calendar list, you’re in the right place.
While providing an invitation gateway makes a lot of sense for Google Workspace consumer(free) accounts where you don’t want strangers to subscribe you to calendars that you don’t want to be a member of, it can be a little frustrating for Google Workspace business and organisations that need users to see a particular calendar.
You’ve probably experienced this, but you can’t always rely on your users to accept these invitations to add a calendar. Then down the track, the user is left scratching their head wondering why they are not getting the calendar events like everyone else.
Google Apps Script – UrlFetchApp, SpreadsheetApp, Ripple API, Time Triggers
I have been very fortunate of late to have the patronage of the Ripple XRP cryptocurrency community via XRP Tip Bot and Coil. This is no small part due to the support of user Recreational Rex from Twitter.
Full disclosure here, I don’t really know all that much about cryptocurrencies. I knew about Bitcoin and Ethereum but really didn’t really invest any time and money into looking at these growing forms of value exchange.
But now I’m a little curious.
I thought it would be fun to see what the value of XRP was against a fairly standard metric like the USD and keep a record of this exchange rate daily over a month or so (Mrs Yagi just read the ‘fun‘ in the last sentence and rolled her eyes).
I also thought it would be pretty cool to see how many exchange providers (Gateways) that conduct USD-XRP exchanges are around and see if there is much difference their exchange rate day-to-day among them.
Fortunately for me, the XRP Ledger provides a freely available open-source ledger that can be accessed via the Ripple Data API. The API can return JSON objects from which we can extract the data we need.
Of course, to record and display the daily exchange-rates I went straight to Google Sheets. I gathered the relevant XPR data using Google Apps Script’s UrlFetchApp Class and pushed it to my Google Sheet with SpreadsheetApp Class.
Here is a live embed of the XRP Google Sheet that is updated via a daily time trigger via Google Apps Script.
Google Apps Script: Time Triggers, ClockTriggerBuilder, ScriptApp
One of the most powerful things about Google Apps Script is the ability to automatically complete tasks with time-driven triggers. You can set up your code to run any one of your functions in your script by the minute, hour, day, week, or month. You can even set it to run based on a specific date.
Have a look at the time-driven trigger options below:
Specific Date and Time: Based on: YYYY-MM-DD HH: MM format
Minute: Every minute or every 5, 10, 15 or 30 minutes.
Hour: Every hour or every 2, 4, 6, 8 or 12 hours.
Day: At a time within an hourly bracket. For example:
Midnight to 1 am,
3 pm to 4 pm
Month: On a specific day of a calendar month at a specific time. For example:
Every 3 day of the month at between 3 am and 4 am.
There are two approaches to setting up these time-based triggers. The first one is by simply using the Trigger creator inside the G Suite Developer Hub. This allows you to select the function that you want to add a trigger to for your project and fill out a simple form to determine when you want your trigger to run.
Alternatively, you can create a time trigger programmatically using the ClockTriggerBuilder class.
In this tutorial, we will build on a previous project we’ve called The Badger, that contains a task check off Google Sheet. If the user does not check off their sheet by the due date, then we can send them an HTML email reminder.
Don’t worry, I will provide the starter code and the Google Sheet for you in a minute. However, if you want to learn how I created the email reminder for The Badger you can follow the tutorial here: