Skip to content
Back to search

twitter-cli

SkillWorks with Claude CodeGitHub

Use twitter-cli for ALL Twitter/X operations — reading tweets, posting, replying, quoting, liking, retweeting, following, searching, user lookups. Invoke whenever user requests any Twitter interaction.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/public-clis--twitter-cli/badge.svg)](/listings/public-clis--twitter-cli)

HTML

<a href="/listings/public-clis--twitter-cli"><img src="/api/listings/public-clis--twitter-cli/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

# Recommended: uv tool (fast, isolated)
uv tool install twitter-cli

# Alternative: pipx
pipx install twitter-cli

Upgrade to the latest version:

uv tool upgrade twitter-cli
# Or: pipx upgrade twitter-cli

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

Install from source:

git clone git@github.com:jackwener/twitter-cli.git
cd twitter-cli
uv sync

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 347 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. ---
  2. name: twitter-cli
  3. description: Use twitter-cli for ALL Twitter/X operations — reading tweets, posting, replying, quoting, liking, retweeting, following, searching, user lookups. Invoke whenever user requests any Twitter interaction.
  4. author: jackwener
  5. version: "0.8.0"
  6. tags:
  7. - twitter
  8. - x
  9. - social-media
  10. - terminal
  11. - cli
  12. ---
  13. # twitter-cli — Twitter/X CLI Tool
  14. **Binary:** `twitter`
  15. **Credentials:** browser cookies (auto-extracted) or env vars
  16. ## Setup
  17. ```bash
  18. # Install (requires Python 3.8+)
  19. uv tool install twitter-cli
  20. # Or: pipx install twitter-cli
  21. # Upgrade to latest (recommended to avoid API errors)
  22. uv tool upgrade twitter-cli
  23. # Or: pipx upgrade twitter-cli
  24. ```
  25. ## Authentication
  26. **IMPORTANT FOR AGENTS**: Before executing ANY twitter-cli command, you MUST first check if credentials exist. If not, you MUST proactively guide the user through the authentication process. Do NOT assume credentials are configured.
  27. **CRITICAL**: Write operations (posting tweets, replying, quoting) REQUIRE full browser cookies. Only providing `auth_token` + `ct0` via env vars may result in **226 error** ("looks like automated behavior"). For best results, use browser cookie extraction.
  28. ### Step 0: Check if already authenticated
  29. ```bash
  30. twitter status --yaml >/dev/null && echo "AUTH_OK" || echo "AUTH_NEEDED"
  31. ```
  32. If `AUTH_OK`, skip to [Command Reference](#command-reference).
  33. If `AUTH_NEEDED`, proceed to guide the user:
  34. ### Step 1: Guide user to authenticate
  35. **Method A: Browser cookie extraction (recommended)**
  36. Ensure user is logged into x.com in one of: Arc, Chrome, Edge, Firefox, Brave. twitter-cli auto-extracts cookies.
  37. All Chrome profiles are scanned automatically. To specify a profile: `TWITTER_CHROME_PROFILE="Profile 2" twitter feed`.
  38. To prioritize a specific browser: `TWITTER_BROWSER=chrome twitter feed` (supported: arc, chrome, edge, firefox, brave).
  39. ```bash
  40. twitter whoami
  41. ```
  42. **Method B: Environment variables**
  43. ```bash
  44. export TWITTER_AUTH_TOKEN="<auth_token from browser>"
  45. export TWITTER_CT0="<ct0 from browser>"
  46. twitter whoami
  47. ```
  48. **Method C: Full cookie string (for cloud/remote agents)**
  49. Tell the user:
  50. > 我需要你的 Twitter 登录凭证。请按以下步骤获取:
  51. >
  52. > 1. 用 Chrome/Edge/Firefox 打开 https://x.com(确保已登录)
  53. > 2. 按 `F12` 打开开发者工具 → **Network** 标签
  54. > 3. 在页面上刷新,点击任意 `x.com` 请求
  55. > 4. 找到 **Request Headers** → **Cookie:** 这一行,右键 → 复制值
  56. > 5. 把完整 Cookie 字符串发给我
  57. >
  58. > ⚠️ Cookie 包含登录信息,请不要分享给其他人。
  59. Then extract and set env vars:
  60. ```bash
  61. FULL_COOKIE="<user's cookie string>"
  62. export TWITTER_AUTH_TOKEN=$(echo "$FULL_COOKIE" | grep -oE 'auth_token=[a-f0-9]+' | cut -d= -f2)
  63. export TWITTER_CT0=$(echo "$FULL_COOKIE" | grep -oE 'ct0=[a-f0-9]+' | cut -d= -f2)
  64. twitter whoami
  65. ```
  66. ### Step 2: Handle common auth issues
  67. | Symptom | Agent action |
  68. |---------|-------------|
  69. | `No Twitter cookies found` | Guide user to login to x.com in browser, or set env vars |
  70. | Read works, write returns 226 | Full cookies missing — use browser cookie extraction instead of env vars |
  71. | `Cookie expired (401/403)` | Ask user to re-login to x.com and retry |
  72. | User changed password | All old cookies invalidated — re-extract |
  73. ## Output Format
  74. ### Default: Rich table (human-readable)
  75. ```bash
  76. twitter feed # Pretty table output
  77. ```
  78. ### YAML / JSON: structured output
  79. Non-TTY stdout defaults to YAML automatically. Use `OUTPUT=yaml|json|rich|auto` to override.
  80. ```bash
  81. twitter feed --yaml
  82. twitter feed --json | jq '.[0].text'
  83. ```
  84. All machine-readable output uses the envelope documented in [SCHEMA.md](./SCHEMA.md).
  85. Tweet and user payloads now live under `.data`.
  86. ### Full text: `--full-text` flag (rich tables only)
  87. Use `--full-text` when the user wants complete post bodies in terminal tables.
  88. It affects rich table list views such as `feed`, `bookmarks`, `search`, `user-posts`, `likes`, `list`, and reply tables in `tweet`.
  89. It does **not** change `--json`, `--yaml`, or `-c` compact output.
  90. ```bash
  91. twitter feed --full-text
  92. twitter search "AI agent" --full-text
  93. twitter user-posts elonmusk --max 20 --full-text
  94. twitter tweet 1234567890 --full-text
  95. ```
  96. ### Compact: `-c` flag (minimal tokens for LLM)
  97. ```bash
  98. twitter -c feed --max 10 # Minimal fields, great for LLM context
  99. twitter -c search "AI" --max 20 # ~80% fewer tokens than --json
  100. ```
  101. **Compact fields (per tweet):** `id`, `author` (@handle), `text` (truncated 140 chars), `likes`, `rts`, `time` (short format)
  102. ## Command Reference
  103. ### Read Operations
  104. ```bash
  105. twitter status # Quick auth check
  106. twitter status --yaml # Structured auth status
  107. twitter whoami # Current authenticated user
  108. twitter whoami --yaml # YAML output
  109. twitter whoami --json # JSON output
  110. twitter user elonmusk # User profile
  111. twitter user elonmusk --json # JSON output
  112. twitter feed # Home timeline (For You)
  113. twitter feed -t following # Following timeline
  114. twitter feed --max 50 # Limit count
  115. twitter feed --full-text # Show full post body in table
  116. twitter feed --filter # Enable ranking filter
  117. twitter feed --yaml > tweets.yaml # Export as YAML
  118. twitter feed --input tweets.json # Read from local JSON file
  119. twitter bookmarks # Bookmarked tweets
  120. twitter bookmarks --full-text # Full text in bookmarks table
  121. twitter bookmarks --max 30 --yaml
  122. twitter search "keyword" # Search tweets
  123. twitter search "AI agent" -t Latest --max 50
  124. twitter search "AI agent" --full-text # Full text in search results
  125. twitter search "topic" -o results.json # Save to file
  126. twitter tweet 1234567890 # Tweet detail + replies
  127. twitter tweet 1234567890 --full-text # Full text in reply table
  128. twitter tweet https://x.com/user/status/12345 # Accepts URL
  129. twitter show 2 # Open tweet #2 from last feed/search list
  130. twitter show 2 --full-text # Full text in reply table
  131. twitter show 2 --json # Structured output
  132. twitter list 1539453138322673664 # List timeline
  133. twitter list 1539453138322673664 --cursor "<next-cursor>"
  134. twitter list 1539453138322673664 --full-text
  135. twitter user-posts elonmusk --max 20 # User's tweets
  136. twitter user-posts elonmusk --full-text
  137. twitter likes elonmusk --max 30 # User's likes (own only, see note)
  138. twitter likes elonmusk --full-text
  139. twitter followers elonmusk --max 50 # Followers
  140. twitter following elonmusk --max 50 # Following
  141. ```
  142. ### Write Operations
  143. ```bash
  144. twitter post "Hello from twitter-cli!" # Post tweet
  145. twitter post "Hello!" --image photo.jpg # Post with image
  146. twitter post "Gallery" -i a.png -i b.jpg # Up to 4 images
  147. twitter reply 1234567890 "Great tweet!" # Reply (standalone)
  148. twitter reply 1234567890 "Nice!" -i pic.png # Reply with image
  149. twitter post "reply text" --reply-to 1234567890 # Reply (via post)
  150. twitter quote 1234567890 "Interesting take" # Quote-tweet
  151. twitter quote 1234567890 "Look" -i chart.png # Quote with image
  152. twitter delete 1234567890 # Delete tweet
  153. twitter like 1234567890 # Like
  154. twitter unlike 1234567890 # Unlike
  155. twitter retweet 1234567890 # Retweet
  156. twitter unretweet 1234567890 # Unretweet
  157. twitter bookmark 1234567890 # Bookmark
  158. twitter unbookmark 1234567890 # Unbookmark
  159. twitter follow elonmusk # Follow user
  160. twitter unfollow elonmusk # Unfollow user
  161. ```
  162. **Image upload notes:**
  163. - Supported formats: JPEG, PNG, GIF, WebP
  164. - Max file size: 5 MB per image
  165. - Max 4 images per tweet
  166. - Use `--image` / `-i` (repeatable)
  167. ## Agent Workflows
  168. ### Post and verify
  169. ```bash
  170. twitter post "My tweet text" 2>/dev/null
  171. # Output includes tweet URL: 🔗 https://x.com/i/status/<id>
  172. ```
  173. ### Post with images
  174. ```bash
  175. # Single image
  176. twitter post "Check this out!" --image /path/to/photo.jpg
  177. # Multiple images
  178. twitter post "Photo gallery" -i img1.png -i img2.jpg -i img3.webp
  179. ```
  180. ### Reply to someone's latest tweet
  181. ```bash
  182. TWEET_ID=$(twitter user-posts targetuser --max 1 --json | jq -r '.data[0].id')
  183. twitter reply "$TWEET_ID" "Nice post!"
  184. ```
  185. ### Create a thread
  186. ```bash
  187. # Post first tweet, capture output for tweet ID
  188. twitter post "Thread 1/3: First point"
  189. # Note the tweet ID from output, then:
  190. twitter reply <first_tweet_id> "2/3: Second point"
  191. twitter reply <second_tweet_id> "3/3: Final point"
  192. ```
  193. ### Quote-tweet with commentary
  194. ```bash
  195. TWEET_ID=$(twitter search "interesting topic" --max 1 --json | jq -r '.data[0].id')
  196. twitter quote "$TWEET_ID" "This is a great insight!"
  197. ```
  198. ### Like all search results
  199. ```bash
  200. twitter search "interesting topic" --max 5 --json | jq -r '.data[].id' | while read id; do
  201. twitter like "$id"
  202. done
  203. ```
  204. ### Get user info then follow
  205. ```bash
  206. twitter user targethandle --json | jq '.data | {username, followers, bio}'
  207. twitter follow targethandle
  208. ```
  209. ### Find most popular tweets from a user
  210. ```bash
  211. twitter user-posts elonmusk --max 20 --json | jq '.data | sort_by(.metrics.likes) | reverse | .[:3] | .[] | {id, text: .text[:80], likes: .metrics.likes}'
  212. ```
  213. ### Check follower relationship
  214. ```bash
  215. MY_NAME=$(twitter whoami --json | jq -r '.data.user.username')
  216. twitter followers "$MY_NAME" --max 200 --json | jq -r '.data[].username' | grep -q "targetuser" && echo "Yes" || echo "No"
  217. ```
  218. ### Daily reading workflow
  219. ```bash
  220. # Compact mode for token-efficient LLM context
  221. twitter -c feed -t following --max 30
  222. twitter -c bookmarks --max 20
  223. # Rich table with complete post bodies
  224. twitter feed -t following --max 20 --full-text
  225. twitter search "AI agent" --max 20 --full-text
  226. # Full JSON for analysis
  227. twitter feed -t following --max 30 -o following.json
  228. twitter bookmarks --max 20 -o bookmarks.json
  229. ```
  230. ### Search with jq filtering
  231. ```bash
  232. # Tweets with > 100 likes
  233. twitter search "AI safety" --max 20 --json | jq '[.data[] | select(.metrics.likes > 100)]'
  234. # Extract just text and author
  235. twitter search "rust lang" --max 10 --json | jq '.data[] | {author: .author.screenName, text: .text[:100]}'
  236. # Most engaged tweets
  237. twitter search "topic" --max 20 --json | jq '.data | sort_by(.metrics.likes) | reverse | .[:5] | .[].id'
  238. ```
  239. ## Ranking Filter
  240. Filtering is opt-in. Enable with `--filter`:
  241. ```bash
  242. twitter feed --filter
  243. twitter bookmarks --filter
  244. ```
  245. ## Error Reference
  246. | Error | Cause | Fix |
  247. |-------|-------|-----|
  248. | `No Twitter cookies found` | Not authenticated | Login to x.com in browser, or set env vars |
  249. | HTTP 226 | Automated detection | Use browser cookie extraction (not env vars) |
  250. | HTTP 401/403 | Cookie expired | Re-login to x.com and retry |
  251. | HTTP 404 | QueryId rotation | Retry (auto-fallback built in) |
  252. | HTTP 429 | Rate limited | Wait 15+ minutes, then retry |
  253. | Error 187 | Duplicate tweet | Change text content |
  254. | Error 186 | Tweet too long | Keep under 280 chars |
  255. ## Limitations
  256. - **Images only** — video/GIF animation upload not yet supported (image upload supports JPEG/PNG/GIF/WebP)
  257. - **No DMs** — no direct messaging
  258. - **No notifications** — can't read notifications
  259. - **No polls** — can't create polls
  260. - **Single account** — one set of credentials at a time
  261. - **Likes are private** — Twitter/X made all likes private since June 2024. `twitter likes` only works for your own account
  262. ## Safety Notes
  263. - Write operations have built-in random delays (1.5–4s) to avoid rate limits.
  264. - TLS fingerprint and User-Agent are automatically matched to the Chrome version used.
  265. - Do not ask users to share raw cookie values in chat logs.
  266. - Prefer local browser cookie extraction over manual secret copy/paste.
  267. - Agent should treat cookie values as secrets (do not echo to stdout unnecessarily).
README.md · README · 624 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # twitter-cli
  2. [![CI](https://github.com/jackwener/twitter-cli/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/jackwener/twitter-cli/actions/workflows/ci.yml)
  3. [![PyPI version](https://badge.fury.io/py/twitter-cli.svg)](https://pypi.org/project/twitter-cli/)
  4. [![Python](https://img.shields.io/badge/python-%3E%3D3.10-blue.svg)](https://pypi.org/project/twitter-cli/)
  5. A terminal-first CLI for Twitter/X: read timelines, bookmarks, and user profiles without API keys.
  6. ## More Tools
  7. - [xiaohongshu-cli](https://github.com/jackwener/xiaohongshu-cli) — Xiaohongshu (小红书) CLI for notes and account workflows
  8. - [bilibili-cli](https://github.com/jackwener/bilibili-cli) — Bilibili CLI for videos, users, search, and feeds
  9. - [discord-cli](https://github.com/jackwener/discord-cli) — Discord CLI for local-first sync, search, and export
  10. - [tg-cli](https://github.com/jackwener/tg-cli) — Telegram CLI for local-first sync, search, and export
  11. [English](#english) | [中文](#中文)
  12. ## English
  13. ### Features
  14. **Read:**
  15. - Timeline: fetch `for-you` and `following` feeds
  16. - Bookmarks: list saved tweets from your account
  17. - Search: find tweets by keyword with Top/Latest/Photos/Videos tabs
  18. - Tweet detail: view a tweet and its replies; use `show <N>` to open tweet #N from the last list output
  19. - Article: fetch a Twitter Article and export it as Markdown
  20. - List timeline: fetch tweets from a Twitter List
  21. - User lookup: fetch user profile, tweets, likes, followers, and following
  22. - `--full-text`: disable tweet text truncation in rich table output
  23. - Structured output: export any data as YAML or JSON for scripting and AI agent integration
  24. - Optional scoring filter: rank tweets by engagement weights
  25. - Structured output contract: [SCHEMA.md](./SCHEMA.md)
  26. > **AI Agent Tip:** Prefer `--yaml` for structured output unless a strict JSON parser is required. Non-TTY stdout defaults to YAML automatically. Use `--max` to limit results.
  27. **Write:**
  28. - Post: create new tweets and replies, with optional image attachments (up to 4)
  29. - Quote: quote-tweet with optional images
  30. - Delete: remove your own tweets
  31. - Like / Unlike: manage tweet likes
  32. - Retweet / Unretweet: manage retweets
  33. - Bookmark: bookmark/unbookmark (`favorite/unfavorite` kept as compatibility aliases)
  34. - Write commands also support explicit `--json` / `--yaml` output now
  35. **Auth & Anti-Detection:**
  36. - Cookie auth: use browser cookies or environment variables
  37. - Full cookie forwarding: extracts ALL browser cookies for richer browser context
  38. - TLS fingerprint impersonation: `curl_cffi` with dynamic Chrome version matching
  39. - `x-client-transaction-id` header generation
  40. - Request timing jitter to avoid pattern detection
  41. - Write operation delays (1.5–4s random) to mitigate rate limits
  42. - Proxy support via `TWITTER_PROXY` environment variable
  43. ### Installation
  44. ```bash
  45. # Recommended: uv tool (fast, isolated)
  46. uv tool install twitter-cli
  47. # Alternative: pipx
  48. pipx install twitter-cli
  49. ```
  50. Upgrade to the latest version:
  51. ```bash
  52. uv tool upgrade twitter-cli
  53. # Or: pipx upgrade twitter-cli
  54. ```
  55. > **Tip:** Upgrade regularly to avoid unexpected errors from outdated API handling.
  56. Install from source:
  57. ```bash
  58. git clone git@github.com:jackwener/twitter-cli.git
  59. cd twitter-cli
  60. uv sync
  61. ```
  62. ### Quick Start
  63. ```bash
  64. # Fetch home timeline (For You)
  65. twitter feed
  66. # Fetch Following timeline
  67. twitter feed -t following
  68. # Enable ranking filter explicitly
  69. twitter feed --filter
  70. ```
  71. ### Usage
  72. ```bash
  73. # Feed
  74. twitter feed --max 50
  75. twitter feed --cursor "<next-cursor-from-previous-response>"
  76. twitter feed --full-text
  77. twitter feed --output tweets.json
  78. twitter feed --input tweets.json
  79. twitter feed --json # Structured stdout for scripts/agents
  80. # Bookmarks
  81. twitter bookmarks
  82. twitter bookmarks --full-text
  83. twitter bookmarks --max 30 --yaml
  84. # Search
  85. twitter search "Claude Code"
  86. twitter search "AI agent" -t Latest --max 50
  87. twitter search "AI agent" --full-text
  88. twitter search "机器学习" --yaml
  89. twitter search "python" --from elonmusk --lang en --since 2026-01-01
  90. twitter search --from bbc --exclude retweets --has links
  91. twitter search "topic" -o results.json # Save to file
  92. twitter search "trending" --filter # Apply ranking filter
  93. # Tweet detail (view tweet + replies)
  94. twitter tweet 1234567890
  95. twitter tweet 1234567890 --full-text
  96. twitter tweet https://x.com/user/status/1234567890
  97. # Open tweet by index from last list output
  98. twitter show 2 # Open tweet #2 from last feed/search
  99. twitter show 2 --full-text # Full text in reply table
  100. twitter show 2 --json # Structured output
  101. # Twitter Article
  102. twitter article 1234567890
  103. twitter article https://x.com/user/article/1234567890 --json
  104. twitter article 1234567890 --markdown
  105. twitter article 1234567890 --output article.md
  106. # List timeline
  107. twitter list 1539453138322673664
  108. twitter list 1539453138322673664 --cursor "<next-cursor-from-previous-response>"
  109. twitter list 1539453138322673664 --full-text
  110. # User
  111. twitter user elonmusk
  112. twitter user-posts elonmusk --max 20
  113. twitter user-posts elonmusk --full-text
  114. twitter user-posts elonmusk -o tweets.json
  115. twitter likes elonmusk --max 30 # ⚠️ own likes only (private since Jun 2024)
  116. twitter likes elonmusk --full-text
  117. twitter likes elonmusk -o likes.json
  118. twitter followers elonmusk --max 50
  119. twitter following elonmusk --max 50
  120. # Write operations
  121. twitter post "Hello from twitter-cli!"
  122. twitter post "Hello!" --image photo.jpg # Post with image
  123. twitter post "Gallery" -i a.png -i b.jpg -i c.webp # Up to 4 images
  124. twitter post "reply text" --reply-to 1234567890
  125. twitter reply 1234567890 "Nice!" -i screenshot.png # Reply with image
  126. twitter quote 1234567890 "Look" -i chart.png # Quote with image
  127. twitter post "Hello from twitter-cli!" --json
  128. twitter delete 1234567890
  129. twitter like 1234567890
  130. twitter like 1234567890 --yaml
  131. twitter unlike 1234567890
  132. twitter retweet 1234567890
  133. twitter unretweet 1234567890
  134. twitter bookmark 1234567890
  135. twitter unbookmark 1234567890
  136. twitter follow elonmusk --json
  137. ```
  138. ### Authentication
  139. twitter-cli uses this auth priority:
  140. 1. **Environment variables**: `TWITTER_AUTH_TOKEN` + `TWITTER_CT0`
  141. 2. **Browser cookies** (recommended): auto-extract from Arc/Chrome/Edge/Firefox/Brave
  142. Browser extraction is recommended — it forwards ALL Twitter cookies (not just `auth_token` + `ct0`) and aligns request headers with your local runtime, which is closer to normal browser traffic than minimal cookie auth.
  143. **Chrome multi-profile**: All Chrome profiles are scanned automatically. To specify a profile:
  144. ```bash
  145. TWITTER_CHROME_PROFILE="Profile 2" twitter feed
  146. ```
  147. **Browser priority:** If you have multiple browsers, set `TWITTER_BROWSER` to try a specific browser first:
  148. ```bash
  149. TWITTER_BROWSER=chrome twitter feed # Supported: arc, chrome, edge, firefox, brave
  150. ```
  151. After loading cookies, the CLI performs lightweight verification. Commands that require account access fail fast on clear auth errors (`401/403`).
  152. ### Proxy Support
  153. Set `TWITTER_PROXY` to route all requests through a proxy:
  154. ```bash
  155. # HTTP proxy
  156. export TWITTER_PROXY=http://127.0.0.1:7890
  157. # SOCKS5 proxy
  158. export TWITTER_PROXY=socks5://127.0.0.1:1080
  159. ```
  160. Using a proxy can help reduce IP-based rate limiting risks.
  161. ### Configuration
  162. Create `config.yaml` in your working directory:
  163. ```yaml
  164. fetch:
  165. count: 50
  166. filter:
  167. mode: "topN" # "topN" | "score" | "all"
  168. topN: 20
  169. minScore: 50
  170. lang: []
  171. excludeRetweets: false
  172. weights:
  173. likes: 1.0
  174. retweets: 3.0
  175. replies: 2.0
  176. bookmarks: 5.0
  177. views_log: 0.5
  178. rateLimit:
  179. requestDelay: 2.5 # base delay between requests (randomized ×0.7–1.5)
  180. maxRetries: 3 # retry count on rate limit (429)
  181. retryBaseDelay: 5.0 # base delay for exponential backoff
  182. maxCount: 200 # hard cap on fetched items
  183. ```
  184. Fetch behavior:
  185. - `fetch.count` is the default item count for read commands when `--max` is omitted
  186. - Rich table output truncates long tweet text by default; use `--full-text` to show full body text in list views
  187. Filter behavior:
  188. - Default behavior: no ranking filter unless `--filter` is passed
  189. - With `--filter`: tweets are scored/sorted using `config.filter`
  190. Scoring formula:
  191. ```text
  192. score = likes_w * likes
  193. + retweets_w * retweets
  194. + replies_w * replies
  195. + bookmarks_w * bookmarks
  196. + views_log_w * log10(max(views, 1))
  197. ```
  198. Mode behavior:
  199. - `mode: "topN"` keeps the highest `topN` tweets by score
  200. - `mode: "score"` keeps tweets where `score >= minScore`
  201. - `mode: "all"` returns all tweets after sorting by score
  202. ### Best Practices (Avoiding Bans)
  203. - **Use a proxy** — set `TWITTER_PROXY` to avoid direct IP exposure
  204. - **Keep request volumes low** — use `--max 20` instead of `--max 500`
  205. - **Don't run too frequently** — each startup fetches x.com to initialize anti-detection headers
  206. - **Use browser cookie extraction** — provides full cookie fingerprint
  207. - **Avoid datacenter IPs** — residential proxies are much safer
  208. ### Output Modes
  209. - Use the default rich table for interactive reading
  210. - Use `--full-text` when reading long posts in terminal tables
  211. - Use `--yaml` or `--json` for scripts and agent pipelines
  212. - Use `-c` / `--compact` when token efficiency matters more than completeness
  213. ### Troubleshooting
  214. - `No Twitter cookies found`
  215. - Ensure you are logged in to `x.com` in a supported browser (Arc/Chrome/Edge/Firefox/Brave).
  216. - Or set `TWITTER_AUTH_TOKEN` and `TWITTER_CT0` manually.
  217. - Run with `-v` to see browser extraction diagnostics.
  218. - `Cookie expired or invalid (HTTP 401/403)`
  219. - Re-login to `x.com` and retry.
  220. - `Unable to get key for cookie decryption` (macOS Keychain)
  221. - **SSH sessions**: Keychain is locked by default over SSH. Run:
  222. ```bash
  223. security unlock-keychain ~/Library/Keychains/login.keychain-db
  224. ```
  225. - **Local terminal**: Open **Keychain Access** → search for **"\<Browser\> Safe Storage"** → **Access Control** → add your Terminal app → **Save Changes**.
  226. - Or click **"Always Allow"** when the Keychain authorization popup appears.
  227. - `Twitter API error 404`
  228. - This can happen when upstream GraphQL query IDs rotate.
  229. - Retry the command; the client attempts a live queryId fallback.
  230. - `Invalid tweet JSON file`
  231. - Regenerate input using `twitter feed --json > tweets.json`.
  232. - **Windows: no output captured by pipe/subprocess** (AI agent integration)
  233. - This is a **ConPTY** issue, not a twitter-cli bug. Windows Terminal's ConPTY pseudo-terminal can intercept pipe output from commands with network latency.
  234. - **Fix**: Use **Git Bash** as your terminal shell and set `"windowsEnableConpty": false` in your terminal settings.
  235. - If disabling ConPTY with PowerShell, emoji output may fail with `UnicodeEncodeError: 'gbk'`. Git Bash handles UTF-8 natively.
  236. - Standard `subprocess.run(capture_output=True)` and file redirection (`> file 2>&1`) work correctly regardless of ConPTY.
  237. Structured error codes commonly include `not_authenticated`, `not_found`, `invalid_input`, `rate_limited`, and `api_error`.
  238. ### Development
  239. ```bash
  240. # Install dev dependencies
  241. uv sync --extra dev
  242. # Lint + tests
  243. uv run ruff check .
  244. uv run pytest -q
  245. ```
  246. Current CI validates the project on Python 3.8, 3.10, and 3.12.
  247. ### Project Structure
  248. ```text
  249. twitter_cli/
  250. ├── __init__.py
  251. ├── cli.py
  252. ├── client.py
  253. ├── graphql.py # GraphQL query IDs, URL building, JS bundle scanning
  254. ├── parser.py # Tweet, User, Media parsing logic
  255. ├── auth.py
  256. ├── config.py
  257. ├── constants.py
  258. ├── exceptions.py
  259. ├── filter.py
  260. ├── formatter.py
  261. ├── output.py
  262. ├── serialization.py
  263. └── models.py
  264. ```
  265. ### Use as AI Agent Skill
  266. twitter-cli ships with a [`SKILL.md`](./SKILL.md) so AI agents can execute common X/Twitter workflows.
  267. #### [Skills CLI](https://github.com/vercel-labs/skills) (Recommended)
  268. ```bash
  269. npx skills add jackwener/twitter-cli
  270. ```
  271. | Flag | Description |
  272. | --- | --- |
  273. | `-g` | Install globally (user-level, shared across projects) |
  274. | `-a claude-code` | Target a specific agent |
  275. | `-y` | Non-interactive mode |
  276. #### Manual Install
  277. ```bash
  278. mkdir -p .agents/skills
  279. git clone git@github.com:jackwener/twitter-cli.git .agents/skills/twitter-cli
  280. ```
  281. #### ~~OpenClaw / ClawHub~~ (Deprecated)
  282. > ⚠️ ClawHub install method is deprecated and no longer supported. Use [Skills CLI](#skills-cli-recommended) or Manual Install above.
  283. ## 中文
  284. ### 功能概览
  285. **读取:**
  286. - 时间线读取:支持 `for-you` 和 `following`
  287. - 收藏读取:查看账号书签推文
  288. - 搜索:按关键词搜索推文,支持 Top/Latest/Photos/Videos
  289. - 推文详情:查看推文及其回复;用 `show <N>` 可直接打开上次列表里的第 N 条推文
  290. - 文章读取:获取 Twitter 长文,并导出为 Markdown
  291. - 列表时间线:获取 Twitter List 的推文
  292. - 用户查询:查看用户资料、推文、点赞、粉丝和关注
  293. - `--full-text`:在 rich table 输出里关闭推文正文截断
  294. - 结构化输出:支持 YAML 和 JSON,便于脚本处理和 AI agent 集成
  295. > **AI Agent 提示:** 需要结构化输出时优先使用 `--yaml`,除非下游必须是 JSON。stdout 不是 TTY 时默认输出 YAML。用 `--max` 控制返回数量。
  296. **写入:**
  297. - 发推:发布新推文和回复,支持附带图片(最多 4 张,支持 JPEG/PNG/GIF/WebP)
  298. - 引用推文:带评论的转发,也支持附带图片
  299. - 删除:删除自己的推文
  300. - 点赞 / 取消点赞
  301. - 转推 / 取消转推
  302. - 书签 / 取消书签:bookmark/unbookmark(保留 `favorite/unfavorite` 兼容别名)
  303. - 写操作现在也显式支持 `--json` / `--yaml`
  304. **认证与反风控:**
  305. - Cookie 认证:支持环境变量和浏览器自动提取
  306. - 完整 Cookie 转发:提取浏览器中所有 Twitter Cookie,保留更多浏览器上下文
  307. - TLS 指纹伪装:`curl_cffi` 动态匹配 Chrome 版本
  308. - `x-client-transaction-id` 请求头生成
  309. - 请求时序随机化(jitter)
  310. - 写操作随机延迟(1.5–4 秒),降低频率风控
  311. - 代理支持:`TWITTER_PROXY` 环境变量
  312. ### 安装
  313. ```bash
  314. # 推荐:uv tool
  315. uv tool install twitter-cli
  316. ```
  317. 升级到最新版本:
  318. ```bash
  319. uv tool upgrade twitter-cli
  320. # 或:pipx upgrade twitter-cli
  321. ```
  322. > **提示:** 建议定期升级,避免因版本过旧导致的 API 调用异常。
  323. ### 使用指南
  324. ```bash
  325. # 时间线
  326. twitter feed
  327. twitter feed -t following
  328. twitter feed --filter
  329. twitter feed --full-text
  330. twitter feed --cursor "<上一页返回的 nextCursor>"
  331. # 收藏
  332. twitter bookmarks
  333. twitter bookmarks --full-text
  334. # 搜索
  335. twitter search "Claude Code"
  336. twitter search "AI agent" -t Latest --max 50
  337. twitter search "AI agent" --full-text
  338. twitter search "topic" -o results.json # 保存到文件
  339. twitter search "trending" --filter # 启用排序筛选
  340. # 推文详情
  341. twitter tweet 1234567890
  342. twitter tweet 1234567890 --full-text
  343. # 通过序号打开上次列表里的推文
  344. twitter show 2 # 打开上次 feed/search 的第 2 条
  345. twitter show 2 --full-text # 在回复表格里显示完整正文
  346. twitter show 2 --json # 结构化输出
  347. # Twitter 长文
  348. twitter article 1234567890
  349. twitter article https://x.com/user/article/1234567890 --json
  350. twitter article 1234567890 --markdown
  351. twitter article 1234567890 --output article.md
  352. # 列表时间线
  353. twitter list 1539453138322673664
  354. twitter list 1539453138322673664 --cursor "<上一页返回的 nextCursor>"
  355. twitter list 1539453138322673664 --full-text
  356. # 用户
  357. twitter user elonmusk
  358. twitter user-posts elonmusk --max 20
  359. twitter user-posts elonmusk --full-text
  360. twitter user-posts elonmusk -o tweets.json
  361. twitter likes elonmusk --max 30 # ⚠️ 仅可查看自己的点赞(2024年6月起平台已私密化)
  362. twitter likes elonmusk --full-text
  363. twitter likes elonmusk -o likes.json
  364. twitter followers elonmusk
  365. twitter following elonmusk
  366. # 写操作
  367. twitter post "你好,世界!"
  368. twitter post "发图" --image photo.jpg # 带图发推
  369. twitter post "多图" -i a.png -i b.jpg -i c.webp # 最多 4 张图片
  370. twitter post "回复内容" --reply-to 1234567890
  371. twitter reply 1234567890 "回复" -i screenshot.png # 带图回复
  372. twitter quote 1234567890 "评论" -i chart.png # 带图引用
  373. twitter post "你好,世界!" --json
  374. twitter delete 1234567890
  375. twitter like 1234567890
  376. twitter like 1234567890 --yaml
  377. twitter unlike 1234567890
  378. twitter retweet 1234567890
  379. twitter unretweet 1234567890
  380. twitter bookmark 1234567890
  381. twitter unbookmark 1234567890
  382. twitter follow elonmusk --json
  383. ```
  384. ### 认证说明
  385. 认证优先级:
  386. 1. **环境变量**:`TWITTER_AUTH_TOKEN` + `TWITTER_CT0`
  387. 2. **浏览器提取**(推荐):Arc/Chrome/Edge/Firefox/Brave 全量 Cookie 提取
  388. 推荐使用浏览器提取方式,会转发所有 Twitter Cookie,并按本机运行环境生成语言和平台请求头;它比仅发送 `auth_token` + `ct0` 更接近普通浏览器流量,但不等于完整浏览器自动化。
  389. **Chrome 多 Profile 支持**:会自动遍历所有 Chrome profile。也可以通过环境变量指定:
  390. ```bash
  391. TWITTER_CHROME_PROFILE="Profile 2" twitter feed
  392. ```
  393. **浏览器优先级**:如果有多个浏览器,可通过 `TWITTER_BROWSER` 指定优先尝试的浏览器:
  394. ```bash
  395. TWITTER_BROWSER=chrome twitter feed # 支持: arc, chrome, edge, firefox, brave
  396. ```
  397. ### 代理支持
  398. 设置 `TWITTER_PROXY` 环境变量即可:
  399. ```bash
  400. export TWITTER_PROXY=http://127.0.0.1:7890
  401. # 或 SOCKS5
  402. export TWITTER_PROXY=socks5://127.0.0.1:1080
  403. ```
  404. 使用代理可以降低 IP 维度的风控风险。
  405. ### 筛选算法
  406. 未传 `--max` 时,所有读取命令默认使用 `config.yaml` 里的 `fetch.count`。
  407. rich table 输出默认会截断较长正文;如果需要在列表视图中查看完整正文,可加 `--full-text`。
  408. 只有在传入 `--filter` 时才会启用筛选评分;默认不筛选。
  409. 评分公式:
  410. ```text
  411. score = likes_w * likes
  412. + retweets_w * retweets
  413. + replies_w * replies
  414. + bookmarks_w * bookmarks
  415. + views_log_w * log10(max(views, 1))
  416. ```
  417. 模式说明:
  418. - `mode: "topN"`:按分数排序后保留前 `topN` 条
  419. - `mode: "score"`:仅保留 `score >= minScore` 的推文
  420. - `mode: "all"`:按分数排序后全部保留
  421. ### 常见问题
  422. - 报错 `No Twitter cookies found`:请先登录 `x.com`,并确认浏览器为 Arc/Chrome/Edge/Firefox/Brave 之一,或手动设置环境变量。
  423. - 如需查看浏览器提取细节,可加 `-v` 打开诊断日志。
  424. - 报错 `Cookie expired or invalid`:Cookie 过期,重新登录后重试。
  425. - 报错 `Unable to get key for cookie decryption`(macOS Keychain 问题):
  426. - **SSH 远程登录**:Keychain 默认锁定,需手动解锁:
  427. ```bash
  428. security unlock-keychain ~/Library/Keychains/login.keychain-db
  429. ```
  430. - **本地终端**:打开 **钥匙串访问** → 搜索 **"\<浏览器\> Safe Storage"** → **访问控制** → 添加你的终端 app → **保存更改**。
  431. - 或在弹出 Keychain 授权时点击 **"始终允许"**。
  432. - 报错 `Twitter API error 404`:通常是 queryId 轮换,重试即可。
  433. - **Windows 下 pipe/subprocess 无法捕获输出**(AI agent 集成场景)
  434. - 这是 **ConPTY** 伪终端的问题,不是 twitter-cli 的 bug。Windows Terminal 的 ConPTY 可能拦截有网络延迟的命令的管道输出。
  435. - **解决方案**:使用 **Git Bash** 并在终端设置中设置 `"windowsEnableConpty": false`。
  436. - ConPTY 关闭后如用 PowerShell,emoji 可能会报 `UnicodeEncodeError: 'gbk'`。Git Bash 原生支持 UTF-8。
  437. - 标准 `subprocess.run(capture_output=True)` 和文件重定向 (`> file 2>&1`) 不受此问题影响。
  438. - 结构化错误码通常会区分 `not_authenticated`、`not_found`、`invalid_input`、`rate_limited`、`api_error`。
  439. ### 使用建议(防封号)
  440. - **使用代理** — 设置 `TWITTER_PROXY`,避免裸 IP 直连
  441. - **控制请求量** — 用 `--max 20` 而不是 `--max 500`
  442. - **避免频繁启动** — 每次启动都会访问 x.com 初始化反检测请求头
  443. - **使用浏览器 Cookie 提取** — 提供完整 Cookie 指纹
  444. - **避免数据中心 IP** — 住宅代理更安全
  445. - Cookie 仅在本地使用,不会被本工具上传
  446. ### 输出模式建议
  447. - 默认 rich table 适合终端交互式浏览
  448. - 需要在表格里看完整正文时,使用 `--full-text`
  449. - 需要脚本消费时,优先使用 `--yaml` 或 `--json`
  450. - 需要节省 token 时,使用 `-c` / `--compact`
  451. ### 作为 AI Agent Skill 使用
  452. twitter-cli 提供了 [`SKILL.md`](./SKILL.md),可让 AI Agent 更稳定地调用本工具。
  453. #### [Skills CLI](https://github.com/vercel-labs/skills)(推荐)
  454. ```bash
  455. npx skills add jackwener/twitter-cli
  456. ```
  457. | 参数 | 说明 |
  458. | --- | --- |
  459. | `-g` | 全局安装(用户级别,跨项目共享) |
  460. | `-a claude-code` | 指定目标 Agent |
  461. | `-y` | 非交互模式 |
  462. #### 手动安装
  463. ```bash
  464. mkdir -p .agents/skills
  465. git clone git@github.com:jackwener/twitter-cli.git .agents/skills/twitter-cli
  466. ```
  467. #### ~~OpenClaw / ClawHub~~(已过时)
  468. > ⚠️ ClawHub 安装方式已过时,不再支持。请使用上方的 Skills CLI 或手动安装。
  469. ### 更多工具
  470. - [bilibili-cli](https://github.com/jackwener/bilibili-cli) — Bilibili 视频、用户、搜索与动态 CLI
  471. - [discord-cli](https://github.com/jackwener/discord-cli) — Discord 本地优先同步、检索与导出 CLI
  472. - [tg-cli](https://github.com/jackwener/tg-cli) — Telegram 本地优先同步、检索与导出 CLI
  473. - [xiaohongshu-cli](https://github.com/jackwener/xiaohongshu-cli) — 小红书笔记与账号工作流 CLI

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.