Google Chat API를 사용하면 관련 메서드를 호출하여 Google Chat에서 메시지를 비동기식으로 생성, 읽기, 업데이트, 삭제할 수 있습니다. 이 가이드에서는 다음 메서드를 호출하는 방법을 설명합니다.
spaces.messages.create
로 메시지를 만듭니다.spaces.messages.get
로 메시지를 읽습니다.spaces.messages.update
로 메시지를 업데이트합니다.spaces.messages.delete
로 메시지를 삭제합니다.
Chat 앱은 Chat API를 비동기식으로 호출하지 않고도 메시지 및 스페이스에 추가되는 등의 Chat 이벤트에 응답할 수 있습니다. Chat 이벤트에 동기식으로 응답하는 Chat 앱을 빌드하려면 Chat 앱 빌드하기를 참고하세요. Chat 앱은 동기식으로 비동기식으로 Chat API와 함께 사용할 수 있습니다.
Chat 앱 없이 Chat 스페이스에서 메시지를 비동기식으로 만들려면 웹훅을 설정합니다.
기본 요건
이 가이드의 예를 실행하려면 다음 기본 요건이 필요합니다.
Python
- Python 3.6 이상
- pip 패키지 관리 도구
Python용 Google 클라이언트 라이브러리입니다. 설치하려면 명령줄 인터페이스에서 다음 명령어를 실행합니다.
pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib oauth2client
Chat 스페이스의 멤버십이 포함된 게시된 Chat 앱:
- Chat 앱을 만들고 게시하려면 Cloud Functions로 Google Chat 앱 빌드하기를 참고하세요.
- Chat 스페이스에 Chat 앱을 추가하려면 Google Chat의 스페이스 또는 대화에 앱 추가하기를 참고하세요.
Chat 앱에 대한 승인 구성:
- 서비스 계정 인증이 완전히 지원됩니다. 서비스 계정을 설정하려면 서비스 계정으로 인증 및 승인을 참조하세요.
- Google Workspace 개발자 프리뷰 프로그램의 일환으로 지원됩니다. 사용자 인증을 설정하려면 사용자 인증 및 승인 (개발자 프리뷰)을 참고하세요.
spaces.messages.update
메서드는 아직 사용자 인증을 지원하지 않습니다.
개발자 프리뷰: 사용자 인증은 특정 기능에 사전 체험판을 제공하는
메시지 만들기
Google Chat에서 메시지를 비동기식으로 만들려면 Message
리소스에서 create
메서드를 호출합니다. 텍스트 또는 카드 메시지를 만들 수 있습니다. 대화목록을 시작하거나 스레드에 답장하려면 threadKey
또는 thread.name
를 지정합니다.
작성한 메시지의 name
를 기록해 두었다가 나중에 읽거나 업데이트하거나 삭제해야 할 때 참조할 수 있습니다. 또는 메시지 이름 지정을 고려해 보세요.
문자 메시지 만들기
문자 메시지를 만드는 방법은 다음과 같습니다.
Python
- 작업 디렉터리에서 이름이
chat_create_text_message.py
인 파일을 만듭니다. chat_create_text_message.py
에 다음 코드를 포함합니다.from httplib2 import Http from oauth2client.service_account import ServiceAccountCredentials from apiclient.discovery import build # Specify required scopes. SCOPES = ['https://www.googleapis.com/auth/chat.bot'] # Specify service account details. CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name( 'service_account.json', SCOPES) # Build the URI and authenticate with the service account. chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http())) # Create a Chat message. result = chat.spaces().messages().create( # The space to create the message in. # # Replace SPACE with a space name. # Obtain the space name from the spaces resource of Chat API, # or from a space's URL. parent='spaces/SPACE', # The message to create. body={'text': 'Hello, world!'} ).execute() print(result)
코드에서
SPACE
를 Chat API의spaces.list()
메서드나 스페이스의 URL에서 가져올 수 있는 스페이스 이름으로 바꿉니다.작업 디렉터리에서 샘플을 빌드하고 실행합니다.
python3 chat_create_text_message.py
카드 메시지 만들기
카드 메시지를 만드는 방법은 다음과 같습니다.

Python
- 작업 디렉터리에서 이름이
chat_create_card_message.py
인 파일을 만듭니다. chat_create_card_message.py
에 다음 코드를 포함합니다.from httplib2 import Http from oauth2client.service_account import ServiceAccountCredentials from apiclient.discovery import build # Specify required scopes. SCOPES = ['https://www.googleapis.com/auth/chat.bot'] # Specify service account details. CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name( 'service_account.json', SCOPES) # Build the URI and authenticate with the service account. chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http())) # Create a Chat message. result = chat.spaces().messages().create( # The space to create the message in. # # Replace SPACE with a space name. # Obtain the space name from the spaces resource of Chat API, # or from a space's URL. parent='spaces/SPACE', # The message to create. body= { 'cardsV2': [{ 'cardId': 'createCardMessage', 'card': { 'header': { 'title': 'A Card Message!', 'subtitle': 'Created with Chat REST API', 'imageUrl': 'https://developers.google.com/chat/images/chat-product-icon.png', 'imageType': 'CIRCLE' }, 'sections': [ { 'widgets': [ { 'buttonList': { 'buttons': [ { 'text': 'Read the docs!', 'onClick': { 'openLink': { 'url': 'https://developers.google.com/chat' } } } ] } } ] } ] } }] } ).execute() print(result)
코드에서
SPACE
를 Chat API의spaces.list()
메서드나 스페이스의 URL에서 가져올 수 있는 스페이스 이름으로 바꿉니다.작업 디렉터리에서 샘플을 빌드하고 실행합니다.
python3 chat_create_card_message.py
메시지 대화목록 시작 또는 답장하기
메시지 대화목록을 시작하려면 메시지를 만들고 thread.name
를 비워 둡니다. 그러면 Google Chat에서 대화목록을 만들 때 메시지를 채웁니다. 원하는 경우 스레드 이름을 맞춤설정하려면 스레드 이름으로 thread.threadKey
를 지정합니다.
메시지 대화목록에 답장하려면 thread.threadKey
또는 thread.name
를 대화목록 이름으로 지정합니다. thread.threadKey
또는 thread.name
가 같은 후속 메시지는 답장과 동일한 대화목록에 게시됩니다.
각 thread.threadKey
는 Chat 앱 또는 Chat 앱을 설정하는 웹훅에 고유합니다. 서로 다른 두 앱 또는 웹훅에서 동일한 thread.threadKey
를 설정하면 메시지가 스레드되지 않습니다. 대신 두 개의 다른 스레드가 시작됩니다. 두 개의 다른 앱 또는 웹훅이 대신 thread.name
를 지정하여 동일한 스레드에 응답을 게시할 수 있습니다.
다음은 thread.threadKey
'nameOfThread'로 스레드를 시작하거나 답장하는 방법입니다.
Python
- 작업 디렉터리에서 이름이
chat_create_message_thread.py
인 파일을 만듭니다. chat_create_message_thread.py
에 다음 코드를 포함합니다.from httplib2 import Http from oauth2client.service_account import ServiceAccountCredentials from apiclient.discovery import build # Specify required scopes. SCOPES = ['https://www.googleapis.com/auth/chat.bot'] # Specify service account details. CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name( 'service_account.json', SCOPES) # Build the URI and authenticate with the service account. chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http())) # Create a Chat message. result = chat.spaces().messages().create( # The space to create the message in. # # REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD replies to an existing thread # if one exists, otherwise it starts a new one. # # Replace SPACE with a space name. # Obtain the space name from the spaces resource of Chat API, # or from a space's URL. parent='spaces/SPACE', # Whether to start a thread or reply to an existing one. # # Required when threading is enabled in a space unless starting a # thread. Ignored in other space types. Threading is enabled when # space.spaceThreadingState is THREADED_MESSAGES. messageReplyOption='REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD', # The message body. body={ # The message to create. 'text': 'Start or reply to another message in a thread!', # The thread to start or reply to. 'thread': { 'threadKey': 'nameOfThread' } } ).execute() print(result)
코드에서
SPACE
를 Chat API의spaces.list()
메서드나 스페이스의 URL에서 가져올 수 있는 스페이스 이름으로 바꿉니다.작업 디렉터리에서 샘플을 빌드하고 실행합니다.
python3 chat_create_message_thread.py
메시지 작성 및 이름 지정
생성된 메시지의 후속 작업을 용이하게 하려면 맞춤 name
를 할당합니다. 맞춤 이름을 할당하면 채팅 앱에서 메시지를 만들 때 반환된 응답 본문의 name
메시지를 저장하지 않고 신속하게 메시지를 회수할 수 있습니다.
맞춤 이름을 할당하면 채팅 앱에서 메시지를 만들 때 반환된 응답 본문의 name
메시지를 저장하지 않고도 메시지를 회수할 수 있습니다.
맞춤 이름을 할당해도 생성된 name
필드(메시지의 리소스 이름)가 대체되지 않습니다. 대신 맞춤 이름을 clientAssignedMessageId
필드로 설정하며, 이 필드는 나중에 업데이트 또는 메시지 삭제와 같은 작업을 처리하는 동안 참조할 수 있습니다.
메시지를 만들 때 사용된 맞춤 이름을 지정하면 오류가 반환되지만 update
및 delete
와 같은 다른 메서드는 예상대로 작동합니다.
맞춤 이름 요구사항:
client-
로 시작합니다. 예를 들어client-custom-name
는 유효한 맞춤 이름이지만custom-name
은 아닙니다.- 소문자, 숫자, 하이픈만 포함할 수 있습니다.
- 길이는 63자(영문 기준) 이하여야 합니다.
메시지를 만들고 이름을 지정하는 방법은 다음과 같습니다.
Python
- 작업 디렉터리에서 이름이
chat_create_named_message.py
인 파일을 만듭니다. chat_create_named_message.py
에 다음 코드를 포함합니다.from httplib2 import Http from oauth2client.service_account import ServiceAccountCredentials from apiclient.discovery import build # Specify required scopes. SCOPES = ['https://www.googleapis.com/auth/chat.bot'] # Specify service account details. CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name( 'service_account.json', SCOPES) # Build the URI and authenticate with the service account. chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http())) # Create a Chat message with a custom name. result = chat.spaces().messages().create( # The space to create the message in. # # Replace SPACE with a space name. # Obtain the space name from the spaces resource of Chat API, # or from a space's URL. parent='spaces/SPACE', # Custom name for the message used to facilitate later operations. messageId='client-custom-name', # The message to create. body={'text': 'Hello, world!'} ).execute() print(result)
코드에서
SPACE
를 Chat API의spaces.list()
메서드나 스페이스의 URL에서 가져올 수 있는 스페이스 이름으로 바꿉니다.작업 디렉터리에서 샘플을 빌드하고 실행합니다.
python3 chat_create_named_message.py
메시지를 읽음
Google Chat에서 메시지를 비동기식으로 읽으려면 Message
리소스에서 get
메서드를 호출하고 읽을 메시지의 name
를 전달합니다.
메시지를 읽는 방법은 다음과 같습니다.
Python
- 작업 디렉터리에서 이름이
chat_read_message.py
인 파일을 만듭니다. chat_read_message.py
에 다음 코드를 포함합니다.from httplib2 import Http from oauth2client.service_account import ServiceAccountCredentials from apiclient.discovery import build # Specify required scopes. SCOPES = ['https://www.googleapis.com/auth/chat.bot'] # Specify service account details. CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name( 'service_account.json', SCOPES) # Build the URI and authenticate with the service account. chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http())) # Get a Chat message. result = chat.spaces().messages().get( # The message to read. # # Replace SPACE with a space name. # Obtain the space name from the spaces resource of Chat API, # or from a space's URL. # # Replace MESSAGE with a message name. # Obtain the message name from the response body returned # after creating a message asynchronously with Chat REST API. name='spaces/SPACE/messages/MESSAGE' ).execute() # Print Chat API's response in your command line interface. print(result)
코드에서
SPACE
를 Chat API의spaces.list()
메서드나 스페이스의 URL에서 가져올 수 있는 스페이스 이름으로 바꿉니다.코드에서
MESSAGE
를 메시지 이름으로 바꿉니다. 이 이름은 Chat API를 사용하여 메시지를 비동기식으로 만든 후 반환된 응답 본문에서 얻거나 생성 시 메시지에 할당된 맞춤 이름으로 바꿉니다.작업 디렉터리에서 샘플을 빌드하고 실행합니다.
python3 chat_read_message.py
메시지 업데이트
Google Chat의 기존 메시지를 비동기식으로 업데이트하려면 Message
리소스에서 update
메서드를 호출하고 업데이트할 메시지의 name
뿐만 아니라 업데이트된 메시지를 지정하는 updateMask
와 body
도 전달합니다.
문자 메시지 업데이트 또는 카드 메시지 앞에 문자 메시지 추가
문자 메시지를 업데이트하려면 다음을 전달합니다.
- 업데이트할 메시지의
name
입니다. updateMask='text'
- 업데이트된 메시지를 지정하는
body
입니다.
업데이트된 메시지가 카드 메시지인 경우 문자 메시지가 카드 메시지 앞에 추가됩니다 (계속 표시됨).
문자 메시지를 SMS로 업데이트하거나 카드 메시지 앞에 문자 메시지를 추가하는 방법은 다음과 같습니다.
Python
- 작업 디렉터리에서 이름이
chat_update_text_message.py
인 파일을 만듭니다. chat_update_text_message.py
에 다음 코드를 포함합니다.from httplib2 import Http from oauth2client.service_account import ServiceAccountCredentials from apiclient.discovery import build # Specify required scopes. SCOPES = ['https://www.googleapis.com/auth/chat.bot'] # Specify service account details. CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name( 'service_account.json', SCOPES) # Build the URI and authenticate with the service account. chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http())) # Update a Chat message. result = chat.spaces().messages().update( # The message to update, and the updated message. # # Replace SPACE with a space name. # Obtain the space name from the spaces resource of Chat API, # or from a space's URL. # # Replace MESSAGE with a message name. # Obtain the message name from the response body returned # after creating a message asynchronously with Chat REST API. name='spaces/SPACE/messages/MESSAGE', updateMask='text', body={'text': 'Updated message!'} ).execute() # Print Chat API's response in your command line interface. print(result)
코드에서
SPACE
를 Chat API의spaces.list()
메서드나 스페이스의 URL에서 가져올 수 있는 스페이스 이름으로 바꿉니다.코드에서
MESSAGE
를 메시지 이름으로 바꿉니다. 이 이름은 Chat API를 사용하여 메시지를 비동기식으로 만든 후 반환된 응답 본문에서 얻거나 생성 시 메시지에 할당된 맞춤 이름으로 바꿉니다.작업 디렉터리에서 샘플을 빌드하고 실행합니다.
python3 chat_update_text_message.py
카드 메시지 업데이트 또는 카드 메시지에 카드 메시지 추가
card 메시지를 업데이트하려면 다음을 전달합니다.
- 업데이트할 메시지의
name
updateMask='cardsV2'
- 업데이트된 메시지를 지정하는
body
입니다.
업데이트된 메시지가 문자 메시지인 경우 카드가 문자 메시지에 추가됩니다 (계속 표시됨). 업데이트된 메시지 자체가 카드인 경우 표시된 카드가 업데이트됩니다.
메시지를 카드 메시지로 업데이트하는 방법은 다음과 같습니다.
Python
- 작업 디렉터리에서 이름이
chat_update_card_message.py
인 파일을 만듭니다. chat_update_card_message.py
에 다음 코드를 포함합니다.from httplib2 import Http from oauth2client.service_account import ServiceAccountCredentials from apiclient.discovery import build # Specify required scopes. SCOPES = ['https://www.googleapis.com/auth/chat.bot'] # Specify service account details. CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name( 'service_account.json', SCOPES) # Build the URI and authenticate with the service account. chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http())) # Update a Chat message. result = chat.spaces().messages().update( # The message to update, and the updated message. # # Replace SPACE with a space name. # Obtain the space name from the spaces resource of Chat API, # or from a space's URL. # # Replace MESSAGE with a message name. # Obtain the message name from the response body returned # after creating a message asynchronously with Chat REST API. name='spaces/SPACE/messages/MESSAGE', updateMask='cardsV2', body= { 'cardsV2': [{ 'cardId': 'updateCardMessage', 'card': { 'header': { 'title': 'An Updated Card Message!', 'subtitle': 'Updated with Chat REST API', 'imageUrl': 'https://developers.google.com/chat/images/chat-product-icon.png', 'imageType': 'CIRCLE' }, 'sections': [ { 'widgets': [ { 'buttonList': { 'buttons': [ { 'text': 'Read the docs!', 'onClick': { 'openLink': { 'url': 'https://developers.google.com/chat' } } } ] } } ] } ] } }] } ).execute() # Print Chat API's response in your command line interface. print(result)
코드에서
SPACE
를 Chat API의spaces.list()
메서드나 스페이스의 URL에서 가져올 수 있는 스페이스 이름으로 바꿉니다.코드에서
MESSAGE
를 메시지 이름으로 바꿉니다. 이 이름은 Chat API를 사용하여 메시지를 비동기식으로 만든 후 반환된 응답 본문에서 얻거나 생성 시 메시지에 할당된 맞춤 이름으로 바꿉니다.작업 디렉터리에서 샘플을 빌드하고 실행합니다.
python3 chat_update_card_message.py
메시지 삭제
Google Chat에서 기존 메시지를 비동기식으로 삭제하려면 Message
리소스에서 delete
메서드를 호출하고 삭제할 메시지의 name
를 전달합니다.
메시지를 삭제하는 방법은 다음과 같습니다.
Python
- 작업 디렉터리에서 이름이
chat_delete_message.py
인 파일을 만듭니다. chat_delete_message.py
에 다음 코드를 포함합니다.from httplib2 import Http from oauth2client.service_account import ServiceAccountCredentials from apiclient.discovery import build # Specify required scopes. SCOPES = ['https://www.googleapis.com/auth/chat.bot'] # Specify service account details. CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name( 'service_account.json', SCOPES) # Build the URI and authenticate with the service account. chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http())) # Delete a Chat message. result = chat.spaces().messages().delete( # The message to delete. # # Replace SPACE with a space name. # Obtain the space name from the spaces resource of Chat API, # or from a space's URL. # # Replace MESSAGE with a message name. # Obtain the message name from the response body returned # after creating a message asynchronously with Chat REST API. name='spaces/SPACE/messages/MESSAGE' ).execute() # Print Chat API's response in your command line interface. # When deleting a message, the response body is empty. print(result)
코드에서
SPACE
를 Chat API의spaces.list()
메서드나 스페이스의 URL에서 가져올 수 있는 스페이스 이름으로 바꿉니다.코드에서
MESSAGE
를 메시지 이름으로 바꿉니다. 이 이름은 Chat API를 사용하여 메시지를 비동기식으로 만든 후 반환된 응답 본문에서 얻거나 생성 시 메시지에 할당된 맞춤 이름으로 바꿉니다.작업 디렉터리에서 샘플을 빌드하고 실행합니다.
python3 chat_delete_message.py
제한사항 및 고려사항
- Google Chat에서 메시지의
name
를 가져올 수 있는 유일한 방법은 메시지를 만들 때 반환된 응답 본문을 사용하는 것입니다. 작성한 메시지의name
를 기록해 두세요. 그러면 나중에 읽거나 업데이트하거나 삭제해야 할 때 참조할 수 있습니다. 또는 메시지 이름 지정을 고려해 보세요. - 서비스 계정을 사용하여 앱으로 인증하면 Chat 앱에서 메시지만 읽고 업데이트하고 삭제할 수 있습니다.
- 사용자 인증을 사용하여 작업을 수행하면 Google Chat은 사용자에게 권한을 부여한 사용자 대신 작업을 수행한 앱의 이름을 알려주는 속성 메시지를 표시할 수 있습니다. 개발자 프리뷰: 앱에서