Este guia explica como usar o método patch
no recurso membership
da API Google Chat para alterar atributos de uma assinatura, como alterar um
participante do espaço para administrador ou mudar a função de administrador para participante.
A
Recurso Membership
representa se um usuário humano ou um app do Google Chat foi convidado;
ausente ou faz parte de um espaço.
Pré-requisitos
Python
- Uma empresa Conta do Google Workspace com acesso a Google Chat.
- Configure o ambiente:
- Crie um projeto do Google Cloud.
- Configure a tela de permissão OAuth.
- Ative e configure a API Google Chat com um nome. o ícone e a descrição do app do Chat.
- Instale o Python biblioteca de cliente das APIs do Google.
-
Criar credenciais de ID do cliente OAuth para um aplicativo para computador. Para executar o exemplo
salve as credenciais como um arquivo JSON chamado
client_secrets.json
em seu no diretório local.
- Escolha um escopo de autorização que ofereça suporte à autenticação de usuários.
Node.js
- Uma empresa Conta do Google Workspace com acesso a Google Chat.
- Configure o ambiente:
- Crie um projeto do Google Cloud.
- Configure a tela de permissão OAuth.
- Ative e configure a API Google Chat com um nome. o ícone e a descrição do app do Chat.
- Instale o Node.js biblioteca de cliente das APIs do Google.
-
Criar credenciais de ID do cliente OAuth para um aplicativo para computador. Para executar o exemplo
salve as credenciais como um arquivo JSON chamado
client_secrets.json
em seu no diretório local.
- Escolha um escopo de autorização que ofereça suporte à autenticação de usuários.
Apps Script
- Uma empresa Conta do Google Workspace com acesso a Google Chat.
- Configure o ambiente:
- Crie um projeto do Google Cloud.
- Configure a tela de permissão OAuth.
- Ative e configure a API Google Chat com um nome. o ícone e a descrição do app do Chat.
- Crie um projeto independente do Apps Script, e ative o Serviço avançado de chat.
- Escolha um escopo de autorização que ofereça suporte à autenticação de usuários.
Atualizar uma assinatura
Para atualizar uma participação no espaço, envie o seguinte na sua solicitação:
- Especifique o escopo de autorização
chat.memberships
. - Chame o método
Método
patch
no recursoMembership
, e transmitir oname
da assinatura a ser atualizada, assim como umupdateMask
e umbody
que especifica os atributos de associação atualizados. - O
updateMask
especifica os aspectos da assinatura que serão atualizados. inclui o seguinte:role
: a função do usuário em um espaço do Chat, que determina as permissões ações no espaço. Os valores possíveis são:ROLE_MEMBER
: participante do espaço. O usuário tem permissões básicas, como enviar mensagens para o espaço. Em grupo individual e sem nome todas as pessoas têm essa função.ROLE_MANAGER
: administrador do espaço. O usuário tem todas as permissões básicas, mais permissões administrativas para gerenciar o espaço, como adicionar ou e remover membros. Só pode ser usado em espaços em quespaceType
éSPACE
(espaços nomeados).
Tornar alguém administrador do espaço
O exemplo a seguir faz de um participante normal do espaço um administrador ao especificar
role
como ROLE_MANAGER
no body
que especifica a assinatura atualizada.
atributos:
Python
- No diretório de trabalho, crie um arquivo chamado
chat_membership_update.py
. Inclua o seguinte código em
chat_membership_update.py
:from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build # Define your app's authorization scopes. # When modifying these scopes, delete the file token.json, if it exists. SCOPES = ["https://www.googleapis.com/auth/chat.memberships"] def main(): ''' Authenticates with Chat API via user credentials, then updates a specified space member to change it from a regular member to a space manager. ''' # Authenticate with Google Workspace # and get user authorization. flow = InstalledAppFlow.from_client_secrets_file( 'client_secrets.json', SCOPES) creds = flow.run_local_server() # Build a service endpoint for Chat API. chat = build('chat', 'v1', credentials=creds) # Use the service endpoint to call Chat API. result = chat.spaces().members().patch( # The membership to update, and the updated role. # # Replace SPACE with a space name. # Obtain the space name from the spaces resource of Chat API, # or from a space's URL. # # Replace MEMBERSHIP with a membership name. # Obtain the membership name from the membership of Chat API. name='spaces/SPACE/members/MEMBERSHIP', updateMask='role', body={'role': 'ROLE_MANAGER'} ).execute() # Prints details about the updated membership. print(result) if __name__ == '__main__': main()
No código, substitua o seguinte:
SPACE
: um nome de espaço, que que você pode conseguir na Métodospaces.list
na API Chat ou pelo URL de um espaço.MEMBERSHIP
: um nome de assinatura, que que você pode conseguir na Métodospaces.members.list
na API Chat.
No diretório de trabalho, crie e execute o exemplo:
python3 chat_membership_update.py
Node.js
- No diretório de trabalho, crie um arquivo chamado
chat_membership_update.js
. Inclua o seguinte código em
chat_membership_update.js
:const chat = require('@googleapis/chat'); const {authenticate} = require('@google-cloud/local-auth'); /** * Updates a membership in a Chat space to change it from * a space member to a space manager. * @return {!Promise<!Object>} */ async function updateSpace() { /** * Authenticate with Google Workspace * and get user authorization. */ const scopes = [ 'https://www.googleapis.com/auth/chat.memberships', ]; const authClient = await authenticate({scopes, keyfilePath: 'client_secrets.json'}); /** * Build a service endpoint for Chat API. */ const chatClient = await chat.chat({version: 'v1', auth: authClient}); /** * Use the service endpoint to call Chat API. */ return await chatClient.spaces.patch({ /** * The membership to update, and the updated role. * * Replace SPACE with a space name. * Obtain the space name from the spaces resource of Chat API, * or from a space's URL. * * Replace MEMBERSHIP with a membership name. * Obtain the membership name from the membership of Chat API. */ name: 'spaces/SPACE/members/MEMBERSHIP', updateMask: 'role', requestBody: { role: 'ROLE_MANAGER' } }); } /** * Use the service endpoint to call Chat API. */ updateSpace().then(console.log);
No código, substitua o seguinte:
SPACE
: um nome de espaço, que que você pode conseguir na Métodospaces.list
na API Chat ou pelo URL de um espaço.MEMBERSHIP
: um nome de assinatura, que que você pode conseguir na Métodospaces.members.list
na API Chat.
No diretório de trabalho, crie e execute o exemplo:
python3 chat_membership_update.js
Apps Script
Este exemplo chama a API Chat usando o Serviço avançado do Chat:
Adicione o escopo de autorização
chat.memberships
ao Arquivoappsscript.json
do projeto do Apps Script:"oauthScopes": [ "https://www.googleapis.com/auth/chat.memberships" ]
Adicione uma função como esta ao arquivo código:
/** * Updates a membership from space member to space manager. * @param {string} memberName The resource name of the membership. */ function updateMembershipToSpaceManager(memberName) { try { const body = {'role': 'ROLE_MANAGER'}; Chat.Spaces.Members.patch(memberName, body); } catch (err) { // TODO (developer) - Handle exception console.log('Failed to create message with error %s', err.message); } }
A API Google Chat muda a associação especificada para um administrador do espaço e retorna
uma instância de Membership
com mais detalhes sobre a mudança.
Tornar um administrador do espaço um participante normal
O exemplo a seguir faz de um administrador de espaço um participante normal ao especificar
role
como ROLE_MEMBER
no body
que especifica a assinatura atualizada.
atributos:
Python
- No diretório de trabalho, crie um arquivo chamado
chat_membership_update.py
. Inclua o seguinte código em
chat_membership_update.py
:from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build # Define your app's authorization scopes. # When modifying these scopes, delete the file token.json, if it exists. SCOPES = ["https://www.googleapis.com/auth/chat.memberships"] def main(): ''' Authenticates with Chat API via user credentials, then updates a specified space member to change it from a regular member to a space manager. ''' # Authenticate with Google Workspace # and get user authorization. flow = InstalledAppFlow.from_client_secrets_file( 'client_secrets.json', SCOPES) creds = flow.run_local_server() # Build a service endpoint for Chat API. chat = build('chat', 'v1', credentials=creds) # Use the service endpoint to call Chat API. result = chat.spaces().members().patch( # The membership to update, and the updated role. # # Replace SPACE with a space name. # Obtain the space name from the spaces resource of Chat API, # or from a space's URL. # # Replace MEMBERSHIP with a membership name. # Obtain the membership name from the membership of Chat API. name='spaces/SPACE/members/MEMBERSHIP', updateMask='role', body={'role': 'ROLE_MEMBER'} ).execute() # Prints details about the updated membership. print(result) if __name__ == '__main__': main()
No código, substitua o seguinte:
SPACE
: um nome de espaço, que que você pode conseguir na Métodospaces.list
na API Chat ou pelo URL de um espaço.MEMBERSHIP
: um nome de assinatura, que que você pode conseguir na Métodospaces.members.list
na API Chat.
No diretório de trabalho, crie e execute o exemplo:
python3 chat_membership_update.py
Node.js
- No diretório de trabalho, crie um arquivo chamado
chat_membership_update.js
. Inclua o seguinte código em
chat_membership_update.js
:const chat = require('@googleapis/chat'); const {authenticate} = require('@google-cloud/local-auth'); /** * Updates a membership in a Chat space to change it from * a space manager to a space member. * @return {!Promise<!Object>} */ async function updateSpace() { /** * Authenticate with Google Workspace * and get user authorization. */ const scopes = [ 'https://www.googleapis.com/auth/chat.memberships', ]; const authClient = await authenticate({scopes, keyfilePath: 'client_secrets.json'}); /** * Build a service endpoint for Chat API. */ const chatClient = await chat.chat({version: 'v1', auth: authClient}); /** * Use the service endpoint to call Chat API. */ return await chatClient.spaces.patch({ /** * The membership to update, and the updated role. * * Replace SPACE with a space name. * Obtain the space name from the spaces resource of Chat API, * or from a space's URL. * * Replace MEMBERSHIP with a membership name. * Obtain the membership name from the membership of Chat API. */ name: 'spaces/SPACE/members/MEMBERSHIP', updateMask: 'role', requestBody: { role: 'ROLE_MEMBER' } }); } /** * Use the service endpoint to call Chat API. */ updateSpace().then(console.log);
No código, substitua o seguinte:
SPACE
: um nome de espaço, que que você pode conseguir na Métodospaces.list
na API Chat ou pelo URL de um espaço.MEMBERSHIP
: um nome de assinatura, que que você pode conseguir na Métodospaces.members.list
na API Chat.
No diretório de trabalho, crie e execute o exemplo:
python3 chat_membership_update.js
Apps Script
Este exemplo chama a API Chat usando o Serviço avançado do Chat:
Adicione o escopo de autorização
chat.memberships
ao Arquivoappsscript.json
do projeto do Apps Script:"oauthScopes": [ "https://www.googleapis.com/auth/chat.memberships" ]
Adicione uma função como esta ao arquivo código:
/** * Updates a membership from space manager to space member. * @param {string} memberName The resource name of the membership. */ function updateMembershipToSpaceMember(memberName) { try { const body = {'role': 'ROLE_MEMBER'}; Chat.Spaces.Members.patch(memberName, body); } catch (err) { // TODO (developer) - Handle exception console.log('Failed to create message with error %s', err.message); } }
A API Google Chat muda a associação especificada para um administrador do espaço e retorna
uma instância de Membership
com mais detalhes sobre a mudança.
Temas relacionados
- Convidar ou adicionar um usuário ou um app do Google Chat a um espaço
- Veja detalhes sobre a assinatura de um usuário ou de um app do Chat.
- Listar os participantes de um espaço
- Remover um usuário ou app do Chat de um espaço.