이 문서에서는 인증된 사용자가 액세스할 수 있는 메시지를 검색하기 위해 Google Chat API의 Message 리소스에서
search
메서드를 사용하는 방법을 설명합니다.
사용자 인증을 사용하면 사용자가 참여한 모든 대화 또는 특정 대화 내에서 메시지를 검색할 수 있습니다. 예를 들어 특정 키워드가 포함된 메시지, 사용자를 멘션하는 메시지, 읽지 않은 메시지 또는 첨부파일이 있는 메시지를 검색할 수 있습니다.
Chat API에서 채팅 메시지는
Message 리소스로 표시됩니다.
Chat 사용자는 텍스트가 포함된 메시지만 보낼 수 있지만 Chat 앱은 정적 또는 대화형 사용자 인터페이스 표시, 사용자로부터 정보 수집, 메시지 비공개 전송 등 다양한 메시지 기능을 사용할 수 있습니다. Chat API에서 사용할 수 있는 메시징
기능에 대한 자세한 내용은
Google Chat 메시지 개요를 참고하세요.
기본 요건
Node.js
- Google Chat에 액세스할 수 있는 Business 또는 Enterprise Google Workspace 계정 Google Chat
- 환경 설정:
- 승인 범위를 선택합니다.
Python
- Google Chat에 액세스할 수 있는 Business 또는 Enterprise Google Workspace 계정 Google Chat
- 환경 설정:
- 승인 범위를 선택합니다.
자바
- Google Chat에 액세스할 수 있는 Business 또는 Enterprise Google Workspace 계정 Google Chat
- 환경 설정:
- 승인 범위를 선택합니다.
Apps Script
- Google Chat에 액세스할 수 있는 Business 또는 Enterprise Google Workspace 계정 Google Chat
- 환경 설정:
- 승인 범위를 선택합니다.
메일 검색
사용자 인증으로 메시지를 검색하려면 요청에 다음을 전달하세요.
chat.messages.readonly또는chat.messages승인 범위를 지정합니다.SearchMessages메서드를 호출합니다.사용자가 회원으로 속한 모든 스페이스 내에서 검색하려면
parent를spaces/-로 설정합니다. 다른 값을 사용하면 오류가 발생합니다.filter필드에 쿼리 문자열을 지정합니다. 쿼리에는 키워드와 필터가 포함될 수 있습니다.
다음 코드 샘플은 '작업' 키워드가 포함된 읽지 않은 메시지를 검색합니다.
Node.js
/**
* Searches for messages in Google Chat.
* @param {string} filter The search query.
*/
async function searchMessages(filter) {
const {ChatServiceClient} = require('@google-apps/chat').v1;
// Instantiates a client
const chatClient = new ChatServiceClient();
// See https://github.com/googleworkspace/node-samples/blob/main/chat/client-libraries/cloud/authentication-utils.js
// for an example of how to authenticate the request.
// Construct request
const request = {
// Parent must be "spaces/-" to search across all spaces.
parent: 'spaces/-',
filter: filter,
};
// Run request
const iterable = await chatClient.searchMessagesAsync(request);
for await (const response of iterable) {
console.log(response);
}
}
searchMessages('tasks AND is_unread()');
Python
from google.apps import chat_v1
def search_messages(filter_str: str):
"""
Searches for messages in Google Chat.
Args:
filter_str: The search query.
"""
# Create a client
client = chat_v1.ChatServiceClient()
# See https://github.com/googleworkspace/python-samples/blob/main/chat/client-libraries/cloud/authentication_utils.py
# for an example of how to authenticate the request.
# Initialize request argument
request = chat_v1.SearchMessagesRequest(
# Parent must be "spaces/-" to search across all spaces.
parent="spaces/-",
filter=filter_str
)
# Make the request
page_result = client.search_messages(request=request)
# Handle the response
for response in page_result:
print(response)
search_messages('tasks AND is_unread()')
자바
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.SearchMessageResult;
import com.google.chat.v1.SearchMessagesRequest;
public class SearchMessages {
public static void main(String[] args) throws Exception {
searchMessages("tasks AND is_unread()");
}
/**
* Searches for messages in Google Chat.
*
* @param filter The search query.
*/
public static void searchMessages(String filter) throws Exception {
// See https://github.com/googleworkspace/java-samples/blob/main/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/AuthenticationUtils.java
// for an example of how to authenticate the request.
try (ChatServiceClient chatServiceClient = ChatServiceClient.create()) {
SearchMessagesRequest request =
SearchMessagesRequest.newBuilder()
.setParent("spaces/-")
.setFilter(filter)
.build();
for (SearchMessageResult result : chatServiceClient.searchMessages(request).iterateAll()) {
System.out.println(result.getMessage().getText());
}
}
}
}
Apps Script
javascript
/**
* Searches for messages in Google Chat.
*/
function searchMessages() {
const filter = 'tasks AND is_unread()';
const url = 'https://chat.googleapis.com/v1/spaces/-/messages:search';
const request_payload = {
filter: filter
};
try {
const response = UrlFetchApp.fetch(url, {
method: 'post',
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
},
contentType: 'application/json',
payload: JSON.stringify(request_payload)
});
if (response.results) {
for (const result of response.results) {
console.log('Message text: %s', result.message.text);
}
} else {
console.log('No messages found.');
}
} catch (err) {
console.log('Failed to search messages with error: %s', err.message);
}
}
검색 필터 및 연산자 사용
filter 필드에서 키워드, 필드, 함수를 사용하여 검색 결과를 구체화할 수 있습니다. 자세한 내용은
SearchMessagesRequest를 참고하세요.
키워드로 검색
특정 텍스트가 포함된 메시지를 검색하려면 키워드를 입력합니다. 예를 들어 대기 중인 보고서를 검색하려면 pending reports를 사용합니다.
필드로 검색
특정 메시지 또는 스페이스 필드로 결과를 필터링할 수 있습니다. 예를 들면 다음과 같습니다.
create_time: 메시지가 생성된 시간으로 필터링합니다. 예:create_time > "2023-01-01T00:00:00Z"sender.name: 발신자의 리소스 이름으로 필터링합니다. 예:sender.name = "users/1234567890"space.name: 검색을 특정 스페이스로 제한합니다. 예:space.name = "spaces/ABCDEFGH"space.display_name: 표시 이름의 일부 일치를 기반으로 스페이스를 필터링합니다. 결과는 상위 5개 스페이스 일치로 제한됩니다. 예:space.display_name:Projectattachment: 첨부파일이 있는지 확인합니다. 예:attachment:*annotations.user_mentions.user.name: 멘션으로 필터링합니다. 예:annotations.user_mentions.user.name:"users/me"
함수를 사용하여 검색
다음 함수를 통해 고급 필터링을 사용할 수 있습니다.
has_link: 하이퍼링크가 하나 이상 포함된 메시지를 반환합니다.is_unread: 사용자가 읽지 않은 메시지를 반환합니다.
서로 다른 필드에서는 AND 연산자만 지원됩니다. 예:
sender.name = "users/me" AND is_unread().