Skill: soraclub/feishu-master (version 1.0.0)

--- name: feishu-master description: AI Tool Extension for Feishu API - A progressively extensible skill that enables AI tools (OpenClaw, Claude Code, etc.) to leverage Feishu capabilities on-demand. Only implements APIs when needed, avoiding premature development. --- # Feishu Skill - AI Tool Extension for Feishu API A progressively extensible skill designed for AI tools to leverage Feishu capabilities. The core philosophy is **implement only what you need, when you need it**. ## ⚠️ CRITICAL: After Creating New Scripts **You MUST update `scripts/script_index.json` immediately after creating any new script.** Failure to update the index will cause: - Future AI lookup cannot find the newly created script - Duplicate implementation of the same functionality - Confusion for other AI tools using this skill **Action required:** Add an entry to `scripts/script_index.json` with fields: `name`, `description`, `usage_hint`, `added_date`, `tags` ## Design Philosophy This skill is **designed specifically for AI tools**, not for human manual use. When an AI tool receives a task involving Feishu: 1. **Check existing scripts first** - Search `scripts/script_index.json` for already-implemented APIs 2. **Implement only if needed** - If no match exists, use Context7 to query Feishu OpenAPI documentation 3. **Add to index** - Once implemented, update the index to avoid future re-implementation This approach ensures: - **No wasted effort** - Only implement APIs when actually needed - **Progressive expansion** - The skill grows based on real usage patterns - **Efficient lookup** - AI tools can quickly find what's already available ## Quick Start This skill works out of the box once authentication is configured: ```bash # Configure authentication (one-time setup) cd scripts/env echo '{"app_id": "your_app_id", "app_secret": "your_app_secret"}' > app.json ``` ## AI Workflow ### Decision Logic When AI encounters a Feishu-related task, follow this decision tree: **Step 1: Check index file** ``` Read scripts/script_index.json Search by: description, tags ``` **If match found:** - Run `python3 script.py --help` to understand parameters - Execute the script - Return result **If NO match found:** - Use Context7 to query Feishu API documentation: ``` Library: open.feishu.cn / larksuite Query: "[specific requirement, e.g., 如何获取群组成员列表]" ``` - Implement new Python script based on documentation - Execute and test - **IMPORTANT:** Update `scripts/script_index.json` to add the new script **If execution fails:** - Check API error messages - Use Context7 or `references/doc_urls.txt` to consult documentation - Fix the script - Re-test ### Critical Decision Points When deciding between "use existing" vs "implement new", consider: - **Is there a semantic match?** Even if parameter names differ, if the functionality is equivalent, use existing script - **What's the cost of implementing?** Simple single-call APIs → implement immediately. Complex multi-call workflows → consider reusing existing scripts - **Can this compose from existing scripts?** Sometimes new features can be achieved by combining multiple existing scripts ## Technical Reference ### Script Index Format `scripts/script_index.json` structure: ```json { "version": "1.0", "last_updated": "2026-02-12T12:00:00Z", "scripts": [ { "name": "get_group_members", "description": "获取指定群组的人员列表", "usage_hint": "python3 get_group_members.py <open_chat_id>", "added_date": "2026-02-12", "tags": ["group", "member", "user"] } ] } ``` **Key fields for AI search:** - `description`: Human-readable explanation of functionality - `tags`: Array of keywords for matching (prioritize these for fuzzy matching) ### Authentication **Configuration file:** `scripts/env/app.json` ```json { "app_id": "cli_xxxxxxxxxxxxxxxx", "app_secret": [REDACTED_SECRET] } ``` To obtain credentials: 1. Login to [Feishu Open Platform](https://open.feishu.cn/) 2. Create or select an application 3. Get App ID and App Secret from application details **Token management:** `get_token.py` handles token lifecycle: - Automatic caching during validity period - Auto-refresh 5 minutes before expiration - Cache file: `scripts/env/token_cache.json` ### Script Template When implementing new APIs, use this template: ```python #!/usr/bin/env python3 """ [Complete functional description] Usage: python3 script.py <param1> <param2> [options] Parameters: param1: Parameter description param2: Parameter description Options: --page-size: Page size (default: 20) --page-[REDACTED_SECRET] token Output: JSON format output: { "code": 0, "msg": "success", "data": { ... } } References: Feishu API: https://open.feishu.cn/document/... """ import sys import json import subprocess from pathlib import Path import requests # Configuration TOKEN_SCRIPT = Path(__file__).parent / "get_token.py" BASE_URL = "https://open.feishu.cn" def get_token(): """Get Feishu access token""" result = subprocess.run( [sys.executable, str(TOKEN_SCRIPT)], capture_output=True, text=True, check=True ) return result.stdout.strip() def api_function(param1, param2, token, **kwargs): """API call function""" headers = {"Authorization": f"Bearer {token}"} # ... implement API call pass def main(): # Handle --help if "--help" in sys.argv or "-h" in sys.argv: print(__doc__) return # Parse required parameters if len(sys.argv) < 3: print(__doc__, file=sys.stderr) sys.exit(1) param1 = sys.argv[1] param2 = sys.argv[2] kwargs = {} # Parse optional parameters for i in range(3, len(sys.argv)): if sys.argv[i].startswith("--"): key = sys.argv[i][2:].replace("-", "_") i += 1 if i < len(sys.argv): kwargs[key] = sys.argv[i] # Get token [REDACTED_SECRET]) # Call API result = api_function(param1, param2, token, **kwargs) # Output JSON print(json.dumps(result, indent=2, ensure_ascii=False)) if __name__ == "__main__": main() ``` **Development standards:** 1. **⚠️ CRITICAL:** After creating any new script, you MUST update `scripts/script_index.json` immediately 2. Complete docstring with Usage, Parameters, Options, Output sections 3. Support `--help` parameter 4. Use `get_token.py` for authentication 5. Output standard JSON format 6. Proper error handling with friendly messages ### 📋 New Script Creation Checklist When implementing a new API, you MUST complete ALL steps: - [ ] Query Context7 for API documentation - [ ] Create the Python script following the template - [ ] Test the script execution (verify it returns correct JSON) - [ ] **⚠️ UPDATE `scripts/script_index.json`** ← Don't forget this! - [ ] Save the API documentation URL to `references/doc_urls.txt` ### Using Context7 for Feishu API When implementing new APIs, query Feishu documentation via Context7: ``` Library ID: open.feishu.cn / larksuite Query examples: - "如何获取群组成员列表" - "发送消息到飞书群组的 API 使用方法" - "飞书文档操作的 OpenAPI" ``` **Why Context7?** - Provides up-to-date API documentation - Includes code examples and parameters - Faster than searching the web manually - Reduces trial-and-error ## Examples ### AI Task Example 1: Get Group Members **User request:** "Get the member list for group oc_xxxxxxxxxxxxx" **AI decision process:** 1. Search `scripts/script_index.json` → Found match: `get_group_members` 2. Execute: `python3 scripts/get_group_members.py oc_xxxxxxxxxxxxx` 3. Return result ### AI Task Example 2: Add New API Capability **User request:** "Delete a message from the group" **AI decision process:** 1. Search `scripts/script_index.json` → No match 2. Context7 query: "飞书删除消息 API" 3. Get documentation showing `message/delete` endpoint 4. Implement `delete_message.py` script 5. Test execution 6. **⛔ CRITICAL STEP: Update `scripts/script_index.json` with new entry** - DO NOT skip this! 7. Return result **Why step 6 is critical:** - If you skip it, next AI will NOT find `delete_message.py` in the index - This causes duplicate work: same functionality will be re-implemented - The progressive expansion philosophy breaks down ## References - [Feishu Open Platform](https://open.feishu.cn/) - [Feishu API Documentation](https://open.feishu.cn/document/ukTMukTMukTM/ukDNz4SO0MjL5QzM/AI-assistant-code-generation-guide) - DEVELOPMENT.md - Detailed development guidelines

path: DEVELOPMENT.md
content: # Feishu Skill Development Guide

本文档说明如何开发和维护 Feishu Skill。

## 目录结构

```
feishu-master/
├── SKILL.md                   # 用户文档 (主入口)
├── DEVELOPMENT.md             # 本文档 - 开发规范
├── scripts/
│   ├── __init__.py            # Python 包初始化
│   ├── get_token.py           # Token 获取与缓存
│   ├── script_index.json      # 脚本索引文件
│   ├── .gitignore             # 忽略敏感文件
│   ├── [api_scripts]/         # API 脚本 (按需添加)
│   └── env/
│       ├── .gitkeep           # 保持目录结构
│       ├── app.example.json   # 应用配置模板
│       ├── app.json           # 应用配置 (用户填写，不提交)
│       └── token_cache.json   # Token 缓存 (自动生成，不提交)
└── references/
    ├── README.md              # 文档说明
    ├── .gitkeep               # 保持目录结构
    ├── feishu_api.md          # API 摘要参考
    └── doc_urls.txt           # API 文档 URL 集合
```

## 脚本开发标准

### 1. Docstring 规范

每个脚本必须有完整的 docstring，包含以下部分：

```python
"""
[简要功能描述，一行]

[详细功能说明，描述脚本的作用和适用场景]

Usage:
    python3 script.py <param1> <param2> [options]

Parameters:
    param1: 参数说明 (类型、取值范围等)
    param2: 参数说明

Options:
    --option-name: 选项说明
    --page-size: 每页数量 (default: 20)
    --help, -h: 显示帮助信息

Output:
    JSON 格式输出:
    {
      "code": 0,
      "msg": "success",
      "data": { ... }
    }

Error Codes:
    0: 成功
    1: 参数错误
    2: API 调用失败

References:
    飞书 API 文档: https://open.feishu.cn/document/...
"""
```

### 2. Help 支持

必须支持 `--help` 和 `-h` 参数，打印 docstring：

```python
def main():
    if "--help" in sys.argv or "-h" in sys.argv:
        print(__doc__)
        return
    # ... 其他逻辑
```

### 3. Token 使用规范

必须通过 `get_token.py` 获取 token，不要在脚本中重复实现：

```python
def get_token():
    """获取飞书 token"""
    result = subprocess.run(
        [sys.executable, str(TOKEN_SCRIPT)],
        capture_output=True,
        text=True,
        check=True
    )
    return result.stdout.strip()
```

### 4. JSON 输出格式

所有脚本必须输出标准 JSON 格式结果：

```python
print(json.dumps(result, indent=2, ensure_ascii=False))
```

### 5. 错误处理

- API 调用失败时返回标准错误响应
- 提供友好的错误提示
- 使用 `sys.exit(1)` 表示错误退出

### 6. 导入模块

```python
import sys
import json
import subprocess
from pathlib import Path

try:
    import requests
except ImportError:
    print("Error: requests 库未安装，请运行: pip install requests", file=sys.stderr)
    sys.exit(1)
```

## 索引维护规范

### 添加新脚本到 script_index.json

每个新脚本必须添加到 `scripts/script_index.json`：

```json
{
  "version": "1.0",
  "last_updated": "2026-02-12T12:00:00Z",
  "scripts": [
    {
      "name": "script_name",
      "description": "脚本功能描述（中文）",
      "usage_hint": "python3 script_name.py <param1> <param2>",
      "added_date": "2026-02-12",
      "tags": ["tag1", "tag2", "tag3"]
    }
  ]
}
```

### 字段说明

| 字段 | 类型 | 必需 | 说明 |
|------|------|------|------|
| `name` | string | 是 | 脚本名称，使用下划线命名法（同时也是脚本文件名） |
| `description` | string | 是 | 功能描述，简明易懂 |
| `usage_hint` | string | 是 | 使用提示，格式如 `python3 script.py <param>` |
| `added_date` | string | 是 | 添加日期，ISO 格式 `YYYY-MM-DD` |
| `tags` | array | 是 | 标签数组，用于搜索匹配 |

### tags 推荐命名

- **功能类型**: `group`, `user`, `message`, `file`, `calendar`
- **操作类型**: `list`, `get`, `create`, `update`, `delete`, `send`
- **其他**: `member`, `info`, `upload`, `download`

## Token 使用规范

### 规范要点

1. 所有 API 脚本必须使用 `get_token.py` 获取 token
2. 不要在 API 脚本中重复实现 token 获取逻辑
3. Token 缓存机制由 `get_token.py` 统一管理
4. Token 有效期为 2 小时，提前 5 分钟自动刷新

### 错误代码

常见错误：
- `99991663`: 无效的 tenant_access_token（配置错误）
- `99991668`: tenant_access_token 已过期（缓存刷新问题）

## 测试流程

### 开发测试

1. **本地测试脚本**
   ```bash
   python3 scripts/get_token.py --check  # 验证 token
   python3 scripts/your_script.py --help
   python3 scripts/your_script.py <params>
   ```

2. **检查 JSON 输出格式**
   ```bash
   python3 scripts/your_script.py <params> | python3 -m json.tool
   ```

3. **更新索引文件**
   ```bash
   # 手动更新 script_index.json 或编写脚本自动更新
   ```

### 测试应用

建议使用测试应用进行开发：
- 在飞书开放平台创建测试应用
- 获取 test app_id 和 test app_secret
- 使用测试群组和数据避免影响正式环境

## 文档更新流程

### 1. 新 API URL 记录

添加 API 文档 URL 到 `references/doc_urls.txt`：

```txt
## 用户
- 获取用户信息: https://open.feishu.cn/document/server-docs/contact-v3/user/get_user
```

### 2. API 摘要更新

如果 API 是常用 API，更新 `references/feishu_api.md`：

```markdown
### 用户 API

#### 获取用户信息

- **Endpoint**: `GET /open-apis/contact/v3/users/:user_id`
- **用途**: ...
```

### 3. last_updated 更新

每次更新 `script_index.json` 时，更新 `last_updated` 字段：

```json
{
  "version": "1.0",
  "last_updated": "2026-02-12T15:30:00Z",
  ...
}
```

## Context7 使用指南

### 查询 API 文档

当需要实现新 API 时，使用 Context7 查询最新文档：

```
Library: open.feishu.cn / larksuite
Query: "如何获取用户详细信息"
```

### 获取代码示例

```
Library: open.feishu.cn / larksuite
Query: "get user info python example"
```

## 版本管理

### 版本号规范

遵循语义化版本 `MAJOR.MINOR.PATCH`：
- `MAJOR`: 不兼容的 API 变更
- `MINOR`: 向后兼容的功能性新增
- `PATCH`: 向后兼容的问题修正

当前版本：`1.0.0`

### 更新记录

在 SKILL.md 或脚本 docstring 中记录重要变更。

## 最佳实践

### 1. 代码风格

- 使用 4 空格缩进
- 单行宽度不超过 120 字符
- 函数名使用 snake_case
- 常量名使用 UPPER_CASE

### 2. 性能考虑

- 重用 token 减少不必要的请求
- 合理设置超时时间（建议 10-30 秒）
- 处理分页数据时避免一次性获取所有数据

### 3. 安全性

- 不要将敏感信息（app_id, app_secret, token）提交到版本控制
- 使用 .gitignore 保护敏感文件
- token 只有 2 小时有效期，已过期的 token 会自动刷新

### 4. 用户体验

- 提供清晰的错误提示
- 支持 `--help` 查看使用说明
- 输出格式一致（JSON）

## 故障排查

### 常见问题

**问题**: `Error: 配置文件不存在 scripts/env/app.json`
- **解决**: 创建 `scripts/env/app.json` 并填入 app_id 和 app_secret

**问题**: `Error: requests 库未安装`
- **解决**: 运行 `pip install requests`

**问题**: API 返回错误码 `99991663`
- **解决**: 检查 `scripts/env/app.json` 中的 app_id 和 app_secret 是否正确

**问题**: API 返回错误码 `99991668`
- **解决**: 删除 `scripts/env/token_cache.json` 强制刷新 token

## 参考资料

- [飞书开放平台](https://open.feishu.cn/)
- [飞书 API 文档](https://open.feishu.cn/document/server-docs/)
- [飞书错误码](https://open.feishu.cn/document/server-docs/api-call/error-code)
- SKILL.md - 用户文档

path: references/doc_urls.txt
content: # 飞书 API 文档 URL 集合

本文件记录已使用的飞书 API 文档 URL，方便快速查阅。

## 认证
- 获取 tenant_access_token: https://open.feishu.cn/document/server-docs/authentication-management/access-token/tenant_access_token

## 群组
- 获取群组信息: https://open.feishu.cn/document/server-docs/im-v1/group-group/get_group_info
- 获取群组成员列表: https://open.feishu.cn/document/server-docs/im-v1/group-group/get_group_member_list

## 一般
- API 概览: https://open.feishu.cn/document/server-docs/api-overview
- 错误码: https://open.feishu.cn/document/server-docs/api-call/error-code
- 开发者工具: https://open.feishu.cn/document/common-capabilities/debugging-tools


path: references/feishu_api.md
content: # 飞书 API 参考文档

本文档记录常用的飞书 API 及其关键参数。

## 概览

飞书开放平台提供了丰富的 API 能力，当前 skill 实现了：
- 认证（Token 获取）
- 群组管理（获取群组成员）

## 常用 API

### 认证 API

#### 获取 tenant_access_token

- **Endpoint**: `POST /open-apis/auth/v3/tenant_access_token/internal`
- **用途**: 获取应用级别的访问令牌
- **参数**:
  - `app_id`: 应用 ID
  - `app_secret`: 应用密钥
- **返回**:
  - `tenant_access_token`: 访问令牌
  - `expire`: 过期时间（秒）

### 群组 API

#### 获取群组成员列表

- **Endpoint**: `GET /open-apis/im/v1/chats/:chat_id/members`
- **用途**: 获取指定群组成员
- **参数**:
  - `chat_id`: 群组 ID
  - `page_size`: 每页数量
  - `page_token`: 分页标记

## 认证方式

飞书 API 使用 Bearer Token 进行认证：

```
Authorization: Bearer {tenant_access_token}
```

## 错误码

常见错误码：
- `0`: 成功
- `99991663`: 无效的 tenant_access_token
- `99991668`: tenant_access_token 已过期
- `99991001`: 参数错误

## 参考资料

- [飞书开放平台](https://open.feishu.cn/)
- [飞书 API 文档](https://open.feishu.cn/document/server-docs/)
- [错误码说明](https://open.feishu.cn/document/server-docs/api-call/error-code)


path: references/README.md
content: # Feishu API Documentation Reference

This directory contains Feishu API documentation references.

## Files

### feishu_api.md
Summary of commonly used Feishu APIs and their key parameters.

### doc_urls.txt
Collection of Feishu API documentation URLs for quick reference.

## Maintaining This Directory

When adding new API scripts:
1. Add the API documentation URL to `doc_urls.txt`
2. If the API is commonly used, add a summary to `feishu_api.md`

## Note

For the most up-to-date API documentation, always refer to:
- [Feishu Open Platform](https://open.feishu.cn/)
- [Feishu API Documentation](https://open.feishu.cn/document/server-docs/)

path: requirements.txt
content: # Feishu Skill Python Dependencies

requests>=2.31.0

path: scripts/env/app.example.json
content: app_id: cli_xxxxxxxxxxxxxxxx
app_secret: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

path: scripts/get_group_members.py
content: #!/usr/bin/env python3
"""
获取飞书群组成员列表

获取指定飞书群组的成员列表，支持分页查询。

Usage:
    python3 get_group_members.py <chat_id> [options]

Parameters:
    chat_id: 群组 ID (open_chat_id)

Options:
    --page-size: 每页数量，默认为 20
    --page-[REDACTED_SECRET]
    --help, -h: 显示帮助信息

Output:
    JSON 格式输出:
    {
      "code": 0,
      "msg": "success",
      "data": {
        "items": [
          {
            "member_id": "ou_xxxxxxxxxxxxxxxx",
            "member_id_type": "open_id",
            "name": "张三",
            "type": "user"
          }
        ],
        "page_token": "next_page_token",
        "has_more": true
      }
    }

Error Codes:
    0: 成功
    1: 参数错误
    2: API 调用失败

Examples:
    # 获取群组成员列表（第一页）
    python3 get_group_members.py <open_chat_id>

    # 获取 50 个群组成员
    python3 get_group_members.py <open_chat_id> --page-size 50

    # 获取下一页成员
    python3 get_group_members.py <open_chat_id> --page-token "next_page_token"

References:
    飞书 API 文档: https://open.feishu.cn/document/server-docs/im-v1/group-group/get_group_member_list
"""

import sys
import json
import subprocess
from pathlib import Path

try:
    import requests
except ImportError:
    print("Error: requests 库未安装，请运行: pip install requests", file=sys.stderr)
    sys.exit(1)

# 配置
TOKEN_SCRIPT = Path(__file__).parent / "get_token.py"
API_URL = "https://open.feishu.cn/open-apis/im/v1/chats"


def get_token():
    """获取飞书 token"""
    result = subprocess.run(
        [sys.executable, str(TOKEN_SCRIPT)],
        capture_output=True,
        text=True,
        check=True
    )
    return result.stdout.strip()


def get_group_members(chat_id, page_size=20, page_token="", token=None):
    """获取群组成员 API 调用"""
    if token is None:
        [REDACTED_SECRET])

    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }

    params = {
        "page_size": page_size
    }

    if page_token:
        params["page_token"] = page_token

    url = f"{API_URL}/{chat_id}/members"
    response = requests.get(url, headers=headers, params=params, timeout=30)
    data = response.json()

    return data


def parse_arguments():
    """解析命令行参数"""
    if "--help" in sys.argv or "-h" in sys.argv:
        print(__doc__)
        sys.exit(0)

    if len(sys.argv) < 2:
        print(__doc__, file=sys.stderr)
        sys.exit(1)

    chat_id = sys.argv[1]
    page_size = 20
    page_token = ""

    # 解析可选参数
    i = 2
    while i < len(sys.argv):
        if sys.argv[i] == "--page-size" and i + 1 < len(sys.argv):
            try:
                page_size = int(sys.argv[i + 1])
            except ValueError:
                print("Error: --page-size 必须是整数", file=sys.stderr)
                sys.exit(1)
            i += 2
        elif sys.argv[i].startswith("--page-token") and i + 1 < len(sys.argv):
            page_token = sys.argv[i + 1]
            i += 2
        else:
            i += 1

    return chat_id, page_size, page_token


def main():
    # 解析参数
    chat_id, page_size, page_token = parse_arguments()

    # 获取 token
    [REDACTED_SECRET])

    # 调用 API
    result = get_group_members(chat_id, page_size, page_token, token)

    # 输出 JSON
    print(json.dumps(result, indent=2, ensure_ascii=False))

    # 根据返回码设置退出状态
    if result.get("code") != 0:
        sys.exit(2)


if __name__ == "__main__":
    main()

path: scripts/get_token.py
content: #!/usr/bin/env python3
"""
飞书 Token 获取与缓存脚本

Usage:
    python3 get_token.py                  # 获取并缓存 token
    python3 get_token.py --check          # 检查缓存状态

Environment:
    env/ 目录下需要配置:
    - app.json: {"app_id": "...", "app_secret": "..."}
    - token_cache.json: (自动生成)
"""

import os
import json
import time
import sys
from pathlib import Path

try:
    import requests
except ImportError:
    print("Error: requests 库未安装，请运行: pip install requests", file=sys.stderr)
    sys.exit(1)

# 目录配置
ENV_DIR = Path(__file__).parent / "env"
APP_FILE = ENV_DIR / "app.json"
TOKEN_CACHE = ENV_DIR / "token_cache.json"

# API 端点
TOKEN_URL = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"


def load_app_config():
    """加载应用配置"""
    if not APP_FILE.exists():
        print(f"Error: 配置文件不存在 {APP_FILE}", file=sys.stderr)
        print("请先创建 env/app.json 并填入 app_id 和 app_secret", file=sys.stderr)
        print("", file=sys.stderr)
        print("示例:", file=sys.stderr)
        print('  {"app_id": "cli_xxxxxxxxxxxxxxxx", "app_secret": "..."}', file=sys.stderr)
        sys.exit(1)

    try:
        return json.loads(APP_FILE.read_text())
    except json.JSONDecodeError as e:
        print(f"Error: 配置文件格式错误 {APP_FILE}: {e}", file=sys.stderr)
        sys.exit(1)


def get_cached_token():
    """获取缓存的 token"""
    if TOKEN_CACHE.exists():
        try:
            data = json.loads(TOKEN_CACHE.read_text())
            expires_at = data.get("expires_at")
            [REDACTED_SECRET]"tenant_access_token")

            if token and expires_at:
                # 提前5分钟刷新
                if time.time() < expires_at - 300:
                    return token
        except (json.JSONDecodeError, KeyError) as e:
            # 缓存文件损坏，忽略并重新获取
            pass
    return None


def request_new_token(app_id, app_secret):
    """请求新 token"""
    response = requests.post(
        TOKEN_URL,
        json={
            "app_id": app_id,
            "app_secret": app_secret
        },
        timeout=10
    )
    data = response.json()

    if data.get("code") != 0:
        print(f"Error: {data.get('msg')}", file=sys.stderr)
        sys.exit(1)

    return data["tenant_access_token"], data["expire"]


def save_token_cache(token, expire_seconds):
    """保存 token 缓存"""
    ENV_DIR.mkdir(parents=True, exist_ok=True)
    cache_data = {
        "tenant_access_token": token,
        "expires_at": time.time() + expire_seconds
    }
    TOKEN_CACHE.write_text(json.dumps(cache_data, indent=2))


def main():
    check_only = "--check" in sys.argv

    # 1. 尝试获取缓存的 token
    if not check_only:
        cached = get_cached_token()
        if cached:
            print(cached)
            return

    # 2. 请求新 token
    config = load_app_config()
    token, expire = request_new_token(config["app_id"], config["app_secret"])

    # 3. 保存缓存
    save_token_cache(token, expire)

    if check_only:
        print(f"[REDACTED_SECRET]")
        print(f"Expires: {expire} seconds")
    else:
        print(token)


if __name__ == "__main__":
    main()

path: scripts/script_index.json
content: {
  "version": "1.0",
  "last_updated": "2026-03-13T12:00:00Z",
  "scripts": [
    {
      "name": "get_group_members",
      "description": "获取指定飞书群组的成员列表",
      "usage_hint": "python3 get_group_members.py <chat_id> [--page-size N] [--page-token TOKEN]",
      "added_date": "2026-02-12",
      "tags": [
        "group",
        "member",
        "list"
      ]
    }
  ]
}


path: scripts/__init__.py
content: #!/usr/bin/env python3
"""
Feishu API scripts package

This module provides a collection of scripts for interacting with Feishu (Lark) APIs.
Each script follows a consistent pattern:
- Uses get_token.py for authentication
- Supports --help for usage information
- Outputs JSON format results
"""

__version__ = "1.0.0"

Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (HIGH)