xfetch
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesexfetch
xfetch
Fetch public data from X (Twitter) — profiles, tweets, threads, search, followers — using the user's own login cookies instead of the paid developer API. This skill ships a single self-contained CLI, , that calls X's GraphQL API directly and emits structured data an agent can parse.
scripts/xfetch.pyHow it stays working (the architecture that matters): the hard part of X scraping is that X constantly changes its site — it rotates GraphQL query IDs every few weeks, migrates endpoints between GET and POST, and reshapes response JSON. This CLI splits those concerns so a break in one place doesn't take everything down:
- It reuses the current query IDs and feature flags shipped by the twikit package (kept fresh with ) — so you don't hand-maintain the fastest-rotating values.
pip install -U twikit - It does its own HTTP requests and JSON parsing, which sidesteps the two things most likely to be broken in twikit at any moment: (1) its homepage-scraped anti-bot transaction ID — this CLI sends a harmless placeholder , which X accepts for read endpoints; and (2) its response-model layer — this CLI parses the raw JSON itself. It also auto-falls-back GET↔POST on a 404, so an endpoint X migrates keeps working.
x-client-transaction-id
Net: if a command suddenly errors for everyone, the first fix is still (refreshes query IDs). If that doesn't help, X changed a response shape — check the parser in .
pip install -U twikitscripts/xfetch.py使用用户自己的登录Cookie而非付费开发者API,从X(Twitter)获取公开数据——包括资料、推文、推文线程、搜索结果、粉丝列表等。本技能提供一个独立的CLI工具,它直接调用X的GraphQL API,并输出可供Agent解析的结构化数据。
scripts/xfetch.py持续可用的核心设计(关键架构): X抓取的难点在于X的网站一直在变化——每隔几周就会轮换GraphQL查询ID,在GET和POST之间切换端点,还会调整响应JSON的结构。这个CLI将这些关注点分离,因此某一出问题不会导致整个工具失效:
- 它复用twikit包提供的当前查询ID和功能标志(通过保持更新)——这样你就不用手动维护那些更新最频繁的值。
pip install -U twikit - 它自行处理HTTP请求和JSON解析,这避开了twikit随时可能出问题的两个地方:(1) 它从首页抓取的反机器人事务ID——这个CLI发送一个无害的占位符,X的读取端点会接受这个值;(2) 它的响应模型层——这个CLI自己解析原始JSON。它还会在遇到404时自动在GET和POST之间切换,因此X迁移的端点仍能正常工作。
x-client-transaction-id
总而言之,如果某个命令突然对所有人都报错,第一个修复方法仍然是(更新查询ID)。如果这没用,那就是X修改了响应结构——检查中的解析器。
pip install -U twikitscripts/xfetch.pyThe agent-native contract
Agent原生约定
scripts/xfetch.py- carries the data payload only (JSON by default). Redirect or pipe it — nothing else is written there.
stdout - carries human status (
stderr) and errors. Read it to diagnose; ignore it when parsing.✓ Saved… - exit code is the truth signal: = success,
0= error,1= not authenticated,2= rate limited (stderr carries3),rate_limit_reset=<epoch>= usage error (bad flag or argument — fix the command, don't re-auth). Branch on the exit code, not on stderr text.64
scripts/xfetch.py- 仅承载数据 payload(默认是JSON)。可以重定向或通过管道传输它——那里不会输出其他内容。
stdout - 承载人类可读的状态(
stderr)和错误。用它来诊断问题;解析数据时忽略它。✓ 已保存… - 退出码是可信信号:= 成功,
0= 错误,1= 未认证,2= 速率限制(stderr中会包含3),rate_limit_reset=<epoch>= 使用错误(标志或参数错误——修正命令即可,不要重新认证)。请根据退出码分支处理,不要依据stderr文本判断。64
Setup (once per environment)
安装设置(每个环境只需一次)
-
Confirm Python and install twikit (a virtualenv is cleanest so you don't touch system packages):bash
python3 -m pip install -r scripts/requirements.txt # installs twikit>=2.3.3 -
Verify the CLI loads:bash
python3 scripts/xfetch.py --version # -> xfetch-skill 0.3
Invoke every command as using this skill's own copy of the script.
python3 scripts/xfetch.py <command> …-
确认Python环境并安装twikit(使用虚拟环境最干净,不会影响系统包):bash
python3 -m pip install -r scripts/requirements.txt # installs twikit>=2.3.3 -
验证CLI可正常加载:bash
python3 scripts/xfetch.py --version # -> xfetch-skill 0.3
所有命令都通过的方式调用,使用本技能自带的脚本副本。
python3 scripts/xfetch.py <命令> …Authenticate first — this is the #1 failure mode
首先完成认证——这是最常见的失败原因
Every data command needs the user's X cookies ( + ). Without them the command prints to stderr and exits 2. Auth is delegated: the human sets it up once, the CLI saves a session to , and you reuse it — you don't own the credential lifecycle, you just check it's present.
auth_tokenct0Not authenticated.~/.config/xfetch/cookies.jsonAlways run this first and branch on the exit code:
bash
python3 scripts/xfetch.py auth checkIf it isn't authenticated, get the human to provide credentials, in order of preference:
-
Extract from a logged-in browser (most convenient — reads the x.com cookies straight from the browser's store, no copy/paste):bash
python3 scripts/xfetch.py auth extract --browser chrome # supported: chrome, chromium, firefox, safari, edge, brave, arc, opera, vivaldi, librewolfRequires(inbrowser_cookie3). On macOS this may prompt for Keychain access — that's the OS handing over the cookie-decryption key, which is expected.requirements.txt -
Import a cookies file (best for browsers without a reader — e.g. ChatGPT Atlas, Orion, or any Chromium fork): export cookies with a "Get cookies.txt" browser extension (Netscapeor JSON both work), then point the CLI at the file — it extracts
cookies.txt+auth_tokenfor you:ct0bashpython3 scripts/xfetch.py auth import --file ~/Downloads/x.com_cookies.txt -
Paste cookie tokens (works for any browser): open DevTools → Application → Cookies →, copy the
https://x.comandauth_tokenvalues, then:ct0bashpython3 scripts/xfetch.py auth set --auth-token <token> --ct0 <token> -
Environment variables (good for CI / one-off, saves nothing to disk):bash
XFETCH_AUTH_TOKEN=<token> XFETCH_CT0=<token> python3 scripts/xfetch.py user @handle -
Username/password login (twikit performs a real login; may trip a captcha or 2FA — passfor TOTP-based 2FA):
--totpbashpython3 scripts/xfetch.py auth login --username <user> --password <pass>
Never invent or guess cookie values. Prefer /env over so no password passes through the command line. If auth is missing and you can't obtain it, stop and ask the human — you cannot proceed without it. These read a real account, so its login is a shared, rate-limited resource: don't hammer it.
auth setlogin所有数据命令都需要用户的X Cookie( + )。没有它们的话,命令会向stderr打印并以退出码2退出。认证是委托式的:用户只需设置一次,CLI会将会话保存到,之后你就可以复用它——你不需要管理凭证的生命周期,只需要检查它是否存在。
auth_tokenct0Not authenticated.~/.config/xfetch/cookies.json务必先运行这个命令并根据退出码判断:
bash
python3 scripts/xfetch.py auth check如果未认证,让用户提供凭证,优先选择以下方式:
-
从已登录的浏览器中提取(最方便——直接从浏览器存储中读取x.com的Cookie,无需复制粘贴):bash
python3 scripts/xfetch.py auth extract --browser chrome # supported: chrome, chromium, firefox, safari, edge, brave, arc, opera, vivaldi, librewolf需要(已包含在browser_cookie3中)。在macOS上这可能会请求钥匙串访问权限——这是系统在提供Cookie解密密钥,属于正常现象。requirements.txt -
导入Cookie文件(最适合没有读取器的浏览器——例如ChatGPT Atlas、Orion,或任何Chromium衍生浏览器):使用“Get cookies.txt”浏览器扩展导出Cookie(Netscape格式的或JSON都可以),然后让CLI指向该文件——它会自动为你提取
cookies.txt+auth_token:ct0bashpython3 scripts/xfetch.py auth import --file ~/Downloads/x.com_cookies.txt -
粘贴Cookie令牌(适用于所有浏览器):打开开发者工具 → 应用 → Cookie →,复制
https://x.com和auth_token的值,然后运行:ct0bashpython3 scripts/xfetch.py auth set --auth-token <token> --ct0 <token> -
环境变量(适合CI/一次性使用,不会保存到磁盘):bash
XFETCH_AUTH_TOKEN=<token> XFETCH_CT0=<token> python3 scripts/xfetch.py user @handle -
用户名/密码登录(twikit会执行真实登录;可能会触发验证码或2FA——如果是TOTP类型的2FA请传入):
--totpbashpython3 scripts/xfetch.py auth login --username <user> --password <pass>
绝不要编造或猜测Cookie值。优先使用或环境变量而非,这样密码不会经过命令行。如果缺少认证信息且你无法获取,请停止并询问用户——没有它你无法继续操作。这些操作会读取真实账号,因此该账号的登录是共享的、有速率限制的资源:不要频繁发起请求。
auth setloginChoose the output format for the consumer
为使用方选择合适的输出格式
The default is pretty-printed for a human reading one result. For anything you or a pipeline will parse, pick deliberately with :
json--format| Format | Flag | Use when |
|---|---|---|
| JSON (pretty) | (default) | Inspecting a single object or a small result |
| JSONL | | Large / multi-page results — one record per line, appendable, stream-friendly |
| CSV | | Spreadsheets or quick tabular analysis (nested fields are JSON-encoded in-cell) |
| SQLite | | Building a queryable dataset; rows go to a |
Add for compact single-line JSON. Save to a file by redirecting stdout, e.g. .
--plain… --format jsonl > tweets.jsonl默认的格式是美化打印的,适合人类查看单个结果。对于你或流水线要解析的内容,请使用主动选择:
json--format| 格式 | 标志 | 适用场景 |
|---|---|---|
| JSON(美化) | (默认) | 检查单个对象或少量结果时 |
| JSONL | | 大量/多页结果——每行一条记录,可追加,适合流式处理 |
| CSV | | 电子表格或快速表格分析(嵌套字段会以JSON编码的形式放在单元格中) |
| SQLite | | 构建可查询的数据集;行数据会存入 |
添加可获得紧凑的单行JSON。通过重定向stdout保存到文件,例如。
--plain… --format jsonl > tweets.jsonlCommands
命令
bash
undefinedbash
undefinedProfile (by @handle or numeric id)
Profile (by @handle or numeric id)
python3 scripts/xfetch.py user @elonmusk
python3 scripts/xfetch.py user @elonmusk
A user's tweets (--replies for replies, --media for media-only)
A user's tweets (--replies for replies, --media for media-only)
python3 scripts/xfetch.py tweets @elonmusk -n 50
python3 scripts/xfetch.py tweets @elonmusk --replies --all --format jsonl > timeline.jsonl
python3 scripts/xfetch.py tweets @elonmusk -n 50
python3 scripts/xfetch.py tweets @elonmusk --replies --all --format jsonl > timeline.jsonl
A user's liked tweets
A user's liked tweets
python3 scripts/xfetch.py likes @handle -n 40
python3 scripts/xfetch.py likes @handle -n 40
Single tweet, and a tweet with its replies (thread)
Single tweet, and a tweet with its replies (thread)
python3 scripts/xfetch.py tweet https://x.com/user/status/1234567890
python3 scripts/xfetch.py thread 1234567890
python3 scripts/xfetch.py tweet https://x.com/user/status/1234567890
python3 scripts/xfetch.py thread 1234567890
Search (--type top|latest|media)
Search (--type top|latest|media)
python3 scripts/xfetch.py search "AI agents" -n 100 --type latest
python3 scripts/xfetch.py search "from:openai since:2024-01-01" --all --format csv > openai.csv
python3 scripts/xfetch.py search "AI agents" -n 100 --type latest
python3 scripts/xfetch.py search "from:openai since:2024-01-01" --all --format csv > openai.csv
Followers / following, paginated into a SQLite dataset
Followers / following, paginated into a SQLite dataset
python3 scripts/xfetch.py followers @handle --all --format sqlite --db network.db
python3 scripts/xfetch.py following @handle -n 100
python3 scripts/xfetch.py followers @handle --all --format sqlite --db network.db
python3 scripts/xfetch.py following @handle -n 100
Your own timelines (uses the logged-in account)
Your own timelines (uses the logged-in account)
python3 scripts/xfetch.py home # "For You"
python3 scripts/xfetch.py home --following # chronological
python3 scripts/xfetch.py bookmarks -n 50
`search` supports X's advanced operators (`from:`, `to:`, `since:`, `until:`, `filter:`, `min_faves:`, etc.) — pass them inside the quoted query. For the full flag reference and the exact fields each command returns, read `references/commands.md`.
DMs, lists, and trends are not exposed as commands (to keep this CLI small), but twikit supports them (`get_dm_history`, `get_list_tweets`, `get_trends`) — add a command following the existing pattern in `scripts/xfetch.py` if the user needs one.python3 scripts/xfetch.py home # "For You"
python3 scripts/xfetch.py home --following # chronological
python3 scripts/xfetch.py bookmarks -n 50
`search`支持X的高级运算符(`from:`、`to:`、`since:`、`until:`、`filter:`、`min_faves:`等)——将它们放在带引号的查询语句中即可。完整的参数参考和每个命令返回的具体字段,请查看`references/commands.md`。
私信、列表和趋势没有作为命令暴露(为了保持CLI轻量),但twikit支持这些功能(`get_dm_history`、`get_list_tweets`、`get_trends`)——如果用户需要,可以按照`scripts/xfetch.py`中现有的模式添加命令。Pagination and rate limits
分页与速率限制
Listing commands (, , , , , , ) share these flags — single page by default, opt into more:
tweetssearchfollowersfollowinglikeshomebookmarksbash
-n 40 # results per page
--all # every page until exhausted
--max-pages 10 # cap the pages
--cursor <c> # start from a specific pagination cursor
--delay 1.5 # seconds between pages (default 1.0 — keep it >0 for --all)When more pages remain — or a pull is interrupted or rate limited mid-way — the CLI prints to stderr. Capture it and pass it back via to resume exactly where the pull stopped instead of refetching from the top.
next_cursor=<value>--cursorX enforces per-account rate limits (roughly a few hundred requests per 15-minute window per endpoint) and this uses the user's real account. For bulk pulls keep a real , prefer over when you only need a sample, and remember aggressive scraping can get the account throttled or flagged. Route through a proxy for heavier work with .
--delay--max-pages--all--proxy http://user:pass@host:port列表类命令(、、、、、、)共享以下参数——默认只获取单页,可选择获取更多:
tweetssearchfollowersfollowinglikeshomebookmarksbash
-n 40 # results per page
--all # every page until exhausted
--max-pages 10 # cap the pages
--cursor <c> # start from a specific pagination cursor
--delay 1.5 # seconds between pages (default 1.0 — keep it >0 for --all)当还有更多页面时——或者拉取过程被中断或遇到速率限制时——CLI会向stderr打印。捕获这个值并通过传入,就可以从上次停止的地方继续,而不用从头重新获取。
next_cursor=<value>--cursorX对每个账号都有速率限制(每个端点大概每15分钟几百次请求),而这个工具使用的是用户的真实账号。对于批量拉取,请设置合理的,如果只需要样本,优先使用而非,请记住过度抓取可能会导致账号被限流或标记。对于更大量的工作,可以通过使用代理。
--delay--max-pages--all--proxy http://user:pass@host:portWhen something fails
出现问题时
Check the exit code, then read stderr to classify:
- exit 2 / → run the auth flow above.
Not authenticated - exit 64 / usage error → the command line itself is wrong (unknown flag, bad value). Fix the invocation — do not re-run auth.
- exit 3 / rate limited → stderr carries ; wait until then, raise
rate_limit_reset=<epoch>, and resume from the--delayvalue printed on stderr.next_cursor= - exit 1 with a GraphQL / parsing error that started suddenly for everyone → X likely changed its site. Upgrade twikit () and retry.
pip install -U twikit - Timeout / network errors mid-pull → resume from the line on stderr instead of refetching from the top.
next_cursor= - Empty result → the account may be private (you only see what the logged-in account can), suspended, or the handle is wrong.
先检查退出码,再读取stderr进行分类:
- 退出码2 / → 运行上述认证流程。
Not authenticated - 退出码64 / 使用错误 → 命令行本身有问题(未知标志、值错误)。修正调用方式——不要重新运行认证。
- 退出码3 / 速率限制 → stderr中会包含;等到那个时间,调高
rate_limit_reset=<epoch>,然后从stderr上打印的--delay值处恢复。next_cursor= - 退出码1,且突然对所有人都出现GraphQL/解析错误 → 很可能是X修改了网站。升级twikit()后重试。
pip install -U twikit - 拉取过程中出现超时/网络错误 → 从stderr上的行处恢复,而不是从头重新获取。
next_cursor= - 结果为空 → 该账号可能是私密的(你只能看到登录账号可见的内容)、被暂停,或者用户名有误。
Scope and good-citizen notes
使用范围与合规注意事项
This reads public data plus whatever the logged-in account can see (its own home, bookmarks, likes). It does not post, like, follow, or modify anything — it's read-only by design. Because it uses the user's own session, the user is responsible for staying within X's Terms of Service and rate limits. Use it for legitimate purposes — research, personal archiving, monitoring accounts the user is entitled to read — not for harassment, mass surveillance, or evading a block. Session cookies live under ; clear them with .
~/.config/xfetch/auth clear本工具读取公开数据以及登录账号可见的内容(自己的首页、书签、点赞)。它不会发布、点赞、关注或修改任何内容——设计上就是只读的。由于它使用用户自己的会话,用户有责任遵守X的服务条款和速率限制。请将其用于合法目的——研究、个人归档、监控你有权读取的账号——不要用于骚扰、大规模监控或绕过封禁。会话Cookie存储在下;可以用清除它们。
~/.config/xfetch/auth clear