Google Docs (클라우드 문서 스킬)
Maton을 통한 관리형 OAuth 인증으로 Google Docs API에 액세스합니다. Google Docs 클라우드 문서를 생성, 읽기, 업데이트, 서식 지정, 일괄 편집할 수 있습니다.
⚠️ 클라우드 vs 로컬 파일 범위 구분:
google-docs(이 스킬): 온라인 Google Docs 클라우드 문서 전용입니다 (docs.google.com/document/d/{documentId}). Maton OAuth API 프록시를 통해 Google의 클라우드 서버와 직접 상호작용합니다.docx스킬: 로컬 디스크에 저장된 로컬.docx/.doc파일을 읽거나, 생성하거나 편집합니다.
빠른 시작
CLI:
# 문서 구조 및 텍스트 내용 가져오기
maton google-docs document get <documentId>
# 새 Google Doc 만들기
maton google-docs document create --title '프로젝트 아키텍처 사양서'
# 문서 본문에 텍스트 추가하기
maton google-docs document write <documentId> --text '회의록: Q3 로드맵 논의.'
Python:
python <<'EOF'
import urllib.request, os, json
req = urllib.request.Request('https://api.maton.ai/google-docs/v1/documents/<documentId>')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
기본 URL
https://api.maton.ai/google-docs/{native-api-path}
Maton은 docs.googleapis.com으로 요청을 프록시하고 OAuth 토큰을 자동으로 주입합니다.
CLI 설치 (선택 사항 — 에이전트가 결정)
Maton CLI는 선택 사항입니다. 에이전트는 환경에 따라 설치 여부를 결정할 수 있습니다.
macOS / Linux
curl -fsSL https://maton.ai/install.sh | bash
Windows
irm https://maton.ai/install.ps1 | iex
npm (크로스 플랫폼)
npm install -g @maton/cli
Homebrew (macOS)
brew install maton-ai/cli/maton
설치 후 다음 명령어로 확인합니다:
maton --version
인증
CLI:
maton login # 브라우저에서 API 키 입력
maton login --interactive # 브라우저 생략, API 키 직접 붙여넣기
maton whoami # 현재 인증 상태 표시
수동:
- maton.ai에서 로그인하거나 계정을 만듭니다.
- maton.ai/settings로 이동합니다.
- API 키를 복사합니다.
- API 키를
MATON_API_KEY환경 변수로 설정합니다:
export MATON_API_KEY="YOUR_API_KEY"
연결 관리
Google Docs OAuth 연결은 https://api.maton.ai에서 관리합니다.
연결 목록
CLI:
maton connection list google-docs --status ACTIVE
maton api -X GET /connections -f app=google-docs -f status=ACTIVE
Python:
python <<'EOF'
import urllib.request, os, json
req = urllib.request.Request('https://api.maton.ai/connections?app=google-docs&status=ACTIVE')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
연결 생성
CLI:
maton connection create google-docs
maton api /connections -f app=google-docs
Python:
python <<'EOF'
import urllib.request, os, json
data = json.dumps({'app': 'google-docs'}).encode()
req = urllib.request.Request('https://api.maton.ai/connections', data=data, method='POST')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
req.add_header('Content-Type', 'application/json')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
응답:
{
"connection": {
"connection_id": "{connection_id}",
"status": "ACTIVE",
"url": "https://connect.maton.ai/?session_token=...",
"app": "google-docs"
}
}
반환된 url을 브라우저에서 열어 OAuth 인증을 완료합니다.
연결 조회
CLI:
maton connection get {connection_id} # 별칭: maton connection view
maton api /connections/{connection_id}
삭제
CLI:
maton connection delete {connection_id} --yes
maton api -X DELETE /connections/{connection_id}
연결 지정
여러 Google Docs 연결이 있는 경우 사용할 연결을 지정합니다:
CLI:
maton google-docs document get <documentId> --connection {connection_id}
maton api /google-docs/v1/documents/<documentId> --connection {connection_id}
Python:
python <<'EOF'
import urllib.request, os, json
req = urllib.request.Request('https://api.maton.ai/google-docs/v1/documents/<documentId>')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
req.add_header('Maton-Connection', '{connection_id}')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
연결이 여러 개인 경우 항상 연결을 지정하여 요청이 올바른 계정으로 전달되도록 합니다.
보안 및 권한
- 액세스는 연결된 Google 계정 내의 Google Docs로 제한됩니다.
- 모든 쓰기 및 삭제 작업에는 명시적인 사용자 승인이 필요합니다. 실행하기 전에 사용자에게 대상 리소스 ID와 콘텐츠 변경 사항을 확인하세요.
API 참조
1. 문서 가져오기
제목, 구조 요소, 인라인 개체 및 단락 스타일을 포함한 전체 문서 개체를 검색합니다.
GET /google-docs/v1/documents/{documentId}
쿼리 매개변수:
suggestionsViewMode-DEFAULT_FOR_CURRENT_ACCESS,PREVIEW_APPROVED,PREVIEW_WITHOUT_SUGGESTIONS,SUGGESTIONS_INLINE.
CLI 예시:
maton google-docs document get <documentId>
maton google-docs document get <documentId> --json
2. 빈 문서 만들기
지정된 제목으로 새 빈 Google Doc을 만듭니다.
POST /google-docs/v1/documents
Content-Type: application/json
{
"title": "분기별 기술 검토"
}
CLI 예시:
maton google-docs document create --title '분기별 기술 검토'
3. 문서에 일반 텍스트 추가하기
CLI를 통해 문서 본문 끝에 일반 텍스트를 추가합니다.
CLI 예시:
# 직접 텍스트 입력
maton google-docs document write <documentId> --text '안녕, 세계!'
# 파일에서 읽기
maton google-docs document write <documentId> -F notes.md
# stdin에서 파이프
echo '파이프 요약' | maton google-docs document write <documentId> -F -
4. 문서 콘텐츠 및 구조 일괄 업데이트 (서식 지정)
문서 텍스트, 서식, 단락 스타일, 머리글/바닥글, 인라인 테이블에 대한 원자적 변형을 수행합니다.
POST /google-docs/v1/documents/{documentId}:batchUpdate
Content-Type: application/json
{
"requests": [
{
"insertText": {
"location": {
"index": 1
},
"text": "임원 요약\n\n이 문서는 클라우드 마이그레이션 전략을 설명합니다."
}
}
]
}
CLI 예시:
maton api -X POST /google-docs/v1/documents/<documentId>:batchUpdate \
-d '{"requests":[{"insertText":{"location":{"index":1},"text":"Hello World\n"}}]}'
batchUpdate의 일반적인 요청 유형:
insertText: 특정 인덱스 위치에 텍스트를 삽입합니다.deleteContentRange: 지정된range(startIndex및endIndex) 내의 콘텐츠를 삭제합니다.replaceAllText: 문서 본문 전체에서 텍스트를 검색하고 바꿉니다.{ "replaceAllText": { "containsText": { "text": "{{PROJECT_NAME}}", "matchCase": true }, "replaceText": "SoloQueue v2.0" } }updateTextStyle: 범위에 굵게, 기울임꼴, 글꼴 크기 또는 색상 서식을 적용합니다.updateParagraphStyle: 제목 스타일(HEADING_1,HEADING_2,NORMAL_TEXT)을 적용합니다.
문서 구조에서 일반 텍스트 추출하기
Google Docs API는 body.content 내의 콘텐츠를 구조 요소로 반환합니다. Python을 사용하여 문서의 일반 텍스트를 읽으려면:
import os, json, urllib.request
req = urllib.request.Request('https://api.maton.ai/google-docs/v1/documents/<documentId>')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
doc = json.load(urllib.request.urlopen(req))
text_chunks = []
for element in doc.get('body', {}).get('content', []):
if 'paragraph' in element:
for elem in element['paragraph'].get('elements', []):
if 'textRun' in elem:
text_chunks.append(elem['textRun'].get('content', ''))
print("".join(text_chunks))
코드 예제
CLI
# 문서 만들기
maton google-docs document create --title '스프린트 계획'
# 문서에 초기 메모 작성
maton google-docs document write <documentId> --text '스프린트 42 목표:\n- 인증 출시\n- 속도 테스트'
# JSON으로 문서 구조 검사
maton google-docs document get <documentId> --json
JavaScript
// 문서 메타데이터 및 콘텐츠 가져오기
const response = await fetch(
'https://api.maton.ai/google-docs/v1/documents/<documentId>',
{
headers: {
'Authorization': `Bearer ${process.env.MATON_API_KEY}`
}
}
);
const doc = await response.json();
console.log(doc.title);
// 새 문서 만들기
const createResponse = await fetch(
'https://api.maton.ai/google-docs/v1/documents',
{
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.MATON_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'RFC: AI Skill Gateway'
})
}
);
const newDoc = await createResponse.json();
console.log('생성된 문서 ID:', newDoc.documentId);
Python
import os
import requests
# 문서 가져오기
response = requests.get(
'https://api.maton.ai/google-docs/v1/documents/<documentId>',
headers={'Authorization': f'Bearer {os.environ["MATON_API_KEY"]}'}
)
doc = response.json()
print(doc.get('title'))
# 문서 만들기
create_response = requests.post(
'https://api.maton.ai/google-docs/v1/documents',
headers={'Authorization': f'Bearer {os.environ["MATON_API_KEY"]}'},
json={'title': 'RFC: AI Skill Gateway'}
)
print('생성됨:', create_response.json().get('documentId'))
참고 사항
- 문서 ID는 불투명 문자열입니다 (URL
https://docs.google.com/document/d/<documentId>/edit에서 추출). maton google-docs document write는 문서 본문 끝에 일반 텍스트를 추가합니다. 특정 인덱스에 텍스트를 삽입하거나, 텍스트를 바꾸거나, 제목/굵게 스타일을 적용하려면batchUpdate를 사용하세요.- 중요: curl 명령어 사용 시 URL에 대괄호가 포함된 경우 글로브(glob) 구문 분석을 비활성화하려면
curl -g를 사용하세요. - 중요: curl 출력을
jq또는 다른 명령어로 파이프할 때, 일부 셸 환경에서는$MATON_API_KEY와 같은 환경 변수가 제대로 확장되지 않을 수 있습니다. 파이핑 시 "잘못된 API 키" 오류가 발생할 수 있습니다.
오류 처리
| 상태 | 의미 |
|---|---|
| 400 | Google Docs 연결 누락 또는 요청 페이로드 형식 오류 |
| 401 | Maton API 키가 잘못되었거나 누락됨 |
| 404 | Google Doc ID를 찾을 수 없거나 액세스 거부됨 |
| 429 | 속도 제한 초과 |
| 5xx | Google Docs API 백엔드 오류 |
문제 해결: API 키 문제
CLI:
maton whoami
maton connection list google-docs
수동:
echo $MATON_API_KEY
python <<'EOF'
import urllib.request, os, json
req = urllib.request.Request('https://api.maton.ai/connections')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
문제 해결: 잘못된 앱 이름
- URL 경로가
google-docs로 시작하는지 확인하세요. 예:
- 올바름:
https://api.maton.ai/google-docs/v1/documents/<documentId> - 올바르지 않음:
https://api.maton.ai/docs/v1/documents/<documentId>