Metadata-Version: 2.4
Name: zhihu-tui
Version: 0.1.3
Summary: A CLI for Zhihu — browse questions, answers, articles from the terminal
Project-URL: Homepage, https://github.com/Xiaofan629/zhihu-cli
Project-URL: Repository, https://github.com/Xiaofan629/zhihu-cli
Project-URL: Issues, https://github.com/Xiaofan629/zhihu-cli/issues
Author: Xiaofan629
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: cli,terminal,zhihu
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.10
Requires-Dist: aiohttp>=3.0
Requires-Dist: browser-cookie3>=0.19
Requires-Dist: click>=8.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: rich>=13.0
Provides-Extra: dev
Requires-Dist: mypy>=1.15.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest-mock>=3.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.11.0; extra == 'dev'
Requires-Dist: types-pyyaml>=6.0.12; extra == 'dev'
Description-Content-Type: text/markdown

# zhihu-cli

[![CI](https://github.com/Xiaofan629/zhihu-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/Xiaofan629/zhihu-cli/actions/workflows/ci.yml)
[![PyPI version](https://img.shields.io/pypi/v/zhihu_tui.svg)](https://pypi.org/project/zhihu-tui/)
[![Python versions](https://img.shields.io/pypi/pyversions/zhihu_tui.svg)](https://pypi.org/project/zhihu-tui/)
[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](./LICENSE)

A CLI for Zhihu — browse questions, answers, articles from the terminal

[English](#features) | [中文](#功能特性)

## Features

- ❓ **Question** — details, answers
- 💬 **Answer** — details, comments
- 📰 **Article** — details, comments
- 💡 **Pin** — pin (想法) details, comments
- 👤 **User** — profile, answers, articles, pins
- 🔍 **Search** — search content, questions, people, articles, answers
- 🔥 **Hot** — hot list
- 📂 **Collections** — favorites, following, collections, personalized feed
- 👍 **Interactions** — vote, follow, unfollow
- 🔐 **Smart auth** — auto-extracts cookies from Chrome/Firefox/Edge/Brave, or manual cookie login
- 📊 **Structured output** — major query commands support `--yaml` and `--json`
- 🤖 **Agent-friendly defaults** — non-TTY stdout defaults to YAML
- 📦 **Stable envelope** — `{ok, schema_version, data/error}` envelope for all structured output
- 🧱 **Normalized payloads** — command-layer output is normalized instead of leaking raw API responses
- 🌐 **Brave support** — auto-extracts cookies from Chrome, Firefox, Edge, and Brave

## Installation

```bash
# Recommended: uv tool (fast, isolated)
uv tool install zhihu-tui

# Or: pipx
pipx install zhihu-tui
```

Upgrade to the latest version:

```bash
uv tool upgrade zhihu-tui
# Or: pipx upgrade zhihu-tui
```

> **Tip:** Upgrade regularly to avoid unexpected errors from outdated API handling.

Or from source:

```bash
git clone https://github.com/Xiaofan629/zhihu-cli
cd zhihu-cli
uv sync
```

Run tests in the project environment:

```bash
uv sync --extra dev
uv run pytest -q
uv run ruff check .
```

If the project directory was moved and stale virtualenv wrappers remain, rerun:

```bash
uv sync --extra dev --reinstall
```

## Usage

```bash
# Login & account
zhihu status                                                           # Check login status
zhihu login --z-c0 <cookie>                                            # Login with z_c0 cookie
zhihu logout                                                           # Clear saved credentials
zhihu whoami                                                           # Detailed profile

# Questions
zhihu question 1908480548659225029                                      # Question details with answers
zhihu question https://www.zhihu.com/question/1908480548659225029       # Also accepts URL
zhihu question 1908480548659225029 -n 5                                 # Top 5 answers

# Answers
zhihu answer 1908294773132981653                                        # Answer details with comments
zhihu answer https://www.zhihu.com/question/.../answer/1908294773132981653  # Also accepts URL

# Articles
zhihu article 2010807391655052859                                       # Article details with comments
zhihu article https://zhuanlan.zhihu.com/p/2010807391655052859          # Also accepts URL

# Pins
zhihu pin 1908503592131847116                                           # Pin (想法) details with comments
zhihu pin https://www.zhihu.com/pin/1908503592131847116                 # Also accepts URL

# Users
zhihu user qiu-qiu-ni-men-bie-xue-liao-21                              # User profile
zhihu user-answers qiu-qiu-ni-men-bie-xue-liao-21 -n 5                 # User's answers
zhihu user-articles qiu-qiu-ni-men-bie-xue-liao-21 -n 5                # User's articles
zhihu user-pins zhi-hu-14-94-58 -n 5                                   # User's pins

# Search
zhihu search "特朗普"                                                   # General search (default)
zhihu search "特朗普" --type people                                     # Search people
zhihu search "特朗普" --type scholar                                    # Search papers
zhihu search "特朗普" --type column                                     # Search columns
zhihu search "特朗普" --type km_general                                 # Search Zhihu Select (盐选内容)
zhihu search "特朗普" --type publication                                # Search eBooks
zhihu search "特朗普" --type ring                                       # Search circles
zhihu search "特朗普" --type topic                                      # Search topics
zhihu search "特朗普" --type zvideo                                     # Search videos
zhihu search "特朗普" -n 5                                              # Top 5 results

# Discovery
zhihu hot                                                               # Hot list (top 30)
zhihu hot -n 10                                                         # Top 10

# Collections
zhihu favorites                                                         # My favorite folders
zhihu favorites -n 10                                                   # Limit results
zhihu collections                                                       # My collections
zhihu collections <url_token>                                           # Someone else's collections
zhihu following                                                         # My following list
zhihu feed                                                              # Personalized feed
zhihu feed -n 5                                                         # Limit results

# Interactions
zhihu vote answer 1908294773132981653                                   # Vote up an answer
zhihu vote answer 1908294773132981653 --down                            # Cancel vote on an answer
zhihu vote article 2010807391655052859                                  # Vote up an article
zhihu vote pin 1999130577123636672                                      # Vote up a pin
zhihu vote pin 1999130577123636672 --down                               # Cancel vote on a pin
zhihu follow question 1908480548659225029                               # Follow a question
zhihu follow user <url_token>                                           # Follow a user
zhihu unfollow question 1908480548659225029                             # Unfollow a question
zhihu unfollow user <url_token>                                         # Unfollow a user
```

> **Tip:** All commands above support `--json` and `--yaml` flags for structured output.
> Add `--yaml` (recommended for AI agents) or `--json` (for `jq` / strict JSON tooling) to any command.

## Authentication

zhihu-cli uses a 3-tier authentication strategy:

1. **Saved credential** — loads from `~/.zhihu-cli/credential.json`
2. **Browser cookies** — auto-extracts from Chrome, Firefox, Edge, Brave via `browser-cookie3`
3. **Manual login** — `zhihu login --z-c0 <z_c0_cookie_value>`

### Getting your z_c0 cookie

1. Open [zhihu.com](https://www.zhihu.com) and log in
2. Open browser DevTools (F12) → Application → Cookies
3. Copy the value of the `z_c0` cookie
4. Run `zhihu login --z-c0 <value>`

`zhihu status` exits with code `0` only when authenticated; otherwise it exits with `1`.

Most commands work without login. Feed, favorites, following, and interactions require authentication. Write actions (vote, follow, unfollow) require valid credentials.

## Structured Output

All `--json` / `--yaml` output uses the shared envelope format. Major commands emit normalized payloads instead of raw API blobs:

- `zhihu question` → `data.question`, `data.answers`
- `zhihu answer` → `data.answer`, `data.comments`
- `zhihu article` → `data.article`, `data.comments`
- `zhihu pin` → `data.pin`, `data.comments`
- `zhihu hot` → `data[]`
- `zhihu search` → normalized result list
- `zhihu vote` / `zhihu follow` / `zhihu unfollow` → normalized write-action results

Structured errors use specific codes such as `not_authenticated`, `invalid_input`, `network_error`, `upstream_error`, `not_found`, `rate_limited`, `api_error`, and `internal_error`.

## Use as AI Agent Skill

zhihu-cli ships with a [`SKILL.md`](./SKILL.md) that teaches AI agents how to use it.

### Agent Output Recommendation

If an AI agent needs machine-readable output, prefer `--yaml` first:

- `--yaml` is usually more token-efficient than pretty-printed JSON
- It is still easy to parse for agents and scripts
- Keep `--json` for `jq`, strict JSON-only tooling, or exact downstream schemas
- Non-TTY stdout defaults to YAML automatically

Examples:

```bash
zhihu status --yaml
zhihu question 1908480548659225029 --yaml
zhihu hot -n 5 --yaml
zhihu search "python" -n 5 --yaml
```

For agent usage, also prefer narrower queries (`-n`) to avoid wasting context on oversized payloads.

When an AI agent is asked to summarize a question, it should fetch answers first. Answers usually contain the core content and are the best primary source for summarization. Only fall back to comments when answers are unavailable or insufficient.

## Troubleshooting

- `需要登录` / `权限不足` / `not_authenticated` — Run `zhihu login --z-c0 <cookie>` or ensure you're logged in to zhihu.com in Chrome/Firefox/Edge.
- `NetworkError` — Check your network connection. If behind a proxy, ensure it supports the target domain.
- Chrome Keychain popup — Chrome encrypts cookies via macOS Keychain. Use Edge, Firefox, or Brave cookies instead, or provide cookies manually via `zhihu login --z-c0`.

Structured error codes: `not_authenticated`, `invalid_input`, `network_error`, `upstream_error`, `not_found`, `rate_limited`, `api_error`, `internal_error`.

---

## 功能特性

- ❓ **问题** — 问题详情、回答列表
- 💬 **回答** — 回答详情、评论
- 📰 **文章** — 专栏文章详情、评论
- 💡 **想法** — 想法详情、评论
- 👤 **用户** — 个人资料、回答列表、文章列表、想法列表
- 🔍 **搜索** — 搜索综合内容、问题、用户、文章、回答
- 🔥 **热榜** — 知乎热榜
- 📂 **收藏** — 收藏夹、关注列表、收藏夹列表、个性化 Feed
- 👍 **互动** — 赞同、关注、取消关注
- 🔐 **智能认证** — 自动从 Chrome/Firefox/Edge/Brave 提取 Cookie，或手动登录
- 📊 **结构化输出** — 主要查询命令支持 `--yaml` 和 `--json`
- 🤖 **更适合 Agent** — 非 TTY 环境默认输出 YAML
- 🧱 **规范化 payload** — 结构化输出在命令层做了收口，不再直接暴露原始 API 响应

## 安装

```bash
# 推荐：uv tool（快速、隔离环境）
uv tool install zhihu-tui

# 或者：pipx
pipx install zhihu-tui
```

升级到最新版本：

```bash
uv tool upgrade zhihu-tui
# 或：pipx upgrade zhihu-tui
```

> **提示：** 建议定期升级，避免因版本过旧导致的 API 调用异常。

或从源码安装：

```bash
git clone https://github.com/Xiaofan629/zhihu-cli
cd zhihu-cli
uv sync
```

开发环境验证：

```bash
uv sync --extra dev
uv run pytest -q
uv run ruff check .
```

如果项目目录发生过移动，导致旧的 virtualenv wrapper 失效，可重新执行：

```bash
uv sync --extra dev --reinstall
```

## 使用示例

```bash
# 登录与账号
zhihu status                                                           # 检查登录状态
zhihu login --z-c0 <cookie>                                            # 使用 z_c0 cookie 登录
zhihu logout                                                           # 清除已保存的凭证
zhihu whoami                                                           # 查看个人信息

# 问题
zhihu question 1908480548659225029                                      # 问题详情及回答
zhihu question https://www.zhihu.com/question/1908480548659225029       # 支持传入 URL
zhihu question 1908480548659225029 -n 5                                 # 前 5 个回答

# 回答
zhihu answer 1908294773132981653                                        # 回答详情及评论
zhihu answer https://www.zhihu.com/question/.../answer/1908294773132981653  # 支持传入 URL

# 文章
zhihu article 2010807391655052859                                       # 文章详情及评论
zhihu article https://zhuanlan.zhihu.com/p/2010807391655052859          # 支持传入 URL

# 想法
zhihu pin 1999130577123636672                                           # 想法详情及评论
zhihu pin https://www.zhihu.com/pin/1999130577123636672                 # 支持传入 URL

# 用户
zhihu user zhi-hu-14-94-58                                             # 用户资料
zhihu user-answers zhi-hu-14-94-58 -n 5                                # 用户的回答
zhihu user-articles zhi-hu-14-94-58 -n 5                               # 用户的文章
zhihu user-pins zhi-hu-14-94-58 -n 5                                   # 用户的想法

# 搜索
zhihu search "特朗普"                                                   # 综合搜索（默认）
zhihu search "特朗普" --type people                                     # 搜索用户
zhihu search "特朗普" --type scholar                                    # 搜索论文
zhihu search "特朗普" --type column                                     # 搜索专栏
zhihu search "特朗普" --type km_general                                 # 搜索盐选内容
zhihu search "特朗普" --type publication                                # 搜索电子书
zhihu search "特朗普" --type ring                                       # 搜索圈子
zhihu search "特朗普" --type topic                                      # 搜索话题
zhihu search "特朗普" --type zvideo                                     # 搜索视频
zhihu search "特朗普" -n 5                                              # 前 5 条结果

# 发现
zhihu hot                                                               # 热榜（默认 30 条，最多 30）
zhihu hot -n 10                                                         # 前 10 条

# 收藏
zhihu favorites                                                         # 我的收藏夹
zhihu favorites -n 10                                                   # 限制数量
zhihu collections                                                       # 我的收藏夹列表
zhihu collections <url_token>                                           # 查看他人的收藏夹
zhihu following                                                         # 我的关注列表
zhihu feed                                                              # 个性化 Feed
zhihu feed -n 5                                                         # 限制数量

# 互动
zhihu vote answer 1908294773132981653                                   # 赞同回答
zhihu vote answer 1908294773132981653 --down                            # 取消赞同回答
zhihu vote article 2010807391655052859                                  # 赞同文章
zhihu vote pin 1999130577123636672                                      # 赞同想法
zhihu vote pin 1999130577123636672 --down                               # 取消赞同想法
zhihu follow question 1908480548659225029                               # 关注问题
zhihu follow user <url_token>                                           # 关注用户
zhihu unfollow question 1908480548659225029                             # 取消关注问题
zhihu unfollow user <url_token>                                         # 取消关注用户
```

> **提示：** 以上所有命令均支持 `--json` 和 `--yaml` 标志用于结构化输出。
> 推荐使用 `--yaml`（适合 AI Agent），或 `--json`（适合 `jq` / 严格的 JSON 工具链）。

## 认证策略

zhihu-cli 采用三级认证策略：

1. **已保存凭证** — 从 `~/.zhihu-cli/credential.json` 加载
2. **浏览器 Cookie** — 通过 `browser-cookie3` 自动从 Chrome、Firefox、Edge、Brave 提取
3. **手动登录** — `zhihu login --z-c0 <z_c0_cookie值>`

### 如何获取 z_c0 Cookie

1. 打开 [zhihu.com](https://www.zhihu.com) 并登录
2. 打开浏览器开发者工具（F12）→ Application → Cookies
3. 复制 `z_c0` Cookie 的值
4. 执行 `zhihu login --z-c0 <值>`

需要认证的命令会自动校验凭证。过期 Cookie 会自动清除；如果只是临时网络异常，不会误清本地凭证（会以 best-effort 继续尝试）。
`zhihu status` 认证成功时退出码为 `0`，否则为 `1`。

大部分命令无需登录。Feed、收藏夹、关注列表和互动操作需要登录。写操作（点赞、赞同、关注、取消关注）需要有效的登录凭证。

## 结构化输出

所有 `--json` / `--yaml` 输出使用统一的信封格式。主要命令会返回命令层规范化后的 payload：

- `zhihu question` → `data.question`、`data.answers`
- `zhihu answer` → `data.answer`、`data.comments`
- `zhihu article` → `data.article`、`data.comments`
- `zhihu hot` → `data[]`
- `zhihu search` → 规范化后的结果列表
- `zhihu vote` / `zhihu follow` / `zhihu unfollow` → 标准化写操作结果

结构化错误码区分成了 `not_authenticated`、`invalid_input`、`network_error`、`upstream_error`、`not_found`、`rate_limited`、`api_error`、`internal_error` 等类型，便于脚本或 agent 做恢复和分支处理。

## 作为 AI Agent Skill 使用

zhihu-cli 自带 [`SKILL.md`](./SKILL.md)，让 AI Agent 能自动学习并使用本工具。

如果 AI Agent 需要机器可读输出，默认优先 `--yaml`：

- `--yaml` 通常比格式化 JSON 更省 token
- 对 agent 来说仍然容易解析
- 只有在要配合 `jq` 或下游必须是 JSON 时，再使用 `--json`
- stdout 不是 TTY 时会默认自动输出 YAML
示例：

```bash
zhihu status --yaml
zhihu question 1908480548659225029 --yaml
zhihu hot -n 5 --yaml
zhihu search "python" -n 5 --yaml
```

另外，agent 应尽量配合 `-n` 缩小结果集，避免把不必要的数据带进上下文。

如果 agent 要帮用户总结一个问题，应该优先拉回答。回答通常就是问题核心内容的第一手来源，最适合做 summary；只有在没有回答或回答明显不足时，再退回到评论。

## 常见问题

- `需要登录` / `权限不足` / `not_authenticated` — 执行 `zhihu login --z-c0 <cookie>` 或确保浏览器已登录 zhihu.com
- `NetworkError` — 检查网络连接
- Chrome 钥匙串弹窗 — 输入 macOS 登录密码即可授权读取 Cookie；`zhihu login` 支持从 Chrome、Edge、Firefox、Brave 自动获取 Cookie

## License

Apache-2.0
