twitter-scrapper/search.go

60 lines
1.5 KiB
Go
Raw Normal View History

package twitterscraper
import (
"context"
"net/url"
"strconv"
)
// SearchTweets returns channel with tweets for a given search query
2020-12-12 23:33:57 +02:00
func (s *Scraper) SearchTweets(ctx context.Context, query string, maxTweetsNbr int) <-chan *Result {
return getTimeline(ctx, query, maxTweetsNbr, s.FetchSearchTweets)
}
// SearchTweets wrapper for default Scraper
func SearchTweets(ctx context.Context, query string, maxTweetsNbr int) <-chan *Result {
2020-12-12 23:33:57 +02:00
return defaultScraper.SearchTweets(ctx, query, maxTweetsNbr)
}
// FetchSearchTweets gets tweets for a given search query, via the Twitter frontend API
2020-12-12 23:33:57 +02:00
func (s *Scraper) FetchSearchTweets(query string, maxTweetsNbr int, cursor string) ([]*Tweet, string, error) {
query = url.PathEscape(query)
2021-03-31 15:12:39 +03:00
if maxTweetsNbr > 100 {
maxTweetsNbr = 100
2020-12-03 21:42:16 +07:00
}
2020-12-12 23:33:57 +02:00
req, err := s.newRequest("GET", "https://twitter.com/i/api/2/search/adaptive.json")
if err != nil {
return nil, "", err
}
2020-06-15 15:26:43 +03:00
q := req.URL.Query()
q.Add("q", query)
q.Add("count", strconv.Itoa(maxTweetsNbr))
q.Add("query_source", "typed_query")
q.Add("pc", "1")
q.Add("spelling_corrections", "1")
if cursor != "" {
q.Add("cursor", cursor)
}
2020-12-23 19:53:48 +02:00
switch s.searchMode {
case SearchLatest:
q.Add("tweet_search_mode", "live")
case SearchPhotos:
q.Add("result_filter", "image")
case SearchVideos:
q.Add("result_filter", "video")
}
req.URL.RawQuery = q.Encode()
var timeline timeline
2020-12-12 23:33:57 +02:00
err = s.RequestAPI(req, &timeline)
if err != nil {
return nil, "", err
}
tweets, nextCursor := parseTimeline(&timeline)
return tweets, nextCursor, nil
}