twitter-scrapper/profile.go

104 lines
2.1 KiB
Go
Raw Normal View History

2019-09-21 10:59:45 +03:00
package twitterscraper
import (
"fmt"
"net/http"
2023-06-01 23:05:37 +03:00
"net/url"
2021-04-23 10:41:22 +03:00
"sync"
2019-09-21 10:59:45 +03:00
"time"
)
2021-04-23 10:41:22 +03:00
// Global cache for user IDs
var cacheIDs sync.Map
// Profile of twitter user.
2019-09-21 10:59:45 +03:00
type Profile struct {
Avatar string
2020-06-15 15:17:08 +03:00
Banner string
2019-09-21 10:59:45 +03:00
Biography string
Birthday string
FollowersCount int
FollowingCount int
FriendsCount int
IsPrivate bool
IsVerified bool
2019-09-21 10:59:45 +03:00
Joined *time.Time
LikesCount int
ListedCount int
2019-09-21 10:59:45 +03:00
Location string
Name string
PinnedTweetIDs []string
2019-09-21 10:59:45 +03:00
TweetsCount int
URL string
UserID string
2019-09-21 10:59:45 +03:00
Username string
Website string
}
type user struct {
Data struct {
User struct {
RestID string `json:"rest_id"`
Legacy legacyUser `json:"legacy"`
} `json:"user"`
} `json:"data"`
Errors []struct {
Message string `json:"message"`
} `json:"errors"`
}
// GetProfile return parsed user profile.
2020-12-12 23:33:57 +02:00
func (s *Scraper) GetProfile(username string) (Profile, error) {
var jsn user
2023-06-01 23:05:37 +03:00
req, err := http.NewRequest("GET", "https://api.twitter.com/graphql/4S2ihIKfF3xhp-ENxvUAfQ/UserByScreenName", nil)
if err != nil {
return Profile{}, err
}
2023-06-01 23:05:37 +03:00
variables := map[string]interface{}{
"screen_name": username,
"withHighlightedLabel": true,
}
query := url.Values{}
query.Set("variables", mapToJSONString(variables))
req.URL.RawQuery = query.Encode()
err = s.RequestAPI(req, &jsn)
if err != nil {
return Profile{}, err
}
if len(jsn.Errors) > 0 {
return Profile{}, fmt.Errorf("%s", jsn.Errors[0].Message)
}
if jsn.Data.User.RestID == "" {
return Profile{}, fmt.Errorf("rest_id not found")
2019-09-21 10:59:45 +03:00
}
jsn.Data.User.Legacy.IDStr = jsn.Data.User.RestID
2019-09-21 10:59:45 +03:00
if jsn.Data.User.Legacy.ScreenName == "" {
2020-08-10 14:08:35 +03:00
return Profile{}, fmt.Errorf("either @%s does not exist or is private", username)
}
return parseProfile(jsn.Data.User.Legacy), nil
2019-09-21 10:59:45 +03:00
}
2020-12-12 23:33:57 +02:00
2021-01-28 11:12:20 +02:00
// GetUserIDByScreenName from API
func (s *Scraper) GetUserIDByScreenName(screenName string) (string, error) {
id, ok := cacheIDs.Load(screenName)
if ok {
return id.(string), nil
}
profile, err := s.GetProfile(screenName)
if err != nil {
return "", err
}
cacheIDs.Store(screenName, profile.UserID)
return profile.UserID, nil
}