|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# Copyright 2024 Google LLC |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +# |
| 16 | +# To install the latest published package dependency, execute the following: |
| 17 | +# python3 -m pip install google-apps-chat |
| 18 | + |
| 19 | +# [START chat_authentication_utils] |
| 20 | +import json |
| 21 | + |
| 22 | +import google.oauth2.credentials |
| 23 | + |
| 24 | +from google_auth_oauthlib.flow import InstalledAppFlow |
| 25 | +from google.apps import chat_v1 as google_chat |
| 26 | + |
| 27 | +CLIENT_SECRETS_FILE = 'client_secrets.json' |
| 28 | + |
| 29 | +SERVICE_ACCOUNT_FILE = 'service_account.json' |
| 30 | + |
| 31 | +APP_AUTH_OAUTH_SCOPE = ["https://www.googleapis.com/auth/chat.bot"] |
| 32 | + |
| 33 | +def create_client_with_app_credentials(): |
| 34 | + # For more information on app authentication, see |
| 35 | + # https://developers.google.com/workspace/chat/authenticate-authorize-chat-app |
| 36 | + creds = google.oauth2.service_account.Credentials.from_service_account_file( |
| 37 | + SERVICE_ACCOUNT_FILE) |
| 38 | + |
| 39 | + return google_chat.ChatServiceClient( |
| 40 | + credentials = creds, |
| 41 | + client_options={ |
| 42 | + "scopes": APP_AUTH_OAUTH_SCOPE |
| 43 | + }) |
| 44 | + |
| 45 | +def create_client_with_user_credentials(scopes): |
| 46 | + # For more information on user authentication, see |
| 47 | + # https://developers.google.com/workspace/chat/authenticate-authorize-chat-user |
| 48 | + flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, scopes) |
| 49 | + cred = flow.run_local_server() |
| 50 | + installed = json.load(open(CLIENT_SECRETS_FILE))["installed"] |
| 51 | + |
| 52 | + creds = google.oauth2.credentials.Credentials( |
| 53 | + token = cred.token, |
| 54 | + refresh_token = cred.refresh_token, |
| 55 | + token_uri = installed["token_uri"], |
| 56 | + client_id = installed["client_id"], |
| 57 | + client_secret = installed["client_secret"], |
| 58 | + scopes = scopes |
| 59 | + ) |
| 60 | + |
| 61 | + # Create a client |
| 62 | + client = google_chat.ChatServiceClient( |
| 63 | + credentials = creds, |
| 64 | + client_options = { |
| 65 | + "scopes" : scopes |
| 66 | + } |
| 67 | + ) |
| 68 | + |
| 69 | + return client |
| 70 | + |
| 71 | +# [END chat_authentication_utils] |
0 commit comments