forked from imperatrona/twitter-scraper
-
Notifications
You must be signed in to change notification settings - Fork 1
/
schedule.go
255 lines (214 loc) · 6.38 KB
/
schedule.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package twitterscraper
import (
"bytes"
"encoding/json"
"errors"
"io"
"net/url"
"strconv"
"strings"
"time"
)
type scheduleTweet struct {
RestID string `json:"rest_id"`
SchedulingInfo struct {
ExecuteAt int64 `json:"execute_at"`
State string `json:"state"`
} `json:"scheduling_info"`
TweetCreateRequest struct {
Type string `json:"type"`
Status string `json:"status"`
ExcludeReplyUserIds []interface{} `json:"exclude_reply_user_ids"`
MediaIds []interface{} `json:"media_ids"`
AutoPopulateReplyMetadata bool `json:"auto_populate_reply_metadata"`
} `json:"tweet_create_request"`
MediaEntities []struct {
MediaKey string `json:"media_key"`
MediaInfo struct {
Typename string `json:"__typename"`
OriginalImgURL string `json:"original_img_url"`
OriginalImgWidth int `json:"original_img_width"`
OriginalImgHeight int `json:"original_img_height"`
DurationMillis int `json:"duration_millis"`
Variants []struct {
ContentType string `json:"content_type"`
Bitrate int `json:"bit_rate,omitempty"`
URL string `json:"url"`
} `json:"variants"`
AspectRatio struct {
Numerator int `json:"numerator"`
Denominator int `json:"denominator"`
} `json:"aspect_ratio"`
PreviewImage struct {
OriginalImgURL string `json:"original_img_url"`
OriginalImgWidth int `json:"original_img_width"`
OriginalImgHeight int `json:"original_img_height"`
} `json:"preview_image"`
} `json:"media_info"`
} `json:"media_entities,omitempty"`
}
func (result *scheduleTweet) parse() *ScheduledTweet {
tweet := &ScheduledTweet{
ID: result.RestID,
State: result.SchedulingInfo.State,
ExecuteAt: time.Unix(result.SchedulingInfo.ExecuteAt/1000, 0),
Text: result.TweetCreateRequest.Status,
}
for _, media := range result.MediaEntities {
k := strings.Split(media.MediaKey, "_")
key := k[len(k)-1]
if media.MediaInfo.Typename == "ApiVideo" {
video := Video{
ID: key,
Preview: media.MediaInfo.PreviewImage.OriginalImgURL,
}
maxBitrate := 0
for _, variant := range media.MediaInfo.Variants {
if variant.Bitrate > maxBitrate {
video.URL = strings.TrimSuffix(variant.URL, "?tag=10")
maxBitrate = variant.Bitrate
}
}
tweet.Videos = append(tweet.Videos, video)
} else if media.MediaInfo.Typename == "ApiGif" {
gif := GIF{
ID: key,
Preview: media.MediaInfo.PreviewImage.OriginalImgURL,
}
maxBitrate := 0
for _, variant := range media.MediaInfo.Variants {
if variant.Bitrate >= maxBitrate {
gif.URL = variant.URL
maxBitrate = variant.Bitrate
}
}
tweet.GIFs = append(tweet.GIFs, gif)
} else if media.MediaInfo.Typename == "ApiImage" {
tweet.Photos = append(tweet.Photos, Photo{
ID: key,
URL: media.MediaInfo.OriginalImgURL,
})
}
}
return tweet
}
type scheduleTweets struct {
Data struct {
Viewer struct {
ScheduledTweetList []scheduleTweet `json:"scheduled_tweet_list"`
} `json:"viewer"`
} `json:"data"`
}
type TweetSchedule struct {
Text string
Date time.Time
Medias []*Media
}
func (timeline *scheduleTweets) parseTweets() []*ScheduledTweet {
var tweets []*ScheduledTweet
for _, entry := range timeline.Data.Viewer.ScheduledTweetList {
if tweet := entry.parse(); tweet != nil {
tweets = append(tweets, tweet)
}
}
return tweets
}
// FetchScheduledTweets gets scheduled tweets via the Twitter frontend GraphQL API.
func (s *Scraper) FetchScheduledTweets() ([]*ScheduledTweet, error) {
req, err := s.newRequest("GET", "https://twitter.com/i/api/graphql/ITtjAzvlZni2wWXwf295Qg/FetchScheduledTweets")
if err != nil {
return nil, err
}
variables := map[string]interface{}{
"ascending": true,
}
query := url.Values{}
query.Set("variables", mapToJSONString(variables))
req.URL.RawQuery = query.Encode()
var timeline scheduleTweets
err = s.RequestAPI(req, &timeline)
if err != nil {
return nil, err
}
tweets := timeline.parseTweets()
return tweets, nil
}
// DeleteScheduledTweet removes tweet from scheduled.
func (s *Scraper) DeleteScheduledTweet(id string) error {
req, err := s.newRequest("POST", "https://twitter.com/i/api/graphql/CTOVqej0JBXAZSwkp1US0g/DeleteScheduledTweet")
if err != nil {
return err
}
req.Header.Set("content-type", "application/json")
variables := map[string]interface{}{
"scheduled_tweet_id": id,
}
body := map[string]interface{}{
"variables": variables,
"queryId": "CTOVqej0JBXAZSwkp1US0g",
}
b, _ := json.Marshal(body)
req.Body = io.NopCloser(bytes.NewReader(b))
var response struct {
Data struct {
Status string `json:"scheduledtweet_delete"`
} `json:"data"`
}
err = s.RequestAPI(req, &response)
if err != nil {
return err
}
if response.Data.Status == "Done" {
return nil
}
return errors.New("scheduled tweet wasn't removed")
}
// CreateScheduledTweet schedule new tweet.
func (s *Scraper) CreateScheduledTweet(schedule TweetSchedule) (string, error) {
if schedule.Date.Unix() <= time.Now().Unix() {
return "", errors.New("date can't be in past")
}
req, err := s.newRequest("POST", "https://twitter.com/i/api/graphql/LCVzRQGxOaGnOnYH01NQXg/CreateScheduledTweet")
if err != nil {
return "", err
}
req.Header.Set("content-type", "application/json")
post_tweet_request := map[string]interface{}{
"auto_populate_reply_metadata": false,
"status": schedule.Text,
"exclude_reply_user_ids": []string{},
"media_ids": []string{},
}
if len(schedule.Medias) > 0 {
var media_ids []string
for _, media := range schedule.Medias {
media_ids = append(media_ids, strconv.Itoa(media.ID))
}
post_tweet_request["media_ids"] = media_ids
}
variables := map[string]interface{}{
"post_tweet_request": post_tweet_request,
"execute_at": schedule.Date.Unix(),
}
body := map[string]interface{}{
"variables": variables,
"queryId": "LCVzRQGxOaGnOnYH01NQXg",
}
b, _ := json.Marshal(body)
req.Body = io.NopCloser(bytes.NewReader(b))
var response struct {
Data struct {
Tweet struct {
ID string `json:"rest_id"`
} `json:"tweet"`
} `json:"data"`
}
err = s.RequestAPI(req, &response)
if err != nil {
return "", err
}
if response.Data.Tweet.ID != "" {
return response.Data.Tweet.ID, nil
}
return "", errors.New("tweet wasn't scheduled")
}