-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitter.go
716 lines (578 loc) · 15.5 KB
/
twitter.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
package service
import (
"encoding/json"
"errors"
"log"
"reflect"
"strings"
"github.com/opensaucerers/giveawaybot/config"
"go.mongodb.org/mongo-driver/bson/primitive"
"github.com/opensaucerer/goaxios"
"github.com/opensaucerers/giveawaybot/typing"
)
// GetAccessToken gets the access token from twitter
func GetTwitterAccessToken(code string) ([]byte, error) {
// send http request to twitter to get access token
r := goaxios.GoAxios{
Url: "https://api.twitter.com/2/oauth2/token",
Method: "POST",
Headers: map[string]string{
// needs to be empty to prevent goaxios from setting content-type to application/json
},
Query: map[string]string{
"code": code,
"grant_type": "authorization_code",
"client_id": config.Env.TwitterClientID,
"redirect_uri": config.Env.TwitterRedirectURL,
"code_verifier": "challenge",
},
}
// send request
resp := r.RunRest()
if resp.Error != nil {
return nil, resp.Error
}
return resp.Bytes, nil
}
// GetAuthenticatedUser gets the authenticated user from twitter
func GetAuthenticatedTwitter(accessToken string) ([]byte, error) {
// get the twitter user
u := goaxios.GoAxios{
Url: "https://api.twitter.com/2/users/me",
BearerToken: accessToken,
Query: map[string]string{
"user.fields": "public_metrics",
},
}
// send request
resp := u.RunRest()
if resp.Error != nil {
return nil, resp.Error
}
return resp.Bytes, nil
}
// RefreshTwitterAccessToken refreshes the access token from twitter
func RefreshTwitterAccessToken(refreshToken string) ([]byte, error) {
// refresh the access token
r := goaxios.GoAxios{
Url: "https://api.twitter.com/2/oauth2/token",
Method: "POST",
Headers: map[string]string{
// needs to be empty to prevent goaxios from setting content-type to application/json
},
Query: map[string]string{
"grant_type": "refresh_token",
"refresh_token": refreshToken,
"client_id": config.Env.TwitterClientID,
},
}
// send request
resp := r.RunRest()
if resp.Error != nil {
return nil, resp.Error
}
return resp.Bytes, nil
}
// Tweet tweets a message to twitter
func Tweet(accessToken, message, replyTo, quote string) ([]byte, error) {
body := map[string]interface{}{"text": message}
if replyTo != "" {
body["reply"] = map[string]interface{}{
"in_reply_to_tweet_id": replyTo,
}
}
if quote != "" {
body["quote_tweet_id"] = quote
}
// tweet the message
r := goaxios.GoAxios{
Url: "https://api.twitter.com/2/tweets",
Method: "POST",
BearerToken: accessToken,
Body: body,
}
// send request
resp := r.RunRest()
if resp.Error != nil {
return nil, resp.Error
}
return resp.Bytes, nil
}
// ListTweets lists tweets from twitter
func ListTweets(accessToken, userID, limit, cursor string) ([]byte, error) {
// list tweets
query := map[string]string{
"tweet.fields": "created_at",
}
if limit != "" {
query["max_results"] = limit
}
if cursor != "" {
query["pagination_token"] = cursor
}
r := goaxios.GoAxios{
Url: "https://api.twitter.com/2/users/" + userID + "/tweets",
BearerToken: accessToken,
Query: query,
}
// send request
resp := r.RunRest()
if resp.Error != nil {
return nil, resp.Error
}
return resp.Bytes, nil
}
// LikeTweet likes a tweet
func LikeTweet(accessToken, userID, tweetID string) ([]byte, error) {
// like tweet
r := goaxios.GoAxios{
Url: "https://api.twitter.com/2/users/" + userID + "/likes",
Method: "POST",
BearerToken: accessToken,
Body: map[string]interface{}{
"tweet_id": tweetID,
},
}
// send request
resp := r.RunRest()
if resp.Error != nil {
return nil, resp.Error
}
return resp.Bytes, nil
}
// Retweet retweets a tweet
func Retweet(accessToken, userID, tweetID string) ([]byte, error) {
// retweet
r := goaxios.GoAxios{
Url: "https://api.twitter.com/2/users/" + userID + "/retweets",
Method: "POST",
BearerToken: accessToken,
Body: map[string]interface{}{
"tweet_id": tweetID,
},
}
// send request
resp := r.RunRest()
if resp.Error != nil {
return nil, resp.Error
}
return resp.Bytes, nil
}
// ListLikes lists likes of a specific tweet
func ListLikes(accessToken, tweetID, limit, cursor string) ([]byte, error) {
// list likes
query := map[string]string{}
if limit != "" {
query["max_results"] = limit
}
if cursor != "" {
query["pagination_token"] = cursor
}
r := goaxios.GoAxios{
Url: "https://api.twitter.com/2/tweets/" + tweetID + "/liking_users",
BearerToken: accessToken,
Query: query,
}
// send request
resp := r.RunRest()
if resp.Error != nil {
return nil, resp.Error
}
return resp.Bytes, nil
}
// IsLiking verifies if a user is liking a tweet
func IsLiking(accessToken, userID, tweetID, cursor string) (bool, error) {
// time.Sleep(20 * time.Second)
// list likes
b, err := ListLikes(accessToken, tweetID, "100", cursor)
if err != nil {
return true, err
}
// parse response
var response typing.TwitterListResponse
if err := json.Unmarshal(b, &response); err != nil {
return true, err
}
var null *int = nil
var zero *int = new(int)
if !reflect.DeepEqual(response.Meta.ResultCount, null) && reflect.DeepEqual(response.Meta.ResultCount, zero) {
return false, nil
}
if len(response.Data) == 0 {
var response typing.TwitterTweetError
if err := json.Unmarshal(b, &response); err != nil {
return true, err
}
if len(response.Errors) > 0 {
if response.Errors[0].Title == config.ErrTwitterNotFound {
return true, nil
}
if response.Errors[0].Title != "" {
return true, errors.New(response.Errors[0].Title)
}
} else if response.Title != "" {
return true, errors.New(response.Title)
}
return true, errors.New("unknown error")
}
for _, user := range response.Data {
if user.ID == userID {
return true, nil
}
}
if response.Meta.NextToken != "" {
return IsLiking(accessToken, userID, tweetID, response.Meta.NextToken)
}
return false, nil
}
// ListRetweets lists retweets of a specific tweet
func ListRetweets(accessToken, tweetID, limit, cursor string) ([]byte, error) {
// list likes
query := map[string]string{}
if limit != "" {
query["max_results"] = limit
}
if cursor != "" {
query["pagination_token"] = cursor
}
r := goaxios.GoAxios{
Url: "https://api.twitter.com/2/tweets/" + tweetID + "/retweeted_by",
BearerToken: accessToken,
Query: query,
}
// send request
resp := r.RunRest()
if resp.Error != nil {
return nil, resp.Error
}
return resp.Bytes, nil
}
// IsRetweeting verifies if a user is retweeting a tweet
func IsRetweeting(accessToken, userID, tweetID, cursor string) (bool, error) {
// time.Sleep(20 * time.Second)
// list likes
b, err := ListRetweets(accessToken, tweetID, "100", cursor)
if err != nil {
return true, err
}
// parse response
var response typing.TwitterListResponse
if err := json.Unmarshal(b, &response); err != nil {
return true, err
}
var null *int = nil
var zero *int = new(int)
if !reflect.DeepEqual(response.Meta.ResultCount, null) && reflect.DeepEqual(response.Meta.ResultCount, zero) {
return false, nil
}
if len(response.Data) == 0 {
var response typing.TwitterTweetError
if err := json.Unmarshal(b, &response); err != nil {
return true, err
}
if len(response.Errors) > 0 {
if response.Errors[0].Title == config.ErrTwitterNotFound {
return true, nil
}
if response.Errors[0].Title != "" {
return true, errors.New(response.Errors[0].Title)
}
} else if response.Title != "" {
return true, errors.New(response.Title)
}
return true, errors.New("unknown error")
}
for _, user := range response.Data {
if user.ID == userID {
return true, nil
}
}
if response.Meta.NextToken != "" {
return IsRetweeting(accessToken, userID, tweetID, response.Meta.NextToken)
}
return false, nil
}
// GetTweet gets a tweet
func GetTweet(accessToken, tweetID string) ([]byte, error) {
// get tweet
r := goaxios.GoAxios{
Url: "https://api.twitter.com/2/tweets",
BearerToken: accessToken,
Query: map[string]string{
"ids": tweetID,
"expansions": "author_id",
},
Method: "GET",
}
// send request
resp := r.RunRest()
if resp.Error != nil {
return nil, resp.Error
}
return resp.Bytes, nil
}
// IsReplying verifies if a user is replying to a tweet
func IsReplying(accessToken, userID, replyID string) (bool, error) {
if replyID == "" {
return false, nil
}
// time.Sleep(20 * time.Second)
// list likes
b, err := GetTweet(accessToken, replyID)
if err != nil {
return true, err
}
// parse response
var response typing.TwitterListResponse
if err := json.Unmarshal(b, &response); err != nil {
return true, err
}
if len(response.Data) == 0 {
var response typing.TwitterTweetError
if err := json.Unmarshal(b, &response); err != nil {
return true, err
}
if len(response.Errors) > 0 {
if response.Errors[0].Title == config.ErrTwitterNotFound {
return false, nil
}
if response.Errors[0].Title != "" {
return true, errors.New(response.Errors[0].Title)
}
} else if response.Title != "" {
return true, errors.New(response.Title)
}
}
for _, tweet := range response.Data {
if tweet.ID == replyID && tweet.AuthorID == userID {
return true, nil
}
}
return false, nil
}
// IsAlive verifies if a tweet is alive
func IsAlive(accessToken, replyID string) (bool, error) {
// time.Sleep(20 * time.Second)
// list likes
b, err := GetTweet(accessToken, replyID)
if err != nil {
return true, err
}
// parse response
var response typing.TwitterListResponse
if err := json.Unmarshal(b, &response); err != nil {
return true, err
}
if len(response.Data) == 0 {
var response typing.TwitterTweetError
if err := json.Unmarshal(b, &response); err != nil {
return true, err
}
if len(response.Errors) > 0 {
if strings.EqualFold(response.Errors[0].Title, config.ErrTwitterNotFound) {
return false, nil
}
if response.Errors[0].Title != "" {
return true, errors.New(response.Errors[0].Title)
}
return true, errors.New("unknown error")
} else if response.Title != "" {
return true, errors.New(response.Title)
}
}
return true, nil
}
// GetTweetEmbed gets a tweet embed
func GetTweetEmbed(username, tweetID string) ([]byte, error) {
/* https://publish.twitter.com/oembed?url=https://twitter.com/UnderworldsNFT/status/1638179205081826306?s=20&partner=&hide_thread=false */
// get embed
r := goaxios.GoAxios{
Url: "https://publish.twitter.com/oembed",
Query: map[string]string{
"url": "https://twitter.com/" + username + "/status/" + tweetID,
"hide_thread": "false",
"partner": "",
"s": "20",
},
Method: "GET",
Headers: map[string]string{},
}
// send request
resp := r.RunRest()
if resp.Error != nil {
return nil, resp.Error
}
return resp.Bytes, nil
}
// DeleteTweet deletes a tweet
func DeleteTweet(accessToken, tweetID string) (bool, error) {
// delete tweet
r := goaxios.GoAxios{
Url: "https://api.twitter.com/2/tweets/" + tweetID,
BearerToken: accessToken,
Method: "DELETE",
}
// send request
resp := r.RunRest()
if resp.Error != nil {
return false, resp.Error
}
// parse response
var response typing.TwitterDeleteTweetResponse
if err := json.Unmarshal(resp.Bytes, &response); err != nil {
return false, err
}
if !response.Data.Deteted {
var response typing.TwitterTweetError
if err := json.Unmarshal(resp.Bytes, &response); err != nil {
return true, err
}
if len(response.Errors) > 0 {
if strings.EqualFold(response.Errors[0].Title, config.ErrTwitterNotFound) {
return true, nil
}
if response.Errors[0].Title != "" {
return true, errors.New(response.Errors[0].Title)
}
return true, errors.New("unknown error")
} else if response.Title != "" {
return true, errors.New(response.Title)
}
}
return true, nil
}
// Mentions gets all mentions to a user
func Mentions(accessToken, userID, limit, cursor string) ([]byte, error) {
// list replies
query := map[string]string{
"tweet.fields": "conversation_id,referenced_tweets",
"expansions": "author_id",
"user.fields": "username",
}
if limit != "" {
query["max_results"] = limit
}
if cursor != "" {
query["pagination_token"] = cursor
}
r := goaxios.GoAxios{
Url: "https://api.twitter.com/2/users/" + userID + "/mentions",
BearerToken: accessToken,
Query: query,
Method: "GET",
}
// send request
// send request
resp := r.RunRest()
if resp.Error != nil {
return nil, resp.Error
}
return resp.Bytes, nil
}
// RetriveReplies gets all replies to a tweet
func RetriveReplies(accessToken, userID, tweetID string, giveawayid primitive.ObjectID) ([]typing.Reply, error) {
var (
replies = make([]typing.Reply, 0)
cursor = ""
limit = "100"
err error
b []byte
i = 0
)
for {
log.Printf("In 5 seconds getting page %d with cursor %s", i, cursor)
// time.Sleep(5 * time.Second)
// list likes
b, err = Mentions(accessToken, userID, limit, cursor)
if err != nil {
return replies, err
}
i++
// parse response
var response typing.TwitterListResponse
if err := json.Unmarshal(b, &response); err != nil {
return replies, err
}
var null *int = nil
var zero *int = new(int)
if !reflect.DeepEqual(response.Meta.ResultCount, null) && reflect.DeepEqual(response.Meta.ResultCount, zero) {
return replies, nil
}
if len(response.Data) == 0 {
var response typing.TwitterTweetError
if err := json.Unmarshal(b, &response); err != nil {
break
}
if len(response.Errors) > 0 {
if response.Errors[0].Title == config.ErrTwitterNotFound {
break
}
if response.Errors[0].Title != "" {
err = errors.New(response.Errors[0].Title)
break
}
} else if response.Title != "" {
err = errors.New(response.Title)
break
}
break
}
log.Printf("Found %d replies on page %d", len(response.Data), i)
for _, tweet := range response.Data {
if tweet.ConversationID == tweetID {
username := ""
Username:
for _, user := range response.Includes.Users {
if user.ID == tweet.AuthorID {
username = user.Username
break Username
}
}
// each tweet text is expected to contain @username. Ideally, each should contain just two @s, the first one being the username of the person being replied to and the second one being the username the person replying tagged. However, there are cases where the tweet text contains more than two @s. To efficiently handle this, we get the last @ in the tweet text and use that to get the username the person replying tagged.
at := strings.LastIndex(tweet.Text, "@")
if at == -1 {
continue
}
// get the username
ftext := tweet.Text[at:]
replies = append(replies, typing.Reply{
ID: tweet.AuthorID,
Text: tweet.Text,
Username: username,
TweetID: tweet.ID,
FText: ftext,
Giveaway: giveawayid,
})
}
}
if response.Meta.NextToken != "" {
cursor = response.Meta.NextToken
} else {
cursor = ""
}
if cursor == "" {
log.Println("Stopping iteration...no more data")
break
}
log.Printf("Next cursor: %s", cursor)
}
return replies, err
}
// Message sends a message to a user
func Message(accessToken, userID, text string) ([]byte, error) {
// send message
r := goaxios.GoAxios{
Url: "https://api.twitter.com/2/dm_conversations/with/" + userID + "/messages",
BearerToken: accessToken,
Body: map[string]interface{}{
"text": text,
},
Method: "POST",
}
// send request
resp := r.RunRest()
if resp.Error != nil {
return nil, resp.Error
}
return resp.Bytes, nil
}