如何用 Go 抓取 Twitter (X):進階搜尋運算子、帳戶時間軸與 Cron 監察器(2026)
How to Scrape Twitter (X) with Go: Advanced Search Operators, Account Timelines, and a Cron Watcher (2026)
xsearch 是一款僅使用 Go 標準函式庫的工具,透過 ScrapeAtlas 取得候選貼文,再在本機套用 X 進階搜尋運算子篩選。工具設有 explain、search 和 watch 三個指令,watch 會把新匹配的貼文追加至 JSONL 檔案。X 服務條款禁止未經書面同意抓取;官方 API 按讀取貼文數收費,2026 年 11 月列價為每篇 $0.005。
"Twitter advanced search" gets about 18,100 US searches a month, and another 1,900 people a month search for how to "search twitter without account". Both groups want the same thing: type from:golang released min_faves:500 -filter:retweets and get a clean list of posts back, ideally in a script that can run every hour. In 2026 that is harder than it looks. The search page needs a login, the official API bills per post returned, and none of the logged-out tricks that used to work are left.
This post builds xsearch, a small Go tool (standard library only) that does it the other way around: it fetches candidate posts as JSON and then applies X's advanced-search operators locally, in about 800 lines of Go you can read and test. It has three commands:
-
explainshows how a query is split between "what to fetch" and "what to filter" -
searchprints matching posts as a table -
watchremembers what it has already reported and appends only new matches to a JSONL file, so it can run from cron
Everything below ran on November 27, 2026 (04:10-04:45 UTC) with Go 1.27.3 on a Linux server.
Read this first: X's Terms of Service prohibit scraping. The X Terms of Service (effective October 9, 2026) say that "crawling or scraping the Services in any form, for any purpose without our prior written consent is expressly prohibited", and that you may not access or search the Services "by any means (automated or otherwise) other than through our currently available, published interfaces". The catch-all group in
x.com/robots.txtisUser-agent: */Disallow: /. Review the terms and the legal risk for your use case and location before you run anything here. If the official X API covers your job, use it: recent search (last 7 days) and full-archive search are both there, billed pay-per-use (X's pricing page listed $0.005 per post read in November 2026). Keep volumes small, and don't republish other people's posts or build profiles of individuals. The tables below mask the handles of private persons.
Step 1: What a logged-out Go client gets
Before writing a parser, check what X sends to a plain HTTP client:
// probe: what X answers to a logged-out client in 2026. Go standard library only.
package main
import (
"bufio"
"fmt"
"io"
"net/http"
"strings"
"time"
)
func main() {
client := &http.Client{
Timeout: 20 * time.Second,
// Show redirects instead of following them.
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
urls := []string{
"https://x.com/search?q=golang%20min_faves%3A100&f=live",
"https://api.x.com/2/tweets/search/recent?query=golang",
"https://syndication.twitter.com/srv/timeline-profile/screen-name/golang",
"https://x.com/robots.txt",
}
for _, u := range urls {
req, _ := http.NewRequest("GET", u, nil)
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0 Safari/537.36")
resp, err := client.Do(req)
if err != nil {
fmt.Printf("%s\n error: %v\n", u, err)
continue
}
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
resp.Body.Close()
fmt.Printf("%s\n HTTP %d", u, resp.StatusCode)
if loc := resp.Header.Get("Location"); loc != "" {
fmt.Printf(" -> %.70s...", loc)
}
fmt.Println()
if strings.HasSuffix(u, "robots.txt") {
// Print the catch-all group: the rules for everyone who isn't a named crawler.
sc := bufio.NewScanner(strings.NewReader(string(body)))
inStar := false
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if strings.HasPrefix(line, "User-agent:") {
inStar = line == "User-agent: *"
}
if inStar && line != "" && !strings.HasPrefix(line, "#") {
fmt.Println(" ", line)
}
}
} else if len(body) > 0 {
fmt.Printf(" %.100s\n", strings.Join(strings.Fields(string(body)), " "))
}
}
}
https://x.com/search?q=golang%20min_faves%3A100&f=live
HTTP 307 -> /i/jf/onboarding/web?redirect_after_login=%2Fsearch%3Ff%3Dlive%26q%3Dg...
https://api.x.com/2/tweets/search/recent?query=golang
HTTP 401
{ "title": "Unauthorized", "type": "about:blank", "status": 401, "detail": "Unauthorized" }
https://syndication.twitter.com/srv/timeline-profile/screen-name/golang
HTTP 429
Rate limit exceeded
https://x.com/robots.txt
HTTP 200
User-agent: *
Disallow: /
Disallow: /i/u
Crawl-delay: 1
Sitemap: https://x.com/sitemap.xml
Sitemap: https://x.com/sitemaps/finance0
Four doors, four answers:
-
x.com/searchanswers with a307to the login flow. The advanced-search form just builds a/search?q=...URL like this one, so it is behind the same wall. -
api.x.com/2/tweets/search/recentis the official API. Without a bearer token you get401. With one you pay per post returned. -
The old syndication timeline (what embedded profile timelines used) is rate-limited to death:
429on the first request from this machine. -
robots.txtlists rules for named search crawlers and then closes everything else withDisallow: /.
So "just scrape the search page" is out, and I'm not going to show login automation or cookie reuse. That is exactly what the terms forbid, and the accounts get locked anyway. What's left is to fetch posts from a data source and do the search part yourself.
Step 2: Where the candidate posts come from
The tool reads X through ScrapeAtlas*, using two endpoints:
-
/v1/twitter/user-tweets?handle=golang&trim=truereturns an account's latest posts (14-20 per account in my runs) with views, likes, retweets, replies, quotes and the fulllegacyobject.sinceanduntilnarrow it down, but only inside that latest window: asking@golangfor September 2026 returned zero posts with the warninglatest_window_limited, even though the account posted in September. It costs 1 credit. -
/v1/twitter/search/posts?query=...finds posts by keyword through a web index, not through X's own search. Results come back in relevance order, a handful per page, with acursorlikeatlas:2orserper:3for the next page. It costs 2 credits per page. In my runs the cursor ran out after 3-4 pages, at roughly 10-20 unique posts per keyword. Operators are not supported there:from:golang since:2026-11-01came back with zero posts.
That split decides the design. A from: query is answered precisely from timelines. Everything else is discovery: the web index proposes posts, the local filter decides. You will not get "every post that mentions X". You'll get a relevant sample that is filtered exactly.
Every response also has a coverage object (complete, order, warnings). The tool prints the warnings on every run, because "0 matches" means something different when the source says complete: false.
Step 3: A client with a disk cache
While you tune a query you run the same fetches over and over. Each response is cached on disk for 30 minutes, keyed by the full URL, so re-running a filter costs nothing. 429 and 5xx are retried with backoff (2s, 4s, 8s). Other errors stop the run instead of being silently skipped.
package main
import (
"crypto/sha1"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"time"
)
const apiBase = "https://api.scrapeatlas.com"
type Client struct {
key string
http *http.Client
cacheDir string
cacheTTL time.Duration
Calls int // paid requests actually sent (cache hits are free)
}
// envelope holds the fields every ScrapeAtlas twitter response shares.
type envelope struct {
Success bool `json:"success"`
Status string `json:"status"`
Cursor *string `json:"cursor"`
Posts []rawTweet `json:"posts"` // /search/posts
Tweets []rawTweet `json:"tweets"` // /user-tweets
Error json.RawMessage `json:"error"`
Coverage struct {
Source string `json:"source"`
Order string `json:"order"`
Complete bool `json:"complete"`
Warnings []string `json:"warnings"`
} `json:"coverage"`
}
func NewClient() (*Client, error) {
key := os.Getenv("SCRAPEATLAS_API_KEY")
if key == "" {
return nil, errors.New("set SCRAPEATLAS_API_KEY")
}
return &Client{key: key, http: &http.Client{Timeout: 60 * time.Second},
cacheDir: "cache", cacheTTL: 30 * time.Minute}, nil
}
func (c *Client) Get(path string, params url.Values) (*envelope, error) {
u := apiBase + path + "?" + params.Encode()
sum := sha1.Sum([]byte(u))
cacheFile := filepath.Join(c.cacheDir, hex.EncodeToString(sum[:8])+".json")
if st, err := os.Stat(cacheFile); err == nil && time.Since(st.ModTime()) < c.cacheTTL {
if b, err := os.ReadFile(cacheFile); err == nil {
return decode(b)
}
}
var lastErr error
for attempt := 0; attempt < 4; attempt++ {
if attempt > 0 {
time.Sleep(time.Duration(1<<attempt) * time.Second) // 2s, 4s, 8s
}
req, _ := http.NewRequest("GET", u, nil)
req.Header.Set("x-api-key", c.key)
resp, err := c.http.Do(req)
if err != nil {
lastErr = err
continue
}
b, err := io.ReadAll(resp.Body)
resp.Body.Close()
c.Calls++
if err != nil {
lastErr = err
continue
}
if resp.StatusCode == 429 || resp.StatusCode >= 500 {
lastErr = fmt.Errorf("%s: HTTP %d", path, resp.StatusCode)
continue
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("%s: HTTP %d: %.300s", path, resp.StatusCode, b)
}
env, err := decode(b)
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
os.MkdirAll(c.cacheDir, 0o755)
os.WriteFile(cacheFile, b, 0o644)
return env, nil
}
return nil, lastErr
}
func decode(b []byte) (*envelope, error) {
var env envelope
if err := json.Unmarshal(b, &env); err != nil {
return nil, err
}
if !env.Success {
return nil, fmt.Errorf("success=false: %.300s", env.Error)
}
return &env, nil
}
Calls counts requests that actually went out, so the summary line can tell you what a run cost. A search page is 2 credits, so a 4-page search is 8 credits.
Step 4: Normalizing a tweet
Both endpoints return X's own GraphQL tweet shape. Some details matter for searching:
-
Retweets are shells. The retweet object has
favorite_count: 0and text cut at 140 characters (RT @resend: We rebuilt our email API to Go.\n\nIt took 7 weeks and 140 PRs, and we've been running in production for weeks at roughly half th…). The real text and media are inretweeted_status_result. -
Long posts live in
note_tweet.legacy.full_textstops near 280 characters. In the saved@golangtimeline, 5 of 17 posts were longer than that. If you match keywords againstfull_text, a word in paragraph two never matches. And not every long post has a note: one of NASA's posts ended mid-sentence at 277 characters ("NASA stands ready to") with nonote_tweetat all. -
Text is HTML-escaped.
>and&show up infull_text, so unescape before matching. -
Timeline items have no author object with
trim=true. Theurlfield (https://x.com/NASA/status/...) still has the handle in its original case.
package main
import (
"encoding/json"
"html"
"strconv"
"strings"
"time"
)
// Tweet is the flat shape the filter and the reports work on.
type Tweet struct {
ID string `json:"id"`
Author string `json:"author"`
Created time.Time `json:"created"`
Text string `json:"text"`
Lang string `json:"lang"`
Faves int `json:"faves"`
Retweets int `json:"retweets"`
Replies int `json:"replies"`
Quotes int `json:"quotes"`
Views int `json:"views"`
ReplyTo string `json:"reply_to,omitempty"`
IsRetweet bool `json:"is_retweet,omitempty"`
IsQuote bool `json:"is_quote,omitempty"`
HasMedia bool `json:"has_media,omitempty"`
URLs []string `json:"urls,omitempty"`
URL string `json:"url"`
}
type rawUser struct {
Result struct {
Core struct {
ScreenName string `json:"screen_name"`
} `json:"core"`
Legacy struct {
ScreenName string `json:"screen_name"`
} `json:"legacy"`
} `json:"result"`
}
type rawLegacy struct {
CreatedAt string `json:"created_at"`
FullText string `json:"full_text"`
Lang string `json:"lang"`
FavoriteCount int `json:"favorite_count"`
RetweetCount int `json:"retweet_count"`
ReplyCount int `json:"reply_count"`
QuoteCount int `json:"quote_count"`
IsQuoteStatus bool `json:"is_quote_status"`
InReplyTo string `json:"in_reply_to_screen_name"`
Entities struct {
URLs []struct {
ExpandedURL string `json:"expanded_url"`
} `json:"urls"`
} `json:"entities"`
ExtendedEntities struct {
Media []json.RawMessage `json:"media"`
} `json:"extended_entities"`
RetweetedStatus *struct {
Result rawTweet `json:"result"`
} `json:"retweeted_status_result"`
}
type rawTweet struct {
TypeName string `json:"__typename"`
Tweet *rawTweet `json:"tweet"` // TweetWithVisibilityResults wraps the real tweet
RestID string `json:"rest_id"`
Core struct {
UserResults rawUser `json:"user_results"`
} `json:"core"`
Views struct {
Count string `json:"count"`
} `json:"views"`
Legacy rawLegacy `json:"legacy"`
NoteTweet *struct { // posts longer than 280 characters
Results struct {
Result struct {
Text string `json:"text"`
EntitySet struct {
URLs []struct {
ExpandedURL string `json:"expanded_url"`
} `json:"urls"`
} `json:"entity_set"`
} `json:"result"`
} `json:"note_tweet_results"`
} `json:"note_tweet"`
URL string `json:"url"`
}
// normalize turns one ScrapeAtlas tweet object into a Tweet. Timeline items
// (trim=true) carry no author object: read it from the post URL, else use
// the handle the caller asked for.
func normalize(r rawTweet, fallbackAuthor string) (Tweet, error) {
if r.Tweet != nil {
r = *r.Tweet
}
l := r.Legacy
created, err := time.Parse(time.RubyDate, l.CreatedAt)
if err != nil {
return Tweet{}, err
}
author := r.Core.UserResults.Result.Core.ScreenName
if author == "" {
author = r.Core.UserResults.Result.Legacy.ScreenName
}
if author == "" && strings.HasPrefix(r.URL, "https://x.com/") {
author, _, _ = strings.Cut(strings.TrimPrefix(r.URL, "https://x.com/"), "/")
}
if author == "" {
author = fallbackAuthor
}
views, _ := strconv.Atoi(r.Views.Count)
t := Tweet{
ID: r.RestID, Author: author, Created: created.UTC(),
Text: html.UnescapeString(l.FullText), Lang: l.Lang,
Faves: l.FavoriteCount, Retweets: l.RetweetCount, Replies: l.ReplyCount,
Quotes: l.QuoteCount, Views: views, ReplyTo: l.InReplyTo,
IsQuote: l.IsQuoteStatus, HasMedia: len(l.ExtendedEntities.Media) > 0,
URL: r.URL,
}
for _, u := range l.Entities.URLs {
t.URLs = append(t.URLs, u.ExpandedURL)
}
if n := r.NoteTweet; n != nil && n.Results.Result.Text != "" {
// legacy.full_text stops near 280 characters; the note has the whole post.
t.Text = html.UnescapeString(n.Results.Result.Text)
t.URLs = nil
for _, u := range n.Results.Result.EntitySet.URLs {
t.URLs = append(t.URLs, u.ExpandedURL)
}
}
if rt := l.RetweetedStatus; rt != nil {
// The retweet shell has favorite_count 0 and a truncated "RT @x: ..." text.
// Keep the shell's id and time, but read text and media from the original.
orig, err := normalize(rt.Result, "")
if err == nil {
t.IsRetweet = true
t.Text = "RT @" + orig.Author + ": " + orig.Text
t.HasMedia, t.URLs = orig.HasMedia, orig.URLs
}
}
if t.URL == "" {
t.URL = "https://x.com/" + t.Author + "/status/" + t.ID
}
return t, nil
}
Step 5: Parsing advanced-search operators
This is the core. The parser supports the operators people actually type into advanced search:
| Operator | Meaning |
|---|---|
word, "exact phrase"
|
whole-word match, case-insensitive (golang also matches #golang) |
a OR b |
either term |
-word, -"phrase"
|
exclude |
#tag, @name
|
the hashtag or mention specifically |
from:, to:
|
author, reply-to account |
lang: |
X's language code |
since:, until:
|
YYYY-MM-DD in UTC, until exclusive |
min_faves:, min_retweets:, min_replies:
|
engagement floors |
filter:replies, filter:retweets, filter:quote, filter:media, filter:links, url:
|
post type, prefix - to exclude |
Anything else (near:, within:, list:) fails loudly instead of being ignored. A silently dropped operator gives you a wider result set than you asked for, and you won't notice.
package main
import (
"fmt"
"strconv"
"strings"
"time"
"unicode"
)
// Atom is one search term or operator, e.g. golang, "go 1.27", from:golang, -filter:replies.
type Atom struct {
Neg bool
Op string // "" for plain words and phrases
Value string
}
// Query is an AND of clauses; each clause is an OR of atoms.
type Query struct {
Clauses [][]Atom
Since time.Time // inclusive, UTC day
Until time.Time // exclusive, UTC day
MinFav int
MinRT int
MinRepl int
}
func tokenize(s string) []string {
var out []string
for i := 0; i < len(s); {
switch {
case s[i] == ' ' || s[i] == '\t':
i++
case s[i] == '"' || (s[i] == '-' && i+1 < len(s) && s[i+1] == '"'):
start := i
if s[i] == '-' {
i++
}
end := strings.IndexByte(s[i+1:], '"')
if end < 0 {
out = append(out, s[start:])
return out
}
out = append(out, s[start:i+1+end+1])
i += end + 2
default:
end := strings.IndexAny(s[i:], " \t")
if end < 0 {
end = len(s) - i
}
out = append(out, s[i:i+end])
i += end
}
}
return out
}
func ParseQuery(s string) (*Query, error) {
q := &Query{}
orNext := false
for _, tok := range tokenize(s) {
if tok == "OR" {
if len(q.Clauses) == 0 {
return nil, fmt.Errorf("query starts with OR")
}
orNext = true
continue
}
a := Atom{}
if strings.HasPrefix(tok, "-") && len(tok) > 1 {
a.Neg, tok = true, tok[1:]
}
if strings.HasPrefix(tok, `"`) {
a.Value = strings.ToLower(strings.Trim(tok, `"`))
} else if k, v, ok := strings.Cut(tok, ":"); ok && v != "" && !strings.Contains(k, "/") {
a.Op, a.Value = strings.ToLower(k), strings.ToLower(v)
} else {
a.Value = strings.ToLower(tok)
}
// Numeric and date operators become fields, not atoms.
handled, err := q.setField(a)
if err != nil {
return nil, err
}
if handled {
orNext = false
continue
}
if orNext {
last := len(q.Clauses) - 1
q.Clauses[last] = append(q.Clauses[last], a)
orNext = false
} else {
q.Clauses = append(q.Clauses, []Atom{a})
}
}
if orNext {
return nil, fmt.Errorf("query ends with OR")
}
return q, nil
}
func (q *Query) setField(a Atom) (bool, error) {
if a.Neg && a.Op != "" && a.Op != "filter" && a.Op != "from" && a.Op != "to" &&
a.Op != "lang" && a.Op != "url" {
return false, fmt.Errorf("cannot negate %s:", a.Op)
}
switch a.Op {
case "since", "until":
t, err := time.Parse("2006-01-02", a.Value)
if err != nil {
return false, fmt.Errorf("%s: want YYYY-MM-DD, got %q", a.Op, a.Value)
}
if a.Op == "since" {
q.Since = t
} else {
q.Until = t
}
return true, nil
case "min_faves", "min_retweets", "min_replies":
n, err := strconv.Atoi(a.Value)
if err != nil || n < 0 {
return false, fmt.Errorf("%s: want a number, got %q", a.Op, a.Value)
}
switch a.Op {
case "min_faves":
q.MinFav = n
case "min_retweets":
q.MinRT = n
default:
q.MinRepl = n
}
return true, nil
case "", "from", "to", "lang", "filter", "url":
return false, nil
}
return false, fmt.Errorf("unsupported operator %s:", a.Op)
}
// words lowercases text and splits it on anything that is not a letter, digit,
// '_', '#' or '@', so "Go 1.27!" -> [go 1 27].
func words(s string) []string {
return strings.FieldsFunc(strings.ToLower(s), func(r rune) bool {
return !(unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' || r == '#' || r == '@')
})
}
func containsSeq(hay, needle []string) bool {
if len(needle) == 0 {
return false
}
outer:
for i := 0; i+len(needle) <= len(hay); i++ {
for j := range needle {
if hay[i+j] != needle[j] {
continue outer
}
}
return true
}
return false
}
func (a Atom) match(t *Tweet, raw, bare []string) bool {
switch a.Op {
case "":
if strings.HasPrefix(a.Value, "#") || strings.HasPrefix(a.Value, "@") {
return containsSeq(raw, words(a.Value)) // #golang must be a hashtag
}
return containsSeq(bare, words(a.Value)) // golang also matches #golang
case "from":
return strings.EqualFold(t.Author, strings.TrimPrefix(a.Value, "@"))
case "to":
return strings.EqualFold(t.ReplyTo, strings.TrimPrefix(a.Value, "@"))
case "lang":
return t.Lang == a.Value
case "url":
for _, u := range t.URLs {
if strings.Contains(strings.ToLower(u), a.Value) {
return true
}
}
return false
case "filter":
switch a.Value {
case "replies":
return t.ReplyTo != ""
case "retweets", "nativeretweets":
return t.IsRetweet
case "quote":
return t.IsQuote
case "media":
return t.HasMedia
case "links":
return len(t.URLs) > 0
}
}
return false
}
// Match applies the whole query to one normalized tweet.
func (q *Query) Match(t *Tweet) bool {
if !q.Since.IsZero() && t.Created.Before(q.Since) {
return false
}
if !q.Until.IsZero() && !t.Created.Before(q.Until) {
return false
}
if t.Faves < q.MinFav || t.Retweets < q.MinRT || t.Replies < q.MinRepl {
return false
}
raw := words(t.Text)
bare := make([]string, len(raw))
for i, w := range raw {
bare[i] = strings.TrimLeft(w, "#@")
}
for _, clause := range q.Clauses {
ok := false
for _, a := range clause {
if a.match(t, raw, bare) != a.Neg {
ok = true
break
}
}
if !ok {
return false
}
}
return true
}
// Handles returns the accounts of the first clause made only of from: atoms
// (from:a OR from:b), or nil when no clause pins the author.
func (q *Query) Handles() []string {
for _, clause := range q.Clauses {
var hs []string
for _, a := range clause {
if a.Op != "from" || a.Neg {
hs = nil
break
}
hs = append(hs, strings.TrimPrefix(a.Value, "@"))
}
if hs != nil {
return hs
}
}
return nil
}
// Keywords returns plain search strings for the web-index search endpoint: the
// positive words and phrases, one string per alternative of the first OR clause.
func (q *Query) Keywords() []string {
var base []string
var alts []string
for _, clause := range q.Clauses {
if len(clause) == 1 && clause[0].Op == "" && !clause[0].Neg {
base = append(base, quoteIfSpace(clause[0].Value))
continue
}
if alts == nil {
plain := true
for _, a := range clause {
plain = plain && a.Op == "" && !a.Neg
}
if plain {
for _, a := range clause {
alts = append(alts, quoteIfSpace(a.Value))
}
}
}
}
if len(alts) == 0 {
if len(base) == 0 {
return nil
}
return []string{strings.Join(base, " ")}
}
var out []string
for _, alt := range alts {
out = append(out, strings.TrimSpace(strings.Join(base, " ")+" "+alt))
}
return out
}
func quoteIfSpace(s string) string {
if strings.Contains(s, " ") {
return `"` + s + `"`
}
return s
}
Three decisions worth explaining:
-
Whole words, no stemming.
releasedoes not match "released", andapidoes not match "APIs". X's search doesn't stem either, so the tool behaves the same, and you get used to writingrelease OR released. -
ORbinds to its neighbours, like X's search:golang OR #go -hiringmeans "(golang or #go) and not hiring". There are no parentheses, which keeps the parser tiny and covers most real queries. -
Keywords()fans out OR groups. The web index doesn't understandOR, soscraping OR scraper OR crawlerbecomes three keyword searches. That's three times the credits, andexplainshows it before you pay.
The tests pin down that behaviour, including the cases people get wrong:
package main
import (
"testing"
"time"
)
func TestMatch(t *testing.T) {
day := func(s string) time.Time { v, _ := time.Parse("2006-01-02", s); return v }
base := Tweet{ID: "1", Author: "golang", Created: day("2026-11-10"), Lang: "en", Faves: 968,
Retweets: 160, Text: "🎊 Go 1.27.4 and 1.26.11 are released! #golang"}
reply := base
reply.ReplyTo, reply.Faves = "someone", 3
rt := base
rt.IsRetweet, rt.Faves = true, 0
cases := []struct {
q string
t Tweet
want bool
}{
{`released`, base, true},
{`release`, base, false}, // whole words, like X
{`"1.27.4 and"`, base, true},
{`golang`, base, true}, // plain word also matches the hashtag
{`#released`, base, false}, // a hashtag query needs the hashtag
{`from:GoLang min_faves:500`, base, true},
{`from:golang min_faves:1000`, base, false},
{`released -filter:replies`, reply, false},
{`released filter:replies to:someone`, reply, true},
{`released -filter:retweets`, rt, false},
{`security OR released lang:en`, base, true},
{`security OR patch`, base, false},
{`released since:2026-11-10 until:2026-11-11`, base, true},
{`released until:2026-11-10`, base, false}, // until is exclusive
{`released -lang:en`, base, false},
}
for _, c := range cases {
q, err := ParseQuery(c.q)
if err != nil {
t.Fatalf("%s: %v", c.q, err)
}
if got := q.Match(&c.t); got != c.want {
t.Errorf("%-45s got %v want %v", c.q, got, c.want)
}
}
}
func TestParseErrors(t *testing.T) {
for _, s := range []string{`OR go`, `go OR`, `min_faves:lots`, `since:11/01/2026`, `near:berlin`, `-min_faves:5`} {
if _, err := ParseQuery(s); err == nil {
t.Errorf("%s: expected an error", s)
}
}
}
func TestPlan(t *testing.T) {
q, _ := ParseQuery(`"web scraping" golang OR rust -hiring min_faves:10`)
got := q.Keywords()
if len(got) != 2 || got[0] != `"web scraping" golang` || got[1] != `"web scraping" rust` {
t.Errorf("keywords = %q", got)
}
q, _ = ParseQuery(`from:golang OR from:NASA launch`)
if hs := q.Handles(); len(hs) != 2 || hs[1] != "nasa" {
t.Errorf("handles = %q", hs)
}
}
=== RUN TestNormalizeSaved
norm_test.go:35: testdata/user-tweets-golang.json: 17 tweets, 5 longer than 290 chars, 3 retweets
norm_test.go:35: testdata/search-posts.json: 9 tweets, 6 longer than 290 chars, 0 retweets
--- PASS: TestNormalizeSaved (0.00s)
=== RUN TestMatch
--- PASS: TestMatch (0.00s)
=== RUN TestParseErrors
--- PASS: TestParseErrors (0.00s)
=== RUN TestPlan
--- PASS: TestPlan (0.00s)
PASS
ok xsearch 0.004s
? xsearch/probe [no test files]
TestNormalizeSaved (in norm_test.go) runs normalize over two saved API responses and checks that every post has an ID, an author and a timestamp. That's how the note_tweet and retweet cases were found.
Step 6: Fetch, filter, report, watch
collect picks the source: timelines when the query pins from:, web-index search otherwise, plus any -watch accounts. watch keeps a state file of already-reported IDs (written to a temp file and renamed, so a crash mid-write can't wipe it) and appends new matches to JSONL.
// xsearch: X (Twitter) advanced-search operators, applied locally to posts
// fetched through the ScrapeAtlas API. Go standard library only.
package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"net/url"
"os"
"sort"
"strings"
"text/tabwriter"
"time"
)
type source struct {
fetched int
warnings map[string]bool
}
// collect fetches candidate posts: timelines when the query pins from:,
// web-index search pages otherwise, plus any extra -watch accounts.
func collect(c *Client, q *Query, pages int, watch []string) (map[string]Tweet, *source, error) {
seen := map[string]Tweet{}
src := &source{warnings: map[string]bool{}}
add := func(env *envelope, list []rawTweet, handle string) {
for _, w := range env.Coverage.Warnings {
src.warnings[env.Coverage.Source+":"+w] = true
}
for _, r := range list {
t, err := normalize(r, handle)
if err != nil || t.ID == "" {
continue
}
src.fetched++
seen[t.ID] = t
}
}
handles := append(q.Handles(), watch...)
for _, h := range handles {
p := url.Values{"handle": {h}, "trim": {"true"}}
if !q.Since.IsZero() {
p.Set("since", q.Since.Format(time.RFC3339))
}
if !q.Until.IsZero() {
p.Set("until", q.Until.Format(time.RFC3339))
}
env, err := c.Get("/v1/twitter/user-tweets", p)
if err != nil {
return nil, nil, fmt.Errorf("timeline @%s: %w", h, err)
}
add(env, env.Tweets, h)
}
if len(q.Handles()) > 0 {
return seen, src, nil // from: is answered by the timelines alone
}
kws := q.Keywords()
if len(kws) == 0 && len(handles) == 0 {
return nil, nil, fmt.Errorf("query needs at least one word, phrase or from:")
}
for _, kw := range kws {
cursor := ""
for page := 1; page <= pages; page++ {
p := url.Values{"query": {kw}}
if cursor != "" {
p.Set("cursor", cursor)
}
env, err := c.Get("/v1/twitter/search/posts", p)
if err != nil {
return nil, nil, fmt.Errorf("search %q page %d: %w", kw, page, err)
}
add(env, env.Posts, "")
if env.Cursor == nil || *env.Cursor == "" {
break
}
cursor = *env.Cursor
}
}
return seen, src, nil
}
func filterSort(all map[string]Tweet, q *Query, order string) []Tweet {
var out []Tweet
for _, t := range all {
if q.Match(&t) {
out = append(out, t)
}
}
sort.Slice(out, func(i, j int) bool {
if order == "top" && out[i].Faves != out[j].Faves {
return out[i].Faves > out[j].Faves
}
return out[i].Created.After(out[j].Created)
})
return out
}
func printTable(ts []Tweet, mask bool) {
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "CREATED (UTC)\tAUTHOR\tLANG\tLIKES\tRTS\tREPLIES\tVIEWS\tTEXT")
for _, t := range ts {
text := strings.Join(strings.Fields(t.Text), " ")
if r := []rune(text); len(r) > 60 {
text = string(r[:57]) + "..."
}
author := t.Author
if r := []rune(author); mask && len(r) > 2 {
author = string(r[:2]) + strings.Repeat("*", len(r)-2) // for reports you share
}
fmt.Fprintf(w, "%s\t@%s\t%s\t%d\t%d\t%d\t%d\t%s\n", t.Created.Format("2006-01-02 15:04"),
author, t.Lang, t.Faves, t.Retweets, t.Replies, t.Views, text)
}
w.Flush()
}
func explain(q *Query) {
fmt.Println("local filters:")
for _, clause := range q.Clauses {
var alts []string
for _, a := range clause {
s := a.Value
if a.Op != "" {
s = a.Op + ":" + s
}
if a.Neg {
s = "NOT " + s
}
alts = append(alts, s)
}
fmt.Println(" ", strings.Join(alts, " OR "))
}
if !q.Since.IsZero() || !q.Until.IsZero() {
day := func(t time.Time, zero string) string {
if t.IsZero() {
return zero
}
return t.Format("2006-01-02")
}
fmt.Printf(" created in [%s, %s)\n", day(q.Since, "start"), day(q.Until, "now"))
}
if q.MinFav+q.MinRT+q.MinRepl > 0 {
fmt.Printf(" likes>=%d retweets>=%d replies>=%d\n", q.MinFav, q.MinRT, q.MinRepl)
}
if hs := q.Handles(); hs != nil {
fmt.Println("fetch: timelines of", strings.Join(hs, ", "))
} else {
fmt.Printf("fetch: web-index search for %q\n", q.Keywords())
}
}
// watch keeps the IDs it has already reported in a state file and appends
// new matches to a JSONL file, so it can run from cron.
func watch(matches []Tweet, statePath, outPath string) ([]Tweet, error) {
state := map[string]string{} // tweet id -> first seen (RFC 3339)
if b, err := os.ReadFile(statePath); err == nil {
if err := json.Unmarshal(b, &state); err != nil {
return nil, fmt.Errorf("%s: %w", statePath, err)
}
}
f, err := os.OpenFile(outPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
return nil, err
}
defer f.Close()
bw := bufio.NewWriter(f)
now := time.Now().UTC().Format(time.RFC3339)
var fresh []Tweet
for _, t := range matches {
if _, ok := state[t.ID]; ok {
continue
}
state[t.ID] = now
fresh = append(fresh, t)
line, _ := json.Marshal(struct {
SeenAt string `json:"seen_at"`
Tweet
}{now, t})
bw.Write(append(line, '\n'))
}
if err := bw.Flush(); err != nil {
return nil, err
}
b, _ := json.MarshalIndent(state, "", " ")
tmp := statePath + ".tmp"
if err := os.WriteFile(tmp, b, 0o644); err != nil {
return nil, err
}
return fresh, os.Rename(tmp, statePath) // atomic: a crash never truncates state
}
func main() {
if len(os.Args) < 3 {
fmt.Fprintln(os.Stderr, "usage: xsearch explain|search|watch [flags] 'query'")
os.Exit(2)
}
cmd := os.Args[1]
fs := flag.NewFlagSet(cmd, flag.ExitOnError)
pages := fs.Int("pages", 3, "max search result pages per keyword (2 credits each)")
watchList := fs.String("watch", "", "comma-separated handles whose timelines are also checked")
order := fs.String("sort", "top", "top (likes) or latest")
statePath := fs.String("state", "state.json", "watch: ids already reported")
outPath := fs.String("out", "matches.jsonl", "watch: new matches are appended here")
mask := fs.Bool("mask", false, "print authors as go*** in the table")
fs.Parse(os.Args[2:])
q, err := ParseQuery(strings.Join(fs.Args(), " "))
if err != nil {
fmt.Fprintln(os.Stderr, "query:", err)
os.Exit(2)
}
if cmd == "explain" {
explain(q)
return
}
c, err := NewClient()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
var extra []string
if *watchList != "" {
extra = strings.Split(*watchList, ",")
}
all, src, err := collect(c, q, *pages, extra)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
matches := filterSort(all, q, *order)
var ws []string
for w := range src.warnings {
ws = append(ws, w)
}
sort.Strings(ws)
fmt.Fprintf(os.Stderr, "fetched %d posts (%d unique), %d match, %d paid requests; coverage warnings: %s\n",
src.fetched, len(all), len(matches), c.Calls, strings.Join(ws, ", "))
switch cmd {
case "search":
printTable(matches, *mask)
case "watch":
fresh, err := watch(matches, *statePath, *outPath)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Fprintf(os.Stderr, "%d new since last run\n", len(fresh))
printTable(fresh, *mask)
default:
fmt.Fprintln(os.Stderr, "unknown command", cmd)
os.Exit(2)
}
}
Build it:
go build -o xsearch .
export SCRAPEATLAS_API_KEY=...
Results
explain before you spend anything
$ ./xsearch explain '"error handling" golang OR #go -hiring lang:en -filter:retweets min_faves:50 since:2026-11-01'
local filters:
error handling
golang OR #go
NOT hiring
lang:en
NOT filter:retweets
created in [2026-11-01, now)
likes>=50 retweets>=0 replies>=0
fetch: web-index search for ["\"error handling\" golang" "\"error handling\" #go"]
The phrase and the OR group go to the web index (two searches, because of the OR). The exclusions, language, date and engagement floor are applied locally.
A precise query: Go releases from official accounts
$ ./xsearch search 'from:golang OR from:NASA released OR security -filter:retweets min_faves:500'
fetched 37 posts (37 unique), 4 match, 2 paid requests; coverage warnings: public_api:latest_window_limited, public_api:module_entries_omitted
CREATED (UTC) AUTHOR LANG LIKES RTS REPLIES VIEWS TEXT
2026-11-10 20:56 @golang en 968 160 16 46411 🎊 Go 1.27.4 and 1.26.11 are released! 🔏 Security: Include...
2026-10-20 03:44 @golang en 837 116 14 39167 👩🏽🔬 Go 1.27.3 and 1.26.10 are released! 🔐 Security: Incl...
2026-10-27 00:57 @golang en 747 111 15 69082 “Our Response To The eMudhra Key Disclosure Incident” by ...
2026-03-06 01:17 @golang en 627 117 10 80319 🌟 Go 1.26.1 and 1.25.8 are released! 🔐 Security: Includes...
Two timeline requests, 37 posts, four matches. NASA had 20 recent posts in the window and none said "released" or "security". The eMudhra post matched on "Security" in its byline ("on behalf of the Go Security team"), which is a fair match but maybe not what you meant. Read the matches before you trust the counts. This is the query type you can trust: the source is the account's own timeline, and the only limit is the window of roughly the last 20 posts.
A discovery query: who is talking about scraping
$ ./xsearch search -mask -pages 3 'scraping OR scraper OR crawler lang:en -filter:replies min_faves:5'
fetched 46 posts (42 unique), 14 match, 8 paid requests; coverage warnings: web_search:web_index_selection
CREATED (UTC) AUTHOR LANG LIKES RTS REPLIES VIEWS TEXT
2026-06-20 12:59 @ak************ en 6606 815 134 951560 Web scraping will never be the same. (100% open-source vi...
2026-07-05 15:19 @ma***** en 2076 70 188 669981 Meta is scraping like crazy. AI training crawls last 3 da...
2026-05-14 09:28 @he******** en 1052 148 12 106608 Alex Xu's System Design Interview is the most recommended...
2026-11-22 17:04 @jo****** en 386 24 56 33748 I disappeared from social media to automate marketing, gr...
2026-08-27 10:32 @na***** en 362 32 22 45599 [Hack] Google's new /goto URLs are encrypted to stop scra...
2026-08-25 16:09 @aa********* en 167 50 13 62729 Keenable stepped out of stealth today with a seed round. ...
2026-11-24 18:05 @ka********* en 156 7 24 12614 Ran The Model Atlas through Vybe's website analyzer I onl...
2026-02-10 17:54 @Vi*********** en 106 8 12 8951 building an autonomous tik tok scaper (with claude code) ...
2026-10-26 00:41 @St************* en 92 7 1 6347 Web scrapers that run in the cloud 24/7. Free for student...
2026-11-23 05:54 @il***** en 35 0 5 5217 Everyone shares prompts to "audit" a repo for security bu...
2026-08-27 11:55 @gl******* en 20 2 9 9140 I still think the tracking tools can pull the urls, so no...
2026-11-12 19:25 @Da******* en 15 2 3 1795 Your agent needs the page — not another CAPTCHA screen. F...
2026-06-23 23:19 @aj*** en 12 0 3 3690 New for Google Search: google•com/goto to fight AI and SE...
2026-11-18 21:23 @st********** en 5 0 2 288 Firecrawl just gave away the thing most scraping for agen...
Three keyword searches, 8 paid requests (16 credits), 42 unique posts, 14 matches. Read the list with the source in mind. It's ordered by relevance in a web index, so it spans February to November 2026, and a post about system-design books matched. Its long note text walks through how a search engine works, crawler included. The filter is exact. The candidate set is not.
The same tool with a stricter query shows the other edge:
$ ./xsearch search -mask -pages 4 '"web scraping" api OR mcp lang:en -filter:replies min_faves:20'
fetched 21 posts (14 unique), 1 match, 8 paid requests; coverage warnings: web_search:tweets_omitted, web_search:web_index_selection
CREATED (UTC) AUTHOR LANG LIKES RTS REPLIES VIEWS TEXT
2026-06-20 12:59 @ak************ en 6606 815 134 951560 Web scraping will never be the same. (100% open-source vi...
Fourteen candidates, one match. Most candidates don't contain the exact phrase "web scraping" at all, because the index matches on topic and not on words. Of the few that do, one has no "api" or "mcp", one is in Korean, and some write "APIs", which whole-word api doesn't match. When a discovery query comes back nearly empty, loosen the words first (api OR apis, drop the phrase), then the floors.
Errors that should be errors
$ ./xsearch search 'near:berlin golang'
query: unsupported operator near:
exit 2
$ ./xsearch search 'lang:en min_faves:100'
query needs at least one word, phrase or from:
exit 1
The second one matters. X would happily run lang:en min_faves:100 across the whole network. Here there is no network-wide stream to filter, so the tool refuses instead of quietly returning a few arbitrary posts.
Watching accounts from cron
$ ./xsearch watch -state data/state.json -out data/matches.jsonl 'from:golang OR from:github OR from:NASA -filter:retweets min_faves:1000'
fetched 51 posts (51 unique), 13 match, 1 paid requests; coverage warnings: public_api:latest_window_limited, public_api:module_entries_omitted
13 new since last run
CREATED (UTC) AUTHOR LANG LIKES RTS REPLIES VIEWS TEXT
2026-11-24 19:59 @NASA en 37785 3322 2162 14042369 As part of a coordinated, whole-of-government effort, NAS...
2026-11-24 16:50 @NASA en 8447 1041 538 954468 A home away from home 🌕 We're building a Moon Base, where...
2026-11-23 18:59 @NASA en 6387 792 233 1269140 Happy Thanksgiving from the @Space_Station! https://t.co/...
2026-11-23 16:28 @NASA en 6135 1011 258 896945 We're on our way to explore the mysteries of Europa, an o...
2026-11-24 22:04 @NASA en 5228 834 231 1205026 We've decided on key design features and mission details ...
2026-11-20 15:19 @NASA en 4582 876 237 765059 We 💛 V-G-R On the evening before Voyager 1 reached its on...
2026-11-25 17:24 @NASA en 3254 587 292 785670 Medicine or engineering? Military or civilian? We're look...
2026-11-20 16:45 @NASA en 2621 412 182 1002646 LIVE: Watch as an uncrewed SpaceX Dragon spacecraft undoc...
2026-10-30 20:26 @golang art 2144 91 35 103476 👀
2026-11-24 10:00 @NASA en 1581 236 115 755869 LIVE: An uncrewed Progress cargo spacecraft carrying food...
2026-11-26 11:30 @NASA en 1533 260 144 604367 LIVE: Watch the Progress 97 spacecraft arrive and dock to...
2026-11-25 16:00 @NASA en 1432 233 74 336979 We’re focused on improving all our business operations, i...
2026-08-11 16:53 @golang en 1219 189 45 142034 AI is your newest teammate—a hyper-productive contributor...
The first run reports everything that matches and records it. "1 paid requests" is not a typo: @golang and @NASA came from the cache of the previous search (same URL, under 30 minutes old), and only @github was fetched. @github had no post over 1,000 likes in its window. The 👀-only post from @golang has the language code art. Posts without real words get codes like that: I saw art and zxx (just a link) in these runs, and X also uses und and qme. lang:en drops all of them.
A later run, after the cache expired:
fetched 51 posts (51 unique), 13 match, 3 paid requests; coverage warnings: public_api:latest_window_limited, public_api:module_entries_omitted
0 new since last run
CREATED (UTC) AUTHOR LANG LIKES RTS REPLIES VIEWS TEXT
That run was at 04:45 UTC, 34 minutes after the first, with three fresh requests (3 credits). Nobody had posted anything over 1,000 likes in between, so nothing was reported and nothing was appended. That's the normal case for a watcher, and it's why the state file matters: without it, every run would report the same 13 posts again. The state file only tracks IDs, though. A post that crosses min_faves:1000 later is reported on the first run where it qualifies. A post that was already reported is never reported again, even if its likes triple. If you want that, store counts per run instead.
A crontab line that checks every two hours and logs new matches:
0 */2 * * * cd /opt/xsearch && ./xsearch watch -state data/state.json -out data/matches.jsonl 'from:golang OR from:github OR from:NASA -filter:retweets min_faves:1000' >> data/watch.log 2>&1
Each line in matches.jsonl is one post with a seen_at time. Here is the first one, pretty-printed and with the text shortened:
{
"seen_at": "2026-11-27T04:11:30Z",
"id": "2125318351341994436",
"author": "NASA",
"created": "2026-11-24T19:59:16Z",
"faves": 37785,
"retweets": 3322,
"replies": 2162,
"views": 14042369,
"url": "https://x.com/NASA/status/2125318351341994436",
"text": "As part of a coordinated, whole-of-government effort, NASA has rapidly mobilized..."
}
Twelve runs a day over three accounts is 36 credits a day. The account window (about 20 posts) is the real limit on the interval: for an account that posts 30 times a day, every two hours is too slow, and posts drop out of the window before you see them.
Pitfalls, in one place
-
Logged-out search is gone.
x.com/searchredirects to login, the API needs a token, the syndication timeline returns429. Don't build on any of them, and don't automate a logged-in session. - Search-by-keyword is discovery, not a firehose. The web index gives about 10-20 relevant posts per keyword, in relevance order, across months. Treat the results as a sample and say so in anything you report.
-
Operators sent to the search endpoint don't work.
from:golang since:2026-11-01returned nothing. Send words, filter locally. -
Timelines are a window, not an archive. About 20 latest posts.
since/untilfilter inside that window and return nothing outside it (latest_window_limited). -
Retweet shells have 0 likes and truncated text. Read the original from
retweeted_status_result, or exclude retweets. -
Use
note_tweetfor long posts.full_textstops near 280 characters, and some long posts have no note at all. -
Whole-word matching is strict.
apidoesn't match "APIs". Write the variants withOR. - Counts move between runs. The same post had 6,605 likes in one response and 6,606 in the next. Store snapshots with a time if you want trends. Don't compare across runs as if they were exact.
-
Language codes include
art,zxx,undandqme.lang:ensilently drops emoji-only and link-only posts. A two-word English post can also come back asda(one@golangpost did). -
Credits add up with OR. Every alternative in the first OR group is a separate search, and every page is 2 credits. Run
explainfirst. -
The official X API doesn't support
min_faves. If you move this tool to the official API later, keep the local filter: engagement floors stay client-side there too.
Wrapping up
- Advanced search can be split in two: fetch candidates, then filter with operators you implement yourself. In Go that's a ~290-line parser plus a table of tests.
-
from:queries are precise; keyword queries are a sample. Print the coverage warnings next to every result, so nobody reads "14 matches" as "14 posts exist". -
explainbeforesearchsaves credits and surprises, andwatchwith a state file turns the whole thing into a cron job. - X's terms ban scraping. Read them, prefer the official API where it fits, keep volumes small, and keep individual people's handles out of anything you publish.
*I build it.
來源:DEV Community · dev.to