ClawSkills logoClawSkills

Google Drive

Google Drive API 集成,附带托管式 OAuth。列出、搜索、创建和管理文件和文件夹。当用户想要与 Google D... 交互时使用此技能

介绍

# Google Drive

通过托管的 OAuth 身份验证访问 Google Drive API。列出、搜索、创建和管理文件及文件夹。

## 快速开始

```bash # List files python <<'EOF' import urllib.request, os, json req = urllib.request.Request('https://gateway.maton.ai/google-drive/drive/v3/files?pageSize=10') 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://gateway.maton.ai/google-drive/{native-api-path} ```

将 `{native-api-path}` 替换为实际的 Google Drive API 端点路径。网关将请求代理到 `www.googleapis.com` 并自动注入您的 OAuth 令牌。

## 身份验证

所有请求都需要在 Authorization 标头中包含 Maton API 密钥:

``` Authorization: Bearer $MATON_API_KEY ```

**环境变量:** 将您的 API 密钥设置为 `MATON_API_KEY`:

```bash export MATON_API_KEY="YOUR_API_KEY" ```

### 获取您的 API 密钥

1. 在 [maton.ai](https://maton.ai) 登录或创建账户 2. 前往 [maton.ai/settings](https://maton.ai/settings) 3. 复制您的 API 密钥

## 连接管理

在 `https://ctrl.maton.ai` 管理您的 Google OAuth 连接。

### 列出连接

```bash python <<'EOF' import urllib.request, os, json req = urllib.request.Request('https://ctrl.maton.ai/connections?app=google-drive&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 ```

### 创建连接

```bash python <<'EOF' import urllib.request, os, json data = json.dumps({'app': 'google-drive'}).encode() req = urllib.request.Request('https://ctrl.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 ```

### 获取连接

```bash python <<'EOF' import urllib.request, os, json req = urllib.request.Request('https://ctrl.maton.ai/connections/{connection_id}') req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}') print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2)) EOF ```

**响应:** ```json { "connection": { "connection_id": "21fd90f9-5935-43cd-b6c8-bde9d915ca80", "status": "ACTIVE", "creation_time": "2025-12-08T07:20:53.488460Z", "last_updated_time": "2026-01-31T20:03:32.593153Z", "url": "https://connect.maton.ai/?session_token=...", "app": "google-drive", "metadata": {} } } ```

在浏览器中打开返回的 `url` 以完成 OAuth 授权。

### 删除连接

```bash python <<'EOF' import urllib.request, os, json req = urllib.request.Request('https://ctrl.maton.ai/connections/{connection_id}', method='DELETE') req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}') print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2)) EOF ```

### 指定连接

如果您有多个 Google Drive 连接,请使用 `Maton-Connection` 标头指定要使用的连接:

```bash python <<'EOF' import urllib.request, os, json req = urllib.request.Request('https://gateway.maton.ai/google-drive/drive/v3/files?pageSize=10') req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}') req.add_header('Maton-Connection', '21fd90f9-5935-43cd-b6c8-bde9d915ca80') print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2)) EOF ```

如果省略,网关将使用默认(最旧)的活动连接。

## API 参考

### 列出文件

```bash GET /google-drive/drive/v3/files?pageSize=10 ```

使用查询: ```bash GET /google-drive/drive/v3/files?q=name%20contains%20'report'&pageSize=10 ```

仅文件夹: ```bash GET /google-drive/drive/v3/files?q=mimeType='application/vnd.google-apps.folder' ```

特定文件夹中的文件: ```bash GET /google-drive/drive/v3/files?q='FOLDER_ID'+in+parents ```

使用字段: ```bash GET /google-drive/drive/v3/files?fields=files(id,name,mimeType,createdTime,modifiedTime,size) ```

### 获取文件元数据

```bash GET /google-drive/drive/v3/files/{fileId}?fields=id,name,mimeType,size,createdTime ```

### 下载文件内容

```bash GET /google-drive/drive/v3/files/{fileId}?alt=media ```

### 导出 Google 文档

```bash GET /google-drive/drive/v3/files/{fileId}/export?mimeType=application/pdf ```

### 创建文件(仅元数据)

```bash POST /google-drive/drive/v3/files Content-Type: application/json

{ "name": "New Document", "mimeType": "application/vnd.google-apps.document" } ```

### 创建文件夹

```bash POST /google-drive/drive/v3/files Content-Type: application/json

{ "name": "New Folder", "mimeType": "application/vnd.google-apps.folder" } ```

### 更新文件元数据

```bash PATCH /google-drive/drive/v3/files/{fileId} Content-Type: application/json

{ "name": "Renamed File" } ```

### 移动文件到文件夹

```bash PATCH /google-drive/drive/v3/files/{fileId}?addParents=NEW_FOLDER_ID&removeParents=OLD_FOLDER_ID ```

### 删除文件

```bash DELETE /google-drive/drive/v3/files/{fileId} ```

### 复制文件

```bash POST /google-drive/drive/v3/files/{fileId}/copy Content-Type: application/json

{ "name": "Copy of File" } ```

## 文件上传

Google Drive 支持三种上传类型,具体取决于文件大小以及是否需要包含元数据。

### 简单上传(媒体)

适用于不需要设置元数据的 5MB 以下文件。

```bash POST /google-drive/upload/drive/v3/files?uploadType=media Content-Type: text/plain

<file content> ```

**Python 示例:** ```python import urllib.request, os

file_content = b'Hello, this is file content!'

url = 'https://gateway.maton.ai/google-drive/upload/drive/v3/files?uploadType=media' req = urllib.request.Request(url, data=file_content, method='POST') req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}') req.add_header('Content-Type', 'text/plain') response = urllib.request.urlopen(req) ```

### 分段上传

适用于需要包含元数据(名称、描述等)的 5MB 以下文件。

```bash POST /google-drive/upload/drive/v3/files?uploadType=multipart Content-Type: multipart/related; boundary=boundary

--boundary Content-Type: application/json; charset=UTF-8

{"name": "myfile.txt", "description": "My file"} --boundary Content-Type: text/plain

<file content> --boundary-- ```

**Python 示例:** ```python import urllib.request, os, json

boundary = '----Boundary' metadata = json.dumps({'name': 'myfile.txt', 'description': 'My file'}) file_content = 'File content here'

body = f'''--{boundary}\r Content-Type: application/json; charset=UTF-8\r \r {metadata}\r --{boundary}\r Content-Type: text/plain\r \r {file_content}\r --{boundary}--'''.encode()

url = 'https://gateway.maton.ai/google-drive/upload/drive/v3/files?uploadType=multipart' req = urllib.request.Request(url, data=body, method='POST') req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}') req.add_header('Content-Type', f'multipart/related; boundary={boundary}') response = urllib.request.urlopen(req) ```

### 可恢复上传(大文件)

适用于大文件(推荐用于大于 5MB 的文件)。此方法: 1. 启动会话 - 获取上传 URI 2. 分块上传 - 分段发送文件 3. 支持恢复 - 如果中断,可以从中断处继续

**步骤 1:启动上传会话**

```bash POST /google-drive/upload/drive/v3/files?uploadType=resumable Content-Type: application/json; charset=UTF-8 X-Upload-Content-Type: application/octet-stream X-Upload-Content-Length: <file_size>

{"name": "large_file.bin"} ```

响应包含带有上传 URI 的 `Location` 标头。

**步骤 2:上传内容**

```bash PUT <upload_uri> Content-Length: <file_size> Content-Type: application/octet-stream

<file content> ```

**Python 示例(完整):** ```python import urllib.request, os, json

file_path = '/path/to/large_file.bin' file_size = os.path.getsize(file_path)

# Step 1: Initiate resumable upload session url = 'https://gateway.maton.ai/google-drive/upload/drive/v3/files?uploadType=resumable' metadata = json.dumps({'name': 'large_file.bin'}).encode()

req = urllib.request.Request(url, data=metadata, method='POST') req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}') req.add_header('Content-Type', 'application/json; charset=UTF-8') req.add_header('X-Upload-Content-Type', 'application/octet-stream') req.add_header('X-Upload-Content-Length', str(file_size))

response = urllib.request.urlopen(req) upload_uri = response.headers['Location']

# Step 2: Upload file in chunks (e.g., 5MB chunks) chunk_size = 5 * 1024 * 1024 with open(file_path, 'rb') as f: offset = 0 while offset < file_size: chunk = f.read(chunk_size) end = offset + len(chunk) - 1

req = urllib.request.Request(upload_uri, data=chunk, method='PUT') req.add_header('Content-Length', str(len(chunk))) req.add_header('Content-Range', f'bytes {offset}-{end}/{file_size}')

response = urllib.request.urlopen(req) offset += len(chunk)

result = json.load(response) print(f"Uploaded: {result['id']}") ```

**恢复中断的上传:**

如果上传中断,请查询上传 URI 以获取当前状态:

```python req = urllib.request.Request(upload_uri, method='PUT') req.add_header('Content-Length', '0') req.add_header('Content-Range', 'bytes */*') response = urllib.request.urlopen(req) # Check Range header in response to get current offset ```

### 更新文件内容

要更新现有文件的内容:

```bash PATCH /google-drive/upload/drive/v3/files/{fileId}?uploadType=media Content-Type: text/plain

<new file content> ```

**Python 示例:** ```python import urllib.request, os

file_id = 'YOUR_FILE_ID' new_content = b'Updated file content!'

url = f'https://gateway.maton.ai/google-drive/upload/drive/v3/files/{file_id}?uploadType=media' req = urllib.request.Request(url, data=new_content, method='PATCH') req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}') req.add_header('Content-Type', 'text/plain') response = urllib.request.urlopen(req) ```

### 上传到特定文件夹

在元数据中包含文件夹 ID:

```python metadata = json.dumps({ 'name': 'myfile.txt', 'parents': ['FOLDER_ID'] }) ```

### 共享文件

```bash POST /google-drive/drive/v3/files/{fileId}/permissions Content-Type: application/json

{ "role": "reader", "type": "user", "emailAddress": "[email protected]" } ```

## 查询运算符

在 `q` 参数中使用: - `name = 'exact name'` - `name contains 'partial'` - `mimeType = 'application/pdf'` - `'folderId' in parents` - `trashed = false` - `modifiedTime > '2024-01-01T00:00:00'`

使用 `and` 组合: ``` name contains 'report' and mimeType = 'application/pdf' ```

## 常见 MIME 类型

- `application/vnd.google-apps.document` - Google 文档 - `application/vnd.google-apps.spreadsheet` - Google 表格 - `application/vnd.google-apps.presentation` - Google 幻灯片 - `application/vnd.google-apps.folder` - 文件夹 - `application/pdf` - PDF

## 代码示例

### JavaScript

```javascript const response = await fetch( 'https://gateway.maton.ai/google-drive/drive/v3/files?pageSize=10', { headers: { 'Authorization': `Bearer ${process.env.MATON_API_KEY}` } } ); ```

### Python

```python import os import requests

response = requests.get( 'https://gateway.maton.ai/google-drive/drive/v3/files', headers={'Authorization': f'Bearer {os.environ["MATON_API_KEY"]}'}, params={'pageSize': 10} ) ```

## 注意事项

- 使用 `fields` 参数限制响应数据 - 分页使用前一个响应的 `nextPageToken` 中的 `pageToken` - 导出仅适用于 Google Workspace 文件 - **上传类型**:对于简单上传(最大 5MB),使用 `uploadType=media`;对于包含元数据的上传(最大 5MB),使用 `uploadType=multipart`;对于大文件,使用 `uploadType=resumable`(推荐用于 > 5MB) - **上传端点**:文件上传使用 `/upload/drive/v3/files`(注意 `/upload` 前缀) - **可恢复上传**:对于大文件,使用分块传输的可恢复上传(最小分块大小 256KB,推荐 5MB) - **最大文件大小**:Google Drive 支持最大 5TB 的文件 - 重要:使用 curl 命令时,如果 URL 包含方括号(`fields[]`、`sort[]`、`records[]`),请使用 `curl -g` 以禁用 glob 解析 - 重要:当将 curl 输出通过管道传输到 `jq` 或其他命令时,在某些 shell 环境中,像 `$MATON_API_KEY` 这样的环境变量可能无法正确展开。在通过管道传输时,您可能会收到“Invalid API key”错误。

## 错误处理

| 状态 | 含义 | |--------|---------| | 400 | 缺少 Google Drive 连接 | | 401 | Maton API 密钥无效或缺失 | | 429 | 速率受限(每账户每秒 10 次请求) | | 4xx/5xx | 来自 Google Drive API 的透传错误 |

### 故障排除:API 密钥问题

1. 检查是否设置了 `MATON_API_KEY` 环境变量:

```bash echo $MATON_API_KEY ```

2. 通过列出连接验证 API 密钥是否有效:

```bash python <<'EOF' import urllib.request, os, json req = urllib.request.Request('https://ctrl.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 ```

### 故障排除:应用名称无效

1. 确保您的 URL 路径以 `google-drive` 开头。例如:

- 正确:`https://gateway.maton.ai/google-drive/drive/v3/files` - 错误:`https://gateway.maton.ai/drive/v3/files`

## 资源

- [Drive API 概览](https://developers.google.com/drive/api/reference/rest/v3) - [列出文件](https://developers.google.com/drive/api/reference/rest/v3/files/list) - [获取文件](https://developers.google.com/drive/api/reference/rest/v3/files/get) - [创建文件](https://developers.google.com/drive/api/reference/rest/v3/files/create) - [更新文件](https://developers.google.com/drive/api/reference/rest/v3/files/update) - [删除文件](https://developers.google.com/drive/api/reference/rest/v3/files/delete) - [导出文件](https://developers.google.com/drive/api/reference/rest/v3/files/export) - [上传文件](https://developers.google.com/drive/api/guides/manage-uploads) - [可恢复上传](https://developers.google.com/drive/api/guides/manage-uploads#resumable) - [搜索查询语法](https://developers.google.com/drive/api/guides/search-files) - [Maton 社区](https://discord.com/invite/dBfFAcefs2) - [Maton 支持](mailto:[email protected])

更多产品