Python 快速入门

快速入门介绍了如何设置和运行调用 Google Workspace API。

Google Workspace 快速入门使用 API 客户端库来处理一些 身份验证和授权流程的详细信息。我们建议 您需要为自己的应用使用客户端库本快速入门使用 适用于测试的简化身份验证方法 环境对于生产环境,我们建议您了解 身份验证和授权 早于 选择访问凭据 适合您应用的广告格式

创建一个向 Google Chat API 发出请求的 Python 命令行应用。

目标

  • 设置环境。
  • 安装客户端库。
  • 设置示例。
  • 运行该示例。

前提条件

如需运行本快速入门,您需要满足以下前提条件:

设置环境

如需完成本快速入门,请设置您的环境。

启用 API

在使用 Google API 之前,您需要先在 Google Cloud 项目中启用这些 API。 您可以在单个 Google Cloud 项目中启用一个或多个 API。
  • 在 Google Cloud 控制台中,启用 Google Chat API。

    启用 API

如果您使用新的 Google Cloud 项目来完成本快速入门,请配置 OAuth 权限请求页面,并将您自己添加为测试用户。如果您已经 已完成此步骤,请跳到下一部分。

  1. 在 Google Cloud 控制台中,点击“菜单”图标 > API 和服务 > OAuth 同意屏幕

    转到 OAuth 同意屏幕

  2. 对于用户类型,选择内部,然后点击创建
  3. 填写应用注册表单,然后点击保存并继续
  4. 现在,您可以跳过添加范围的步骤,然后点击保存并继续。 以后,如果您要创建一款应用供用户使用 Google Workspace 组织,您必须将用户类型更改为外部,然后执行以下操作: 添加您的应用所需的授权范围。

  5. 查看您的应用注册摘要。如要进行更改,请点击修改。如果应用 点击 Back to Dashboard(返回信息中心)。

为桌面应用授权凭据

如需对最终用户进行身份验证并访问应用中的用户数据,您需要执行以下操作: 创建一个或多个 OAuth 2.0 客户端 ID。客户端 ID 用于标识 连接到 Google OAuth 服务器。如果您的应用在多个平台上运行 您必须为每个平台创建一个单独的客户端 ID。
  1. 在 Google Cloud 控制台中,依次点击“菜单”图标 > API 和服务 > 凭据

    进入“凭据”页面

  2. 依次点击创建凭据 > OAuth 客户端 ID
  3. 依次点击应用类型 > 桌面应用
  4. 名称字段中,输入凭据的名称。此名称仅在 Google Cloud 控制台中显示。
  5. 点击创建。系统会显示“OAuth 客户端创建”屏幕,其中显示了您的新客户端 ID 和客户端密钥。
  6. 点击 OK。新创建的凭据会显示在 OAuth 2.0 客户端 ID 下。
  7. 将下载的 JSON 文件保存为 credentials.json,并将 复制到您的工作目录中。

配置 Google Chat 应用

要调用 Google Chat API,您必须配置 Google Chat 应用。对于任何写入请求,Google Chat 使用 以下信息。

  1. 在 Google Cloud 控制台中,前往 Chat API 配置页面:

    前往“Chat API 配置”页面

  2. Application info(应用信息)下,输入以下信息:

    1. 应用名称字段中,输入 Chat API quickstart app
    2. 头像网址字段中,输入 https://developers.google.com/chat/images/quickstart-app-avatar.png
    3. 说明字段中,输入 Quickstart for calling the Chat API
  3. 互动功能下,点击启用互动功能 切换到关闭位置,以便停用 Chat 应用。

  4. 点击保存

安装 Google 客户端库

  • 安装 Python 版 Google 客户端库:

    pip install --upgrade google-apps-chat google-auth-httplib2 google-auth-oauthlib
    

配置示例

  1. 在您的工作目录中,创建一个名为 quickstart.py 的文件。
  2. quickstart.py 中添加以下代码:

    chat/quickstart/quickstart.py
    from __future__ import print_function
    
    import os.path
    
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from google.apps import chat_v1 as google_chat
    
    
    # If modifying these scopes, delete the file token.json.
    SCOPES = ['https://www.googleapis.com/auth/chat.spaces.readonly']
    
    
    def main():
        """Shows basic usage of the Google Chat API.
        """
        creds = None
        # 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.
        if os.path.exists('token.json'):
            creds = Credentials.from_authorized_user_file('token.json', SCOPES)
        # If there are no (valid) credentials available, let the user log in.
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'credentials.json', SCOPES)
                creds = flow.run_local_server(port=0)
            # Save the credentials for the next run
            with open('token.json', 'w') as token:
                token.write(creds.to_json())
    
        try:
            # Create a client
            client = google_chat.ChatServiceClient(
                credentials = creds,
                client_options = {
                    "scopes" : SCOPES
                }
            )
    
            # Initialize request argument(s)
            request = google_chat.ListSpacesRequest(
                # Filter spaces by space type (SPACE or GROUP_CHAT or DIRECT_MESSAGE)
                filter = 'space_type = "SPACE"'
            )
    
            # Make the request
            page_result = client.list_spaces(request)
    
            # Handle the response. Iterating over page_result will yield results and
            # resolve additional pages automatically.
            for response in page_result:
                print(response)
        except Exception as error:
            # TODO(developer) - Handle errors from Chat API.
            print(f'An error occurred: {error}')
    
    
    if __name__ == '__main__':
        main()

运行示例

  1. 在您的工作目录中,构建并运行该示例:

    python3 quickstart.py
    
  1. 首次运行该示例时,它会提示您授予访问权限: <ph type="x-smartling-placeholder">
      </ph>
    1. 如果您尚未登录 Google 账号,请在系统提示时登录。如果 如果您登录了多个账号,请选择一个用于授权的账号。
    2. 点击接受

    您的 Python 应用运行并调用 Google Chat API。

    授权信息存储在文件系统中,因此下次运行该示例时 则系统不会提示您授权。

后续步骤