Creating Webhooks for Google Chat App with Apps Script

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:

Or it can occur with other third-party services. Imagine that you want to get an update from:

  • Your Stripe or PayPal account whenever a new payment comes in.
  • A course management service like Gumroad.
  • 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.

Captain Webhook of the Pirate Sheet HTTPS Request

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.

In this tutorial, we will cover how to:

Continue reading “Creating Webhooks for Google Chat App with Apps Script”

Develop a Google Chat App Currency Converter with Google Apps Script

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.

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)

Convert a currency inside a Google Chat Space Example

We will also provide two more slash commands:

  1. /xe-help – This will provide instructions for the user on how to enter a conversion.
    Google Chat App Currency Converter xe-help slash command example
  2. /xe-list – This will provide a list of all currency codes.
    Google Chat App Currency Converter xe-list slash command example

Create and Publish a Google Workspace Add-on with Apps Script Course

Need help with Google Workspace development?

Go something to solve bigger than Chat GPT?

I can help you with all of your Google Workspace development needs, from custom app development to integrations and security. I have a proven track record of success in helping businesses of all sizes get the most out of Google Workspace.

Schedule a free consultation today to discuss your needs and get started or learn more about our services here.

1. Create the /xe and /xe-help slash commands

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.

Video 1

If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

The Code

Code.gs

CurrencyGlobals.gs

SlashCommands.gs

appsscript.json

In your appsscript.json file, add the following:

For me this would look like this:

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

Accessing the API is done through the Google Apps Script UrlFetchApp Class with the .fetch() method. This will return two important methods worth noting:

  1. .getContentText() – The returned text from the fetch. For us, this will be a stringified JSON.
  2. .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.

Video 2

Tutorial Links – For part 2

The Code

CurrencyAPI.gs

Create this file to store your Currency API connector.

Test.gs

Create this file to use for testing certain stages of your project.

CurrencyGlobals.gs – Add to. 

Add the currency code to the bottom of this file.

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.

The expected input from the user is as follows:

/xe [amount]source_currrency_code:destination_currency_code

For example,

/xe 115.44AUD:USD

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:

  1. Allow for any number before the currency code section.  E.g. 1 or 1,110,00 or $2300.00.
  2. 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.
  3. Provide some spacing flexibility between:
    1. The amount and the currency code section. E.g. 20     AUD:USD or 20AUD:USD.
    2. The source currency code and the colon ( Up to 3 spaces should be enough). E.g. 20AUD :USD or 20AUD   :USD or 20AUD:USD.
    3. 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
  4. 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:

  1. Missing number. No number no conversion. Error e.g. /xe or /xe AUD:EUR
  2. 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.
  3. 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
  4. Non-3 letter currency codes. All currency codes are 3 letters in length. Error e.g. 2A:USD or 4AUD:US
  5. 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:.
  6. 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.

The Creator Of Regular Expressions
Regular Expressions were invented by Stephen Kleene, a known Priest of  Silencio, who designed the syntax to be rendered instantly forgettable if attempted to be learnt.

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.
    • /g -Any occurrence of the selected search item.

Video 3

The Code – SlashCommands.gs

attemptConversion()

Remove the placemarker: return xe text = "${text}".

Add:

 

validateAndRetrieveCurrenciesAndAmount(text)

Add the following function.

 

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 = destination value: 1 AUD = 0.619865 USD
  • 1 destination value = source value: 1 USD = 1.613254 AUD
  • The date the exchange rate was found: (Last updated: 2022-10-16)

Convert a currency inside a Google Chat Space Example

We can retrieve all but one bit of these from the object that is returned from our request:

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…

spanner in the 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.

A problem arises in Javascript when we try and round up a value using the JavaScript toFixed() method.

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.

The Solution

How do we resolve this?

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.

= Number(weirdNum + “e+6”)
= Number(5.5555555 + “e+6”)
= Number(“5.5555555e+6”)
= 5555555.5

Now we can use the JavaScript Math.round() method to round the last decimal place to the correct value.

= Math.round(5555555.5)

= 5,555,556

Next, we need to convert the number back to the correct decimal value by reversing the exponent value we set:

= +(5,555,556 + “e-6”)

Note the plus symbol at the start of the braces, this is a sneaky way of conversing an exponent number text string to a number.

Video 4

Video released 19 Oct 2022.

The Code

SlashCommands.gs

In the attemptConversion(text) function replace:
return xe text = "${(typeof conversion === "string")? conversion: JSON.stringify(conversion)}"
with
return currencyConversion(conversion);
currencyConversion()

 

If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

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:

Google Chat App Currency Converter xe-list slash command example

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.

Cards version 2 JSON

We will need to create a JSON to send to the Chat API to construct our card.

The card contains a header property and a section 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.

Inside each section, you can add a number of widgets set as an array. There are heaps of widgets to choose from that we noted in our Google Chat App for Developers tutorial.

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:

https://images.unsplash.com/photo-1599930113854-d6d7fd521f10?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=880&q=80

The image is by globe maker, Gaël Gaborel.

Video 5

Video released 22 Oct 2022.

The Code

Code.gs – onMessage()

Add a third switch option for /xe-list

Don’t forget that you will need to go to your GCP console for your project. Select APIs and Services. Then scroll down to find your Chat API.

In the Chat API, select configuration. Scroll down to the Slash commands select and add a new slash command.

The details will be:

  • Name: /xe-list
  • Command ID: 3
  • Description: List of all currency conversion codes.

Select ‘Done’ and then save the configuration.

CurrencyCardList.gs

Create a new file called CurrencyCardList.gs. Here you will add the following function.

createListCardResponse()

 

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 found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

What to take things further? Check out my tutorial on building webhooks for Google Chat:

Creating Webhooks for Google Chat App with Apps Script

~Yagi

Google Chat Apps for Google Apps Script Developers (updated 2023-11-04)

In this article, we will look at Google Chat Apps and go over some of the basics of developing a chat app with Google Apps Script.

Note that Chat Apps are currently only available to Google Workspace paid accounts and not standard ‘@gmail’ consumer accounts.

What are Google Chat Apps?

All about Google Chat Apps YouTube Video
Click to go to the video!

Google Chat is a business-level messaging tool for Google Workspace that allows you to chat one-on-one and in groups called Spaces within your business and even with clients and contractors outside of your domain.

Its integrations with Google Workspace tools like Google sheets, docs and slides right inside chat along with a Google Task tab and a convenient file library tab make it a really handy business tool.

But one thing that is often overlooked is that you can add Chat Apps or Chat Bots to your Google Chat Spaces or DM a chat app directly to accomplish tasks conveniently.

There are hundreds of 3rd party Chat App integrations for you to choose from. Anything from project management to customer support and more.

Google Chat Apps Available

Chat apps can:

Continue reading “Google Chat Apps for Google Apps Script Developers (updated 2023-11-04)”