Skip to content

Commit

Permalink
feat: Add Google Chat API quickstart (#845)
Browse files Browse the repository at this point in the history
Co-authored-by: pierrick <pierrick@google.com>
  • Loading branch information
PierrickVoulet and pierrick authored Aug 1, 2024
1 parent cb970a4 commit f67ff93
Show file tree
Hide file tree
Showing 4 changed files with 1,211 additions and 0 deletions.
16 changes: 16 additions & 0 deletions chat/quickstart/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Google Chat Node.js Quickstart

Complete the steps described in the [quickstart instructions](
https://developers.google.com/workspace/chat/api/guides/quickstart/nodejs),
and in about five minutes you'll have a simple Node.js command-line
application that makes requests to the Google Chat API.

## Install

`npm install`

## Run

After following the quickstart setup instructions, run the sample:

`node .`
119 changes: 119 additions & 0 deletions chat/quickstart/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/**
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// [START chat_quickstart]

const fs = require('fs').promises;
const path = require('path');
const process = require('process');
const {authenticate} = require('@google-cloud/local-auth');
const {ChatServiceClient} = require('@google-apps/chat');
const {auth} = require('google-auth-library');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/chat.spaces.readonly'];

// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = path.join(process.cwd(), 'token.json');
const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');

/**
* Reads previously authorized credentials from the save file.
*
* @return {Promise<OAuth2Client|null>}
*/
async function loadSavedCredentialsIfExist() {
try {
const content = await fs.readFile(TOKEN_PATH);
const credentials = JSON.parse(content);
return auth.fromJSON(credentials);
} catch (err) {
console.log(err);
return null;
}
}

/**
* Serializes credentials to a file compatible with GoogleAuth.fromJSON.
*
* @param {OAuth2Client} client
* @return {Promise<void>}
*/
async function saveCredentials(client) {
const content = await fs.readFile(CREDENTIALS_PATH);
const keys = JSON.parse(content);
const key = keys.installed || keys.web;
const payload = JSON.stringify({
type: 'authorized_user',
client_id: key.client_id,
client_secret: key.client_secret,
refresh_token: client.credentials.refresh_token,
});
await fs.writeFile(TOKEN_PATH, payload);
}

/**
* Load or request or authorization to call APIs.
*
* @return {Promise<OAuth2Client>}
*/
async function authorize() {
let client = await loadSavedCredentialsIfExist();
if (client) {
return client;
}
client = await authenticate({
scopes: SCOPES,
keyfilePath: CREDENTIALS_PATH,
});
if (client.credentials) {
await saveCredentials(client);
}
return client;
}

/**
* Lists spaces with user credential.
* @param {OAuth2Client} authClient An authorized OAuth2 client.
*/
async function listSpaces(authClient) {
// Create a client
const chatClient = new ChatServiceClient({
authClient: authClient,
scopes: SCOPES,
});

// Initialize request argument(s)
const request = {
// Filter spaces by space type (SPACE or GROUP_CHAT or DIRECT_MESSAGE)
filter: 'space_type = "SPACE"'
};

// Make the request
const pageResult = chatClient.listSpacesAsync(request);

// Handle the response. Iterating over pageResult will yield results and
// resolve additional pages automatically.
for await (const response of pageResult) {
console.log(response);
}
}

authorize().then(listSpaces).catch(console.error);

// [END chat_quickstart]
Loading

0 comments on commit f67ff93

Please sign in to comment.