이 가이드에서는 Google Chat 앱에서 메시지를 보내는 다양한 방법을 설명합니다.
- 사용자 상호작용에 응답하여 실시간으로 문자 메시지 및 카드 메시지를 전송합니다.
Message
리소스에서create
메서드를 호출하여 텍스트 및 카드 메시지를 비동기식으로 전송합니다.- 메시지 대화목록을 시작하거나 답장합니다.
- 메시지를 보내고 이름을 지정합니다.
Message
리소스는 Google Chat의 텍스트 또는 카드 메시지를 나타냅니다. 상응하는 메서드를 호출하여 Google Chat API에서 메시지를 create
, get
, update
또는 delete
할 수 있습니다. 문자 및 카드 메시지에 관한 자세한 내용은 Google Chat 메시지 개요를 참고하세요.
텍스트 또는 카드 메시지를 비동기식으로 보내기 위해 Google Chat API의 Message
리소스에서 create
메서드를 호출하는 대신 Google Chat 앱은 메시지를 만들어 사용자 상호작용에 실시간으로 응답할 수도 있습니다. 사용자 상호작용에 대한 응답에는 인증이 필요하지 않으며 대화형 대화상자 및 링크 미리보기를 포함한 다른 유형의 메시지도 지원됩니다. 자세한 내용은 Google Chat 앱과의 상호작용 수신 및 응답을 참고하세요.
기본 요건
Node.js
- Google Chat에 액세스할 수 있는 Google Workspace 계정
- 게시된 채팅 앱. 채팅 앱을 빌드하려면 이 quickstart을 따르세요.
- 채팅 앱이 비동기 메시지를 보낼 수 있도록 구성된 승인입니다. 실시간으로 메시지를 보내는 데 승인 구성은 필요하지 않습니다.
Python
- Python 3.6 이상
- pip 패키지 관리 도구
Python용 최신 Google 클라이언트 라이브러리입니다. 설치하거나 업데이트하려면 명령줄 인터페이스에서 다음 명령어를 실행합니다.
pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib oauth2client
게시된 채팅 앱. 채팅 앱을 만들고 게시하려면 Google Chat 앱 빌드를 참조하세요.
채팅 앱이 비동기 메시지를 보낼 수 있도록 구성된 승인입니다. 실시간으로 메시지를 보내는 데 승인 구성은 필요하지 않습니다.
Apps Script
- Google Chat에 액세스할 수 있는 Google Workspace 계정
- 게시된 채팅 앱. 채팅 앱을 빌드하려면 이 quickstart을 따르세요.
문자 메시지 보내기
이 섹션에서는 다음 두 가지 방법으로 문자 메시지를 보내는 방법을 설명합니다.
- 사용자 상호작용에 응답하여 실시간으로 문자 메시지를 보냅니다.
- Google Chat API를 비동기식으로 호출하여 문자 메시지를 보냅니다.
실시간으로 문자 메시지 보내기
이 예에서는 채팅 앱이 스페이스에 추가될 때마다 문자 메시지를 만들어 전송합니다. 사용자 온보딩을 위한 권장사항을 알아보려면 유용한 온보딩으로 사용자 및 스페이스 시작하기를 참고하세요.
사용자가 채팅 앱을 스페이스에 추가할 때 문자 메시지를 보내려면 채팅 앱이 ADDED_TO_SPACE
상호작용 이벤트에 응답합니다. ADDED_TO_SPACE
상호작용 이벤트에 SMS로 응답하려면 다음 코드를 사용하세요.
Node.js
/**
* Sends an onboarding message when the Chat app is added to a space.
*
* @param {Object} event The event object from Chat API.
* @return {Object} Response from the Chat app. An onboarding message that
* introduces the app and helps people get started with it.
*/
exports.onMessage = function onMessage(req, res) {
if (req.method === 'GET' || !req.body.message) {
res.send(
'Hello! This function is meant to be used in a Google Chat space.');
}
// Send an onboarding message when added to a Chat space
if(req.body.type === 'ADDED_TO_SPACE') {
res.json({
'text': 'Hi, Cymbal at your service. I help you manage your calendar
from Google Chat. Take a look at your schedule today by typing
`/checkCalendar`, or schedule a meeting with `/scheduleMeeting`. To
learn what else I can do, type `/help`.'
});
}
};
Apps Script
/**
* Sends an onboarding message when the Chat app is added to a space.
*
* @param {Object} event The event object from Chat API.
* @return {Object} Response from the Chat app. An onboarding message that
* introduces the app and helps people get started with it.
*/
function onAddToSpace(event) {
return {
'text': 'Hi, Cymbal at your service. I help you manage your calendar
from Google Chat. Take a look at your schedule today by typing
`/checkCalendar`, or schedule a meeting with `/scheduleMeeting`. To learn
what else I can do, type `/help`.'
}
}
코드 샘플은 다음 문자 메시지를 반환합니다.
비동기식으로 SMS 보내기
다음 섹션에서는 앱 인증 및 사용자 인증을 사용하여 비동기식으로 SMS를 보내는 방법을 설명합니다.
문자 메시지를 보내려면 요청에 다음을 전달합니다.
- 앱 인증에서
chat.bot
승인 범위를 지정합니다. 사용자 인증을 통해chat.messages.create
승인 범위를 지정합니다. Message
리소스에서create
메서드를 호출합니다.
앱 인증이 포함된 SMS 보내기
앱 인증을 사용하여 SMS를 보내는 방법은 다음과 같습니다.
Python
- 작업 디렉터리에서 이름이
chat_create_text_message_app.py
인 파일을 만듭니다. chat_create_text_message_app.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( 'credentials.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_app.py
Chat API는 전송된 메시지를 자세히 설명하는 Message
의 인스턴스를 반환합니다.
사용자 인증이 포함된 문자 메시지 보내기
사용자 인증을 사용하여 문자 메시지를 보내는 방법은 다음과 같습니다.
Python
- 작업 디렉터리에서 이름이
chat_create_text_message_user.py
인 파일을 만듭니다. chat_create_text_message_user.py
에 다음 코드를 포함합니다.import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError # 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.messages.create"] def main(): ''' Authenticates with Chat API via user credentials, then creates a text message in a Chat space. ''' # Start with no credentials. creds = None # 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().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() # Prints details about the created membership. print(result) if __name__ == '__main__': main()
코드에서
SPACE
을 스페이스 이름으로 바꿉니다. 이 이름은 Chat API의spaces.list()
메서드 또는 스페이스의 URL에서 가져올 수 있습니다.작업 디렉터리에서 샘플을 빌드하고 실행합니다.
python3 chat_create_text_message_user.py
Chat API는 전송된 메시지를 자세히 설명하는 Message
의 인스턴스를 반환합니다.
카드 메시지 보내기
이 섹션에서는 다음 두 가지 방법으로 카드 메시지를 보내는 방법을 설명합니다.
- 사용자 상호작용에 응답하여 실시간으로 카드 메시지를 전송합니다.
- Google Chat API를 비동기식으로 호출하여 카드 메시지를 보냅니다.
실시간으로 카드 메시지 전송
채팅 앱은 카드 메시지를 만들어 사용자가 채팅 앱에 메시지를 보내거나 채팅 앱을 스페이스에 추가하는 경우와 같은 사용자 상호작용에 응답할 수 있습니다. 사용자 상호작용에 응답하는 방법에 대한 자세한 내용은 Chat 앱 상호작용 이벤트 수신 및 응답을 참조하세요.
이 예에서는 사용자가 채팅 앱에 메시지를 보내면 채팅 앱은 사용자의 이름과 아바타 이미지를 표시하는 카드 메시지를 전송하여 응답합니다.
Node.js
Python
Apps Script
비동기식으로 카드 메시지 보내기
카드 메시지를 보내려면 요청에 다음을 전달합니다.
- 앱 인증에서
chat.bot
승인 범위를 지정합니다. 사용자 인증으로 카드 메시지를 보낼 수 없습니다. Message
리소스에서create
메서드를 호출합니다.
다음은 카드 메시지의 예입니다.
앱 인증으로 카드 메시지를 보내는 방법은 다음과 같습니다.
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( 'credentials.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 the Chat 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
필드를 지정합니다(선택사항).
메시지 대화목록에 답장하려면 스레드의 threadKey
또는 name
필드를 지정하는 메시지를 보냅니다. 사람이나 다른 채팅 앱에서 스레드를 만든 경우 thread.name
필드를 사용해야 합니다.
일치하는 스레드가 없으면 messageReplyOption
필드를 설정하여 메시지를 새 스레드를 시작할지 또는 게시하지 못할지를 지정할 수 있습니다.
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( 'credentials.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', # 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. # # REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD replies to an existing thread # if one exists, otherwise it starts a new one. 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
Chat API는 전송된 메시지를 자세히 설명하는 Message
의 인스턴스를 반환합니다.
메시지 전송 및 이름 지정
이 섹션에서는 맞춤 이름으로 메시지를 보내는 방법을 설명합니다. 메시지 이름을 사용하여 메시지를 가져오기, 업데이트 또는 삭제할 수 있습니다.
또한 커스텀 이름을 할당하면 채팅 앱이 메시지를 보낼 때 반환된 응답 본문에서 메시지 name
를 저장하지 않고 메시지를 회수할 수 있습니다.
커스텀 이름을 할당해도 생성된 name
필드(메시지의 리소스 이름)는 바뀌지 않습니다. 대신 커스텀 이름을 clientAssignedMessageId
필드로 설정하며, 메시지 업데이트 또는 삭제와 같은 이후 작업을 처리할 때 참조할 수 있습니다.
커스텀 이름에는 다음과 같은 요구사항이 있습니다.
client-
로 시작합니다. 예를 들어client-custom-name
은 유효한 맞춤 이름이지만custom-name
는 그렇지 않습니다.- 소문자, 숫자, 하이픈만 포함해야 합니다.
- 63자(영문 기준) 이하여야 합니다.
- 메시지를 전송하는 동안 사용된 커스텀 이름을 지정하면 오류가 반환되지만
update
및delete
와 같은 다른 메서드는 예상대로 작동합니다.
메시지를 보내고 이름을 지정하는 방법은 다음과 같습니다.
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( 'credentials.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
Chat API는 전송된 메시지를 자세히 설명하는 Message
의 인스턴스를 반환합니다.
문제 해결
Google Chat 앱 또는 카드에서 오류를 반환하면 채팅 인터페이스에 '문제 발생' 또는 '요청을 처리할 수 없습니다'라는 메시지가 표시됩니다. 채팅 UI에 오류 메시지가 표시되지 않지만 채팅 앱 또는 카드에서 예기치 않은 결과가 발생하는 경우가 있습니다. 예를 들어 카드 메시지가 표시되지 않을 수 있습니다.
Chat UI에 오류 메시지가 표시되지 않더라도 Chat 앱의 오류 로깅이 사용 설정된 경우 오류를 해결하는 데 도움이 되는 자세한 오류 메시지와 로그 데이터가 제공됩니다. 오류 보기, 디버깅, 수정에 관한 도움말은 Google Chat 오류 문제 해결 및 수정하기를 참고하세요.
관련 주제
- 메일의 서식을 지정합니다.
- 메시지 세부정보 확인하기
- 스페이스의 메시지 나열하기
- 메시지를 업데이트합니다.
- 메시지 삭제
- Google Chat 메시지에서 사용자 식별하기
- 수신 웹훅을 사용하여 Google Chat에 메시지 보내기