Skip to content

Commit

Permalink
feat: add Cloud Client library samples for Chat (#851)
Browse files Browse the repository at this point in the history
* feat: add Cloud Client library samples for Chat

* README improvements

* README improvements 2

---------

Co-authored-by: pierrick <pierrick@google.com>
  • Loading branch information
PierrickVoulet and pierrick authored Aug 17, 2024
1 parent f67ff93 commit 765b105
Show file tree
Hide file tree
Showing 44 changed files with 3,017 additions and 0 deletions.
21 changes: 21 additions & 0 deletions chat/client-libraries/cloud/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Google Chat API - Cloud Client library samples

## Set up

1. Add `service_account.json` and/or `client_secrets.json` to the current
folder depending on the credentials used by the samples to run:

1. `service_account.json` for
[app credentials](https://developers.google.com/workspace/chat/authenticate-authorize-chat-app)

1. `client_secrets.json` for
[user credentials](https://developers.google.com/workspace/chat/authenticate-authorize-chat-user)

1. Execute `npm install`

## Run

Execute `npm run replace-with-the-sample-file.js` wih the sample file path of the sample.

For example, to run the sample `create-message-app-cred`, you should run
`npm run create-message-app-cred.js`.
114 changes: 114 additions & 0 deletions chat/client-libraries/cloud/authentication-utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/**
* 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_authentication_utils]

import http from 'http';
import url from 'url';
import open from 'open';
import destroyer from 'server-destroy';
import {readFile} from 'fs/promises';
import {OAuth2Client} from 'google-auth-library';
import {ChatServiceClient} from '@google-apps/chat';

// Application authentication
const SERVICE_ACCOUNT_FILE = './service_account.json';
const APP_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.bot'];

// User authentication
const CLIENT_SECRETS_FILE = './client_secrets.json';
const CLIENT_SECRETS = JSON.parse(await readFile(
new URL(CLIENT_SECRETS_FILE, import.meta.url)
)).web;

/**
* Create a new Chat service client with application credentials.
*
* @returns {ChatServiceClient} The resulting client for the Chat service
*/
export function createClientWithAppCredentials () {
// For more information on app authentication, see
// https://developers.google.com/workspace/chat/authenticate-authorize-chat-app
return new ChatServiceClient({
keyFile: SERVICE_ACCOUNT_FILE,
scopes: APP_AUTH_OAUTH_SCOPES,
});
}

/**
* Create a new Chat service client with user credentials and scopes.
*
* @param {!string[]} scopes Required scopes for the desired API requests
* @returns {Promise<ChatServiceClient>} The resulting client for the Chat service
*/
export async function createClientWithUserCredentials (scopes) {
// For more information on user authentication, see
// https://developers.google.com/workspace/chat/authenticate-authorize-chat-user
return new ChatServiceClient({
authClient: await getAuthenticatedUserOAuth2Client(scopes),
scopes: scopes,
});
}

/**
* Create a new OAuth2 client and go through the OAuth2 flow.
*
* @param {!string[]} scopes Required scopes for the desired API requests
* @returns {Promise<OAuth2Client>} The resulting Google OAuth2 client
*/
function getAuthenticatedUserOAuth2Client(scopes) {
return new Promise((resolve, reject) => {
// Create a client based on client secrets
const oAuth2Client = new OAuth2Client(
CLIENT_SECRETS.client_id,
CLIENT_SECRETS.client_secret,
CLIENT_SECRETS.redirect_uris[0]
);

// Generate the URL to use for consent
const authorizeUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: scopes,
});

// Open an HTTP server to accept the OAuth2 callback
const server = http.createServer(async (request, response) => {
try {
if (request.url.indexOf('/oauth2callback') > -1) {
// Acquire the code and close the server.
const queryString =
new url.URL(request.url, 'http://localhost:3000').searchParams;
const code = queryString.get('code');
response.end('Done!');
server.destroy();
// Acquire the tokens
const r = await oAuth2Client.getToken(code);
// Update credentials of the OAuth2 client.
oAuth2Client.setCredentials(r.tokens);
resolve(oAuth2Client);
}
} catch (e) {
reject(e);
}
}).listen(3000, () => {
// Open default browser and start the flow
open(authorizeUrl, {wait: false}).then(cp => cp.unref());
});
destroyer(server);
});
}

// [END chat_authentication_utils]
52 changes: 52 additions & 0 deletions chat/client-libraries/cloud/create-membership-user-cred-for-app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/**
* 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.
*/
// It may require modifications to work in your environment.

// [START chat_create_membership_user_cred_for_app]

import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.memberships.app'];

// This sample shows how to create membership with app credential for an app
async function main() {
// Create a client
const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

// Initialize request argument(s)
const request = {
// Replace SPACE_NAME here.
parent: 'spaces/SPACE_NAME',
membership: {
member: {
// Member name for app membership, do not change this
name: 'users/app',
// User type for the membership
type: 'BOT'

Check failure on line 38 in chat/client-libraries/cloud/create-membership-user-cred-for-app.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma
}

Check failure on line 39 in chat/client-libraries/cloud/create-membership-user-cred-for-app.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma
}

Check failure on line 40 in chat/client-libraries/cloud/create-membership-user-cred-for-app.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma
};

// Make the request
const response = await chatClient.createMembership(request);

// Handle the response
console.log(response);
}

main().catch(console.error);

// [END chat_create_membership_user_cred_for_app]
52 changes: 52 additions & 0 deletions chat/client-libraries/cloud/create-membership-user-cred.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/**
* 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.
*/
// It may require modifications to work in your environment.

// [START chat_create_membership_user_cred]

import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.memberships'];

// This sample shows how to create membership with user credential for a human user
async function main() {
// Create a client
const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

// Initialize request argument(s)
const request = {
// Replace SPACE_NAME here.
parent: 'spaces/SPACE_NAME',
membership: {
member: {
// Replace USER_NAME here
name: 'users/USER_NAME',
// User type for the membership
type: 'HUMAN'

Check failure on line 38 in chat/client-libraries/cloud/create-membership-user-cred.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma
}

Check failure on line 39 in chat/client-libraries/cloud/create-membership-user-cred.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma
}

Check failure on line 40 in chat/client-libraries/cloud/create-membership-user-cred.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma
};

// Make the request
const response = await chatClient.createMembership(request);

// Handle the response
console.log(response);
}

main().catch(console.error);

// [END chat_create_membership_user_cred]
53 changes: 53 additions & 0 deletions chat/client-libraries/cloud/create-message-app-cred-with-cards.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* 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.
*/
// It may require modifications to work in your environment.

// [START chat_create_message_app_cred_with_cards]

import {createClientWithAppCredentials} from './authentication-utils.js';

// This sample shows how to create message with a card attached with app credential
async function main() {
// Create a client
const chatClient = createClientWithAppCredentials();

// Initialize request argument(s)
const request = {
// Replace SPACE_NAME here.
parent: 'spaces/SPACE_NAME',
message: {
text: 'Hello with app credential!',
cardsV2: [{
cardId: 'card-id',
card: {
header: {
title: 'And with a card!',
}

Check failure on line 38 in chat/client-libraries/cloud/create-message-app-cred-with-cards.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma
}

Check failure on line 39 in chat/client-libraries/cloud/create-message-app-cred-with-cards.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma
}]

Check failure on line 40 in chat/client-libraries/cloud/create-message-app-cred-with-cards.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma
}

Check failure on line 41 in chat/client-libraries/cloud/create-message-app-cred-with-cards.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma
};

// Make the request
const response = await chatClient.createMessage(request);

// Handle the response
console.log(response);
}

main().catch(console.error);

// [END chat_create_message_app_cred_with_cards]
43 changes: 43 additions & 0 deletions chat/client-libraries/cloud/create-message-app-cred.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* 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.
*/
// It may require modifications to work in your environment.

// [START chat_create_message_app_cred]

import {createClientWithAppCredentials} from './authentication-utils.js';

// This sample shows how to create message with app credential
async function main() {
// Create a client
const chatClient = createClientWithAppCredentials();

// Initialize request argument(s)
const request = {
// Replace SPACE_NAME here.
parent: 'spaces/SPACE_NAME',
message: { text: 'Hello with app credential!' }
};

// Make the request
const response = await chatClient.createMessage(request);

// Handle the response
console.log(response);
}

main().catch(console.error);

// [END chat_create_message_app_cred]
49 changes: 49 additions & 0 deletions chat/client-libraries/cloud/create-message-user-cred-at-mention.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* 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.
*/
// It may require modifications to work in your environment.

// [START chat_create_message_user_cred_at_mention]

import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create'];

// This sample shows how to create message with user credential with a user mention
async function main() {
// Create a client
const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

// Initialize request argument(s)
const request = {
// Replace SPACE_NAME here.
parent: 'spaces/SPACE_NAME',
message: {
// The user with USER_NAME will be mentioned if they are in the space
// Replace USER_NAME here
text: 'Hello <users/USER_NAME>!'
}
};

// Make the request
const response = await chatClient.createMessage(request);

// Handle the response
console.log(response);
}

main().catch(console.error);

// [END chat_create_message_user_cred_at_mention]
Loading

0 comments on commit 765b105

Please sign in to comment.