forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redditbot.go
310 lines (253 loc) · 7.58 KB
/
redditbot.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
package reddit
import (
"context"
"fmt"
"html"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/jonas747/discordgo"
"github.com/jonas747/go-reddit"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/common/config"
"github.com/jonas747/yagpdb/common/mqueue"
"github.com/jonas747/yagpdb/reddit/models"
"github.com/sirupsen/logrus"
"github.com/volatiletech/sqlboiler/queries/qm"
"golang.org/x/oauth2"
)
const (
MaxPostsHourFast = 200
MaxPostsHourSlow = 200
)
var (
confClientID = config.RegisterOption("yagpdb.reddit.clientid", "Client ID for the reddit api application", "")
confClientSecret = config.RegisterOption("yagpdb.reddit.clientsecret", "Client Secret for the reddit api application", "")
confRedirectURI = config.RegisterOption("yagpdb.reddit.redirect", "Redirect URI for the reddit api application", "")
confRefreshToken = config.RegisterOption("yagpdb.reddit.refreshtoken", "RefreshToken for the reddit api application, you need to ackquire this manually, should be set to permanent", "")
feedLock sync.Mutex
fastFeed *PostFetcher
slowFeed *PostFetcher
)
func (p *Plugin) StartFeed() {
go p.runBot()
}
func (p *Plugin) StopFeed(wg *sync.WaitGroup) {
wg.Add(1)
feedLock.Lock()
if fastFeed != nil {
ff := fastFeed
go func() {
ff.StopChan <- wg
}()
fastFeed = nil
} else {
wg.Done()
}
if slowFeed != nil {
sf := slowFeed
go func() {
sf.StopChan <- wg
}()
slowFeed = nil
} else {
wg.Done()
}
feedLock.Unlock()
}
func UserAgent() string {
return fmt.Sprintf("YAGPDB:%s:%s (by /u/jonas747)", confClientID.GetString(), common.VERSIONNUMBER)
}
func setupClient() *reddit.Client {
authenticator := reddit.NewAuthenticator(UserAgent(), confClientID.GetString(), confClientSecret.GetString(), confRedirectURI.GetString(),
"a", reddit.ScopeEdit+" "+reddit.ScopeRead)
redditClient := authenticator.GetAuthClient(&oauth2.Token{RefreshToken: confRefreshToken.GetString()}, UserAgent())
return redditClient
}
func (p *Plugin) runBot() {
feedLock.Lock()
if os.Getenv("YAGPDB_REDDIT_FAST_FEED_DISABLED") == "" {
fastFeed = NewPostFetcher(p.redditClient, false, NewPostHandler(false))
go fastFeed.Run()
}
slowFeed = NewPostFetcher(p.redditClient, true, NewPostHandler(true))
go slowFeed.Run()
feedLock.Unlock()
}
type PostHandlerImpl struct {
Slow bool
ratelimiter *Ratelimiter
}
func NewPostHandler(slow bool) PostHandler {
rl := NewRatelimiter()
go rl.RunGCLoop()
return &PostHandlerImpl{
Slow: slow,
ratelimiter: rl,
}
}
func (p *PostHandlerImpl) HandleRedditPosts(links []*reddit.Link) {
for _, v := range links {
if strings.EqualFold(v.Selftext, "[removed]") || strings.EqualFold(v.Selftext, "[deleted]") {
continue
}
if !v.IsRobotIndexable {
continue
}
// since := time.Since(time.Unix(int64(v.CreatedUtc), 0))
// logger.Debugf("[%5.2fs %6s] /r/%-20s: %s", since.Seconds(), v.ID, v.Subreddit, v.Title)
p.handlePost(v, 0)
}
}
func (p *PostHandlerImpl) handlePost(post *reddit.Link, filterGuild int64) error {
// createdSince := time.Since(time.Unix(int64(post.CreatedUtc), 0))
// logger.Printf("[%5.1fs] /r/%-15s: %s, %s", createdSince.Seconds(), post.Subreddit, post.Title, post.ID)
qms := []qm.QueryMod{
models.RedditFeedWhere.Subreddit.EQ(strings.ToLower(post.Subreddit)),
models.RedditFeedWhere.Slow.EQ(p.Slow),
models.RedditFeedWhere.Disabled.EQ(false),
}
if filterGuild > 0 {
qms = append(qms, models.RedditFeedWhere.GuildID.EQ(filterGuild))
}
config, err := models.RedditFeeds(qms...).AllG(context.Background())
if err != nil {
logger.WithError(err).Error("failed retrieving reddit feeds for subreddit")
return err
}
// Get the configs that listens to this subreddit, if any
filteredItems := p.FilterFeeds(config, post)
// No channels nothing to do...
if len(filteredItems) < 1 {
return nil
}
logger.WithFields(logrus.Fields{
"num_channels": len(filteredItems),
"subreddit": post.Subreddit,
}).Debug("Found matched reddit post")
message, embed := CreatePostMessage(post)
for _, item := range filteredItems {
idStr := strconv.FormatInt(item.ID, 10)
webhookUsername := "r/" + post.Subreddit + " • YAGPDB"
if item.UseEmbeds {
mqueue.QueueMessageWebhook("reddit", idStr, item.GuildID, item.ChannelID, "", embed, true, webhookUsername)
} else {
mqueue.QueueMessageWebhook("reddit", idStr, item.GuildID, item.ChannelID, message, nil, true, webhookUsername)
}
if common.Statsd != nil {
go common.Statsd.Count("yagpdb.reddit.matches", 1, []string{"subreddit:" + post.Subreddit, "guild:" + strconv.FormatInt(item.GuildID, 10)}, 1)
}
}
return nil
}
func (p *PostHandlerImpl) FilterFeeds(feeds []*models.RedditFeed, post *reddit.Link) []*models.RedditFeed {
filteredItems := make([]*models.RedditFeed, 0, len(feeds))
OUTER:
for _, c := range feeds {
// remove duplicates
for _, v := range filteredItems {
if v.ChannelID == c.ChannelID {
continue OUTER
}
}
limit := MaxPostsHourFast
if p.Slow {
limit = MaxPostsHourSlow
}
// apply ratelimiting
if !p.ratelimiter.CheckIncrement(time.Now(), c.GuildID, limit) {
continue
}
if post.Over18 && c.FilterNSFW == FilterNSFWIgnore {
// NSFW and we ignore nsfw posts
continue
} else if !post.Over18 && c.FilterNSFW == FilterNSFWRequire {
// Not NSFW and we only care about nsfw posts
continue
}
if p.Slow {
if post.Score < c.MinUpvotes {
// less than required upvotes
continue
}
}
filteredItems = append(filteredItems, c)
}
return filteredItems
}
func CreatePostMessage(post *reddit.Link) (string, *discordgo.MessageEmbed) {
plainMessage := fmt.Sprintf("**%s**\n*by %s (<%s>)*\n",
html.UnescapeString(post.Title), post.Author, "https://redd.it/"+post.ID)
plainBody := ""
if post.IsSelf {
plainBody = common.CutStringShort(html.UnescapeString(post.Selftext), 250)
} else {
plainBody = post.URL
}
if post.Spoiler {
plainMessage += "|| " + plainBody + " ||"
} else {
plainMessage += plainBody
}
embed := &discordgo.MessageEmbed{
Author: &discordgo.MessageEmbedAuthor{
URL: "https://reddit.com/u/" + post.Author,
Name: post.Author,
},
Provider: &discordgo.MessageEmbedProvider{
Name: "Reddit",
URL: "https://reddit.com",
},
Description: "**" + html.UnescapeString(post.Title) + "**\n",
}
embed.URL = "https://redd.it/" + post.ID
if post.IsSelf {
embed.Title = "New self post"
if post.Spoiler {
embed.Description += "|| " + common.CutStringShort(html.UnescapeString(post.Selftext), 250) + " ||"
} else {
embed.Description += common.CutStringShort(html.UnescapeString(post.Selftext), 250)
}
embed.Color = 0xc3fc7e
} else {
embed.Color = 0x718aed
embed.Title = "New link post"
embed.Description += post.URL
if post.Media.Type == "" && !post.Spoiler {
embed.Image = &discordgo.MessageEmbedImage{
URL: post.URL,
}
}
}
if post.Spoiler {
embed.Title += " [spoiler]"
}
plainMessage = common.EscapeSpecialMentions(plainMessage)
return plainMessage, embed
}
type RedditIdSlice []string
// Len is the number of elements in the collection.
func (r RedditIdSlice) Len() int {
return len(r)
}
// Less reports whether the element with
// index i should sort before the element with index j.
func (r RedditIdSlice) Less(i, j int) bool {
a, err1 := strconv.ParseInt(r[i], 36, 64)
b, err2 := strconv.ParseInt(r[j], 36, 64)
if err1 != nil {
logger.WithError(err1).Error("Failed parsing id")
}
if err2 != nil {
logger.WithError(err2).Error("Failed parsing id")
}
return a > b
}
// Swap swaps the elements with indexes i and j.
func (r RedditIdSlice) Swap(i, j int) {
temp := r[i]
r[i] = r[j]
r[j] = temp
}