-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtwitter.go
280 lines (237 loc) · 6.66 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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/g8rswimmer/go-twitter/v2"
log "github.com/sirupsen/logrus"
"github.com/slack-go/slack"
"gorm.io/gorm"
)
var twitterIconURL = "https://emoji.slack-edge.com/T085AJH3L/twitter/290f7fdbde70c82d.png"
type TwitterTweet struct {
ID int32 `gorm:"AUTO_INCREMENT" form:"id" json:"id"`
TweetID string `gorm:"not null" form:"tweet_id" json:"tweet_id"`
}
type authorize struct {
Token string
}
func (a authorize) Add(req *http.Request) {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", a.Token))
}
func getTweets(config *Config) ([]*twitter.TweetDictionary, error) {
var results []*twitter.TweetDictionary
client := &twitter.Client{
Authorizer: authorize{
Token: config.TwitterBearerToken,
},
Client: http.DefaultClient,
Host: "https://api.twitter.com",
}
// search for all tweets in the last day, with a max of 100
// we'll ignore pagination for now since its unlikely to be needed for dokku...
opts := twitter.TweetRecentSearchOpts{
MaxResults: 100,
Expansions: []twitter.Expansion{
twitter.ExpansionEntitiesMentionsUserName,
twitter.ExpansionAuthorID,
twitter.ExpansionReferencedTweetsID,
},
StartTime: time.Now().AddDate(0, 0, -1),
TweetFields: []twitter.TweetField{
twitter.TweetFieldCreatedAt,
twitter.TweetFieldConversationID,
twitter.TweetFieldAttachments,
twitter.TweetFieldLanguage,
},
}
tweetResponse, err := client.TweetRecentSearch(context.Background(), config.Tag, opts)
if err != nil {
return results, fmt.Errorf("tweet lookup error: %v", err)
}
// this is rough but many tweets should be ignored in these languages because they refer to either:
// - some pop artist's dog (kpop I think)
// - count dooku (a mispelling from star wars)
// - something crappy (telegu I believe)
// ideally we can parse the entities and tell if its actually about dokku,
// but honestly I don't care too much
ignoreLanguages := map[string]bool{
"es": true,
"et": true,
"ja": true,
"in": true,
"it": true,
}
// ignore anything with these words too
ignoreWords := []string{
"caliphate",
"chennai",
"chatta",
"chettha",
"comte",
"conde",
"disney",
"dokkan",
"hera",
"imarat",
"isis",
"luke",
"kadyrov",
"movie",
"shiseru",
"sushi",
"tamil",
"theatre",
"theater",
"umarov",
}
// ignore these authors completely
ignoreAuthors := []string{"dokku"}
// allow all tweets with these words to go through
allowWords := []string{"caprover", "coolify", "heroku"}
for _, tweet := range tweetResponse.Raw.TweetDictionaries() {
ignore := false
for _, word := range allowWords {
if strings.Contains(strings.ToLower(tweet.Tweet.Text), word) {
results = append(results, tweet)
ignore = true
break
}
}
if ignoreLanguages[tweet.Tweet.Language] {
continue
}
for _, word := range ignoreWords {
if strings.Contains(strings.ToLower(tweet.Tweet.Text), word) {
ignore = true
break
}
}
for _, author := range ignoreAuthors {
if tweet.Author.UserName == author {
ignore = true
break
}
}
// ignore anyone with the tag in the name
if strings.Contains(strings.ToLower(tweet.Author.UserName), config.Tag) {
continue
}
// ignore anyone with the tag in the username
if strings.Contains(strings.ToLower(tweet.Author.Name), config.Tag) {
continue
}
for _, mention := range tweet.Mentions {
if strings.Contains(strings.ToLower(mention.User.UserName), config.Tag) {
ignore = true
break
}
// ignore anyone with the tag in the username
if strings.Contains(strings.ToLower(mention.User.Name), config.Tag) {
ignore = true
break
}
}
// ignore retweets
for _, reference := range tweet.ReferencedTweets {
if reference.Reference.Type == "retweeted" {
ignore = true
break
}
}
if ignore {
continue
}
results = append(results, tweet)
}
return results, nil
}
func sendSlackNotificationForTwitterTweet(result *twitter.TweetDictionary, config *Config) error {
if !config.NotifySlack {
return nil
}
logFields := log.Fields{
"tweet_id": result.Tweet.ID,
}
t, err := time.Parse(time.RFC3339, result.Tweet.CreatedAt)
if err != nil {
return err
}
link := fmt.Sprintf("https://twitter.com/%s/status/%s", result.Author.UserName, result.Tweet.ID)
attachment := slack.Attachment{
Color: "#36a64f",
Fallback: "New tweet on Twitter!",
AuthorName: result.Author.UserName,
AuthorLink: fmt.Sprintf("https://twitter.com/%s", result.Author.UserName),
Title: result.Tweet.Text,
TitleLink: link,
Footer: "Twitter Tweet Notification",
FooterIcon: twitterIconURL,
Ts: json.Number(strconv.FormatInt(int64(t.Unix()), 10)),
}
log.WithFields(logFields).Info("Notifying slack")
messageOpts := []slack.MsgOption{
slack.MsgOptionAsUser(false),
slack.MsgOptionAttachments(attachment),
slack.MsgOptionIconEmoji(":twitter:"),
slack.MsgOptionText("New tweet on <"+link+"|Twitter>", false),
slack.MsgOptionUsername("Twitter Tweet Notifications"),
slack.MsgOptionDisableLinkUnfurl(),
}
api := slack.New(config.SlackToken)
if _, _, err := api.PostMessage(config.SlackChannelID, messageOpts...); err != nil {
return err
}
return nil
}
func processTwitter(config *Config, db *gorm.DB) error {
if err := db.AutoMigrate(&TwitterTweet{}); err != nil {
return fmt.Errorf("error migrating TwitterTweet: %w", err)
}
if config.TwitterBearerToken == "" {
log.Warn("No TWITTER_BEARER_TOKEN specified, skipping twitter")
return nil
}
log.Info("Fetching tweets")
results, err := getTweets(config)
if err != nil {
return err
}
inserted := 0
notified := 0
log.WithField("tweet_count", len(results)).Info("Processing tweets")
for _, result := range results {
logFields := log.Fields{
"tweet_id": result.Tweet.ID,
}
var entity TwitterTweet
if dbResult := db.First(&entity, "tweet_id = ?", result.Tweet.ID); !errors.Is(dbResult.Error, gorm.ErrRecordNotFound) {
continue
}
log.WithFields(logFields).Info("Inserting new tweet")
entity = TwitterTweet{
TweetID: result.Tweet.ID,
}
if dbResult := db.Create(&entity); dbResult.Error != nil {
log.WithError(dbResult.Error).WithFields(logFields).Fatal("error inserting tweet into database")
continue
}
inserted += 1
if err := sendSlackNotificationForTwitterTweet(result, config); err != nil {
log.WithError(err).WithFields(logFields).Fatal("error posting tweet to slack")
continue
}
notified += 1
}
log.WithFields(log.Fields{
"processed_tweet_count": len(results),
"inserted_tweet_count": inserted,
"notified_tweet_count": notified,
}).Info("Done with twitter tweets")
return nil
}