# GoogleApp

Use this lib to connect BJS with [Google App Script](https://developers.google.com/apps-script)

![](https://3310729168-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVh0yg9olT-QWqi3AYt%2F-MG806E9llpnWD-Ax0fX%2F-MG811nMSXwLiCzb5OKb%2Fimage.png?alt=media\&token=75bd0e84-88b0-447c-9941-76bc2f34c808)

## Getting started

### **Easy setup**

1. Copy this [table](https://docs.google.com/spreadsheets/d/1aOIYlwRqiCFWxeTTkhE31pBFTOeByrl3FRusGc1pZZ0/edit#gid=0) to your Google account
2. [Deploy](#3.-deploy-as-web-app) as web app
3. Try to open web app via app [Public App url](#4.-public-app-url)
4. Install *GoogleAppLib* and *WebhooksLib* to your bot
5. Create [setup](#7.-create-setup-command) command

After this step you can [use](#using) this Lib and [debug](#debugging).

###

### **Detail setup**

{% hint style="info" %}
This is detail setup description. Please try to use [easy setup](#easy-setup) before it.
{% endhint %}

#### **1. Create new App Script project**

Go to <https://script.google.com> and create new project by button:

![](https://3310729168-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVh0yg9olT-QWqi3AYt%2F-MG806E9llpnWD-Ax0fX%2F-MG81efFz8LK3N3yndQs%2Fimage.png?alt=media\&token=561b4af6-09dc-44a9-a76d-ceb4c0652459)

#### 2. Add Code.gs

Paste the script from [above](https://github.com/bots-business/store-libs/blob/master/GoogleAppSync.gs) into the script code editor and hit *Save.*

![](https://3310729168-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVh0yg9olT-QWqi3AYt%2Fuploads%2FKEwOv2Sp79kmBT2FYhWl%2Fimage.png?alt=media\&token=0cf57262-ac6d-4411-abac-7b6ab731f765)

You will need to contact your Google Apps administrator, or else use a Gmail account.)

#### **3. Deploy as web app**

Now click *Deploy*. You may be asked to review permissions now. **Project version** - always "New".

![](https://3310729168-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVh0yg9olT-QWqi3AYt%2Fuploads%2FPbozXJYWnN4qOfwSFwTW%2F%D0%A1%D0%BD%D0%B8%D0%BC%D0%BE%D0%BA%20%D1%8D%D0%BA%D1%80%D0%B0%D0%BD%D0%B0%20%D0%BE%D1%82%202022-06-14%2014-11-17.png?alt=media\&token=ce9e77d0-4d57-4e74-bede-8a43b68f2831)

Cloick in Deploy button. You will have Public App url.

#### 4. Public App URL

The URL that you get will be the webhook that you need use in this Lib. You can test this webhook in your browser first by pasting it. Note that depending on your Google Apps instance, you may need to adjust the URL to make it work.&#x20;

#### 5. Add permissions

You need to add [permissions](#permissions)

#### 6. Install *GoogleAppLib* and *WebhooksLib* to bot

Go to App > Libs and install *GoogleAppLib* and *WebhooksLib*&#x20;

#### 7. Create setup command:

**`/setup`**

```javascript
// replace with your URL, obtained in step 4
Libs.GoogleApp.setUrl("https://script.google.com/macros/*******");
```

## Using

Use any Google App script in BJS now

```javascript
function GACode(){
   // Google App Script code here
   // Please note: this function is runs on GA not BB
   // ...
}

// BJS
Libs.GoogleApp.run({
  code: GACode, // Function with Google App code
  onRun: "onRun", // Optional. This command will be executed after run
  email: "my@email.com" // Optional. Email for errors,
  // debug: true // For debug. Default is false
});
```

Example for command `/task`

```javascript
function GACode(){
  // translation from English to France
  var trans = LanguageApp.translate(params, 'en', 'fr');

  // make Google Calendar event
  var event = CalendarApp.getDefaultCalendar()
    .createEventFromDescription('Lunch with ' + user.first_name + ', Friday at 1PM');
  
  // send Email
  MailApp.sendEmail({
    to: "help@example.com",
    subject: "hello from bot " + bot.name,
    htmlBody: "<h1>Hello!</h1>How are you?<br>" +
        "We have message to bot: " + message
  });

  // ...
  // Use all power of Google App Script!
  
  // return result as JSON
  return { event: event, trans: trans }
}

Libs.GoogleApp.run({
  code: GACode,
  onRun: "onRun",
  // email: "test@example.com" // email for errors
  // debug: true // default false
});
```

{% hint style="warning" %}
You can turn on debug flag with true

Then you can [debug](#debugging) code
{% endhint %}

command `onRun`

```javascript
Bot.sendMessage(inspect(options))
```

{% hint style="warning" %}
**GACode** - it is isolated function with Google App code. It can not have BJS code like `Bot.sendMessage` and etc. Only GA code!

**But you can** use [variables](https://help.bots.business/bjs/variables) and pass data with [options](https://help.bots.business/bjs/bot-functions#bot-run-options) for Bot.run method.

```javascript
let myVar = "will not works";

options.myVar = "will be works";

function GACode(){
   // Google App Script code here
   // Please note: this function is runs on GA not BB
   // ...
   
   myVar = 5; // Error! myVar is not defined in GA only in BB side
   
   // this will be works:
   let myVar;
   myVar = 5;
   
   Bot.sendMessage("ok")  // Error! It is BJS not GA code!
   
   let botName = bot.name; // Will be worked
   let myVar = options.myVar; // Will be worked
}
```

{% endhint %}

## Permissions

{% hint style="warning" %}
You need set permissions for Google App Script
{% endhint %}

Run `Libs.GoogleApp.run()`in first time. You can have like such error:

> Error on Google App script: "Exception"
>
> "The script does not have permission to perform that action. Required permissions: (<https://www.googleapis.com/auth/calendar> || <https://www.googleapis.com/auth/calendar.readonly> || <https://www.google.com/calendar/feeds>)"

If you have such error you need set access rights.

### Granting access rights via manifest file

Full help available [here](https://developers.google.com/apps-script/concepts/scopes#setting_explicit_scopes). From that help:

1. Open the script project.
2. At the left, click **Project Settings** settings.
3. Select the **Show "appsscript.json" manifest file in editor** checkbox:

![](https://3310729168-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVh0yg9olT-QWqi3AYt%2Fuploads%2FgSTIJtspj7PVVlo3lxbA%2Fimage.png?alt=media\&token=f21c85c6-dce4-450b-b2ed-4e1e4ef0d2da)

At the left, click **Editor** code.

At the left, click the `appsscript.json` file.

Locate the top-level field labeled `oauthScopes`. If it's not present, you can add it.

The `oauthScopes` field specifies an array of strings. To set the scopes your project uses, replace the contents of this array with the scopes you want it to use. For example:

```
{
  "timeZone": "Asia/Tokyo",
  "dependencies": {
  },
  "webapp": {
    "access": "ANYONE_ANONYMOUS",
    "executeAs": "USER_DEPLOYING"
  },
  "exceptionLogging": "STACKDRIVER",
  "oauthScopes": ["https://www.googleapis.com/auth/script.send_mail",
                  "https://www.googleapis.com/auth/script.external_request",
                  "https://www.googleapis.com/auth/spreadsheets"],
  "runtimeVersion": "V8"
}
```

1. <https://www.googleapis.com/auth/script.send_mail>", "<https://www.googleapis.com/auth/script.external_request> - is mandatory scope
2. Save the manifest file using **Ctrl+S** or the Save file icon in the menu bar.
3. Publish your app again (see [step 3](#getting-started))

![](https://3310729168-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVh0yg9olT-QWqi3AYt%2F-MGq7uzKdeK0-3ddk1VR%2F-MH-AT1ETFDtLKZ3WWX8%2Fimage.png?alt=media\&token=ce29c17d-1037-41bd-af6d-ab36f0339e95)

## Debugging

Run `Libs.GoogleAppLib.run`in first time. Then:

* go to Google App Script Editor (See [step 2](#getting-started))
* select "debug" function on Tab
* press "Debug" button:

![](https://3310729168-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVh0yg9olT-QWqi3AYt%2Fuploads%2FqI586EC66C2GzSa7lmzY%2Fimage.png?alt=media\&token=5a4fd15f-a806-4771-9fde-2756c5a77c85)

Google app is runs. Bot will sent execution result to you. Also you can receive email with error description.

{% hint style="success" %}
You can use "debug" function anytime for debugging
{% endhint %}

Also you can open web app by url (see [step 5](#getting-started)) in incognito mode. And look for any errors. For example we have permission error here:

![](https://3310729168-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVh0yg9olT-QWqi3AYt%2Fuploads%2FtQ8Nh7YOlPlFO6x5ixJS%2Fimage.png?alt=media\&token=30ff6714-a725-4b84-ac4c-54ced104fbb4)

## Links

[Google App script](https://developers.google.com/apps-script) home page

Google App Script [examples](https://github.com/gsuitedevs/apps-script-samples) - good examples for inspiration

Stack Overflow [answers](http://stackoverflow.com/questions/tagged/google-apps-script) - ask your questions on SO

[Videos](https://developers.google.com/apps-script/guides/videos) -  Check out the Apps Script videos on YouTube

[Reference](https://developers.google.com/apps-script/reference) - The reference documentation provided in this section describes the various Apps Script services and the Apps Script manifest file structure.
