twitter-scrapper/search.go

87 lines
2.5 KiB
Go
Raw Normal View History

package twitterscraper
import (
"context"
"errors"
"strconv"
)
2023-05-30 17:31:00 +03:00
const searchURL = "https://api.twitter.com/2/search/adaptive.json"
// SearchTweets returns channel with tweets for a given search query
func (s *Scraper) SearchTweets(ctx context.Context, query string, maxTweetsNbr int) <-chan *TweetResult {
return getTweetTimeline(ctx, query, maxTweetsNbr, s.FetchSearchTweets)
2020-12-12 23:33:57 +02:00
}
// SearchProfiles returns channel with profiles for a given search query
func (s *Scraper) SearchProfiles(ctx context.Context, query string, maxProfilesNbr int) <-chan *ProfileResult {
return getUserTimeline(ctx, query, maxProfilesNbr, s.FetchSearchProfiles)
}
// getSearchTimeline gets results for a given search query, via the Twitter frontend API
func (s *Scraper) getSearchTimeline(query string, maxNbr int, cursor string) (*timelineV1, error) {
if !s.isLogged {
return nil, errors.New("scraper is not logged in for search")
}
if maxNbr > 50 {
maxNbr = 50
2020-12-03 21:42:16 +07:00
}
2023-05-30 17:31:00 +03:00
req, err := s.newRequest("GET", searchURL)
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(maxNbr))
q.Add("query_source", "typed_query")
q.Add("pc", "1")
2023-02-16 11:15:13 +02:00
q.Add("requestContext", "launch")
q.Add("spelling_corrections", "1")
2023-02-16 11:15:13 +02:00
q.Add("include_ext_edit_control", "true")
if cursor != "" {
q.Add("cursor", cursor)
}
2020-12-23 19:53:48 +02:00
switch s.searchMode {
case SearchLatest:
2023-04-30 00:25:35 +03:00
q.Add("tweet_search_mode", "live")
2020-12-23 19:53:48 +02:00
case SearchPhotos:
q.Add("result_filter", "image")
case SearchVideos:
q.Add("result_filter", "video")
case SearchUsers:
q.Add("result_filter", "user")
}
req.URL.RawQuery = q.Encode()
var timeline timelineV1
2020-12-12 23:33:57 +02:00
err = s.RequestAPI(req, &timeline)
if err != nil {
return nil, err
}
return &timeline, nil
}
// FetchSearchTweets gets tweets for a given search query, via the Twitter frontend API
func (s *Scraper) FetchSearchTweets(query string, maxTweetsNbr int, cursor string) ([]*Tweet, string, error) {
timeline, err := s.getSearchTimeline(query, maxTweetsNbr, cursor)
if err != nil {
return nil, "", err
}
2021-07-16 11:08:43 +03:00
tweets, nextCursor := timeline.parseTweets()
return tweets, nextCursor, nil
}
// FetchSearchProfiles gets users for a given search query, via the Twitter frontend API
func (s *Scraper) FetchSearchProfiles(query string, maxProfilesNbr int, cursor string) ([]*Profile, string, error) {
timeline, err := s.getSearchTimeline(query, maxProfilesNbr, cursor)
if err != nil {
return nil, "", err
}
2021-07-16 11:08:43 +03:00
users, nextCursor := timeline.parseUsers()
return users, nextCursor, nil
}