/
creepydm.go
327 lines (270 loc) · 8.21 KB
/
creepydm.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
package kardbot
import (
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"sync"
"time"
"github.com/TannerKvarfordt/Kard-bot/kardbot/config"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus"
)
const (
creepyDMGet = "get-creepy-dm"
creepyChannelDM = "to-channel"
creepyDMOptIn = "opt-in"
creepyDMOptOut = "opt-out"
defaultCreepyDMOdds float32 = 0.5
)
var (
// Creepy DM subscribers
// key: discord user ID
// val: is currently subscribed
creepyDMSubs map[string]bool
creepyDMSubsMutex sync.RWMutex
// Odds [0.0, 1.0] that the user will receive
// a creepy DM on any given day.
creepyDMOdds float32
// List of creepy DMs
creepyDMs []string
)
type creepyDmSubscribersConfig struct {
Subs map[string]bool `json:"creepy-dm-subscribers"`
Odds float32 `json:"creepy-dm-odds"`
}
const creepyDmSubscribersFilepath = "config/creepy-dm-subscribers.json"
var creepyDmSubscribersFileMutex sync.RWMutex
func init() {
creepyDmSubscribersFileMutex.RLock()
defer creepyDmSubscribersFileMutex.RUnlock()
creepyDMSubsMutex.Lock()
defer creepyDMSubsMutex.Unlock()
cfg := creepyDmSubscribersConfig{}
cfg.Odds = defaultCreepyDMOdds
jsonCfg, err := config.NewJsonConfig(creepyDmSubscribersFilepath)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(jsonCfg.Raw, &cfg)
if err != nil {
log.Fatal(err)
}
creepyDMOdds = cfg.Odds
creepyDMSubs = cfg.Subs
if creepyDMOdds < 0.0 || creepyDMOdds > 1.0 {
log.Fatalf("creepyDMOdds configuration value (%f) is out of range. Valid values are [0.0, 1.0]", creepyDMOdds)
}
if creepyDMOdds < 0.01 {
log.Warn("creepyDMOdds set at less than 1%")
}
}
const creepyDmListFilepath = "config/creepy-dms.json"
func init() {
cfg := struct {
CreepyDMs []string `json:"creepy-dms"`
}{}
jsonCfg, err := config.NewJsonConfig(creepyDmListFilepath)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(jsonCfg.Raw, &cfg)
if err != nil {
log.Fatal(err)
}
creepyDMs = cfg.CreepyDMs
}
func creepyDMHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
wg := bot().updateLastActive()
defer wg.Wait()
if s == nil || i == nil {
log.Errorf("nil session or interaction; s=%v, i=%v", s, i)
return
}
var err error
switch i.ApplicationCommandData().Options[0].Name {
case creepyDMGet:
err = getCreepyDM(s, i)
case creepyDMOptIn:
err = creepyDMsOptIn(s, i)
case creepyDMOptOut:
err = creepyDMsOptOut(s, i)
default:
err = fmt.Errorf("unknown subcommand")
}
if err != nil {
log.Error(err)
interactionRespondEphemeralError(s, i, true, err)
}
}
func creepyDMsOptIn(s *discordgo.Session, i *discordgo.InteractionCreate) error {
metadata, err := getInteractionMetaData(i)
if err != nil {
return err
}
creepyDMSubsMutex.Lock()
creepyDMSubs[metadata.AuthorID] = true
creepyDMSubsMutex.Unlock()
err = writeCreepyDmSubscribersToConfig()
if err != nil {
err = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: fmt.Sprintf("%s, you are subscribed to creepy DMs as long as the bot remains up, but there was an error persisting your subscription. Please try to opt-in again.", metadata.AuthorUsername),
Flags: InteractionResponseFlagEphemeral,
},
})
if err != nil {
return err
}
return nil
}
return s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: fmt.Sprintf("%s subscribed to creepy DMs 😈", metadata.AuthorUsername),
},
})
}
func creepyDMsOptOut(s *discordgo.Session, i *discordgo.InteractionCreate) error {
metadata, err := getInteractionMetaData(i)
if err != nil {
return err
}
creepyDMSubsMutex.Lock()
creepyDMSubs[metadata.AuthorID] = false
creepyDMSubsMutex.Unlock()
err = writeCreepyDmSubscribersToConfig()
if err != nil {
err = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: fmt.Sprintf("%s, you are unsubscribed to creepy DMs as long as the bot remains up, but there was an error persisting your opt-out. Please try to opt-out again.", metadata.AuthorUsername),
},
})
if err != nil {
return err
}
return nil
}
return s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: fmt.Sprintf("%s unsubscribed from creepy DMs 👿", metadata.AuthorUsername),
},
})
}
func getCreepyDM(s *discordgo.Session, i *discordgo.InteractionCreate) error {
msg := creepyDMs[rand.Intn(len(creepyDMs))]
sendToChannel := false
if len(i.ApplicationCommandData().Options[0].Options) > 0 {
sendToChannel = i.ApplicationCommandData().Options[0].Options[0].BoolValue()
}
if sendToChannel {
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: msg,
},
})
if err != nil {
return err
}
return nil
}
metadata, err := getInteractionMetaData(i)
if err != nil {
return err
}
uc, err := s.UserChannelCreate(metadata.AuthorID)
if err != nil {
return err
}
_, err = s.ChannelMessageSend(uc.ID, msg)
if err != nil {
return err
}
log.Tracef("Sent %s a creepy DM", metadata.AuthorUsername)
time.Sleep(time.Millisecond * 250) // sleep a bit for the initial response to be received
return s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Sent you a creepy DM 😈",
Flags: InteractionResponseFlagEphemeral,
},
})
}
// sendCreepyDMs is run every day. It spawns a goroutine for each
// subscriber and randomly decides whether or not said subscriber
// will receive creepy-PM that day. If so the goroutine sleeps
// for a random amount of time, not exceeding 24 hours, before
// sending the DM.
func sendCreepyDMs() {
wg := sync.WaitGroup{}
defer wg.Wait()
creepyDMSubsMutex.RLock()
// Defers are LIFO; this MUST happen prior to wg.Wait
// or any subscribe/unsubscribe commands will be deadlocked.
defer creepyDMSubsMutex.RUnlock()
// Made this an anonymous inner function so that I wouldn't
// accidentally use an uncopied value from bot().CreepyDMSubs
// after the mutex is released.
sendDM := func(subID string) error {
user, err := bot().Session.User(subID)
if err != nil {
return err
}
if rand.Float32() > creepyDMOdds {
log.Infof("%s escaped a creepy DM this time...", user.Username)
return nil
}
log.Infof("%s will get a creepy DM today >:) (unless they unsubscribe before we send it)", user.Username)
const minutesPerDay = 1440
time.Sleep(time.Minute * time.Duration(rand.Intn(minutesPerDay)))
activeWG := bot().updateLastActive()
defer activeWG.Wait()
if !isSubbedToCreepyDMs(subID, user.Username) {
log.Infof("%s has unsubbed from creepy DMs since this routine started", user.Username)
return nil
}
dm := creepyDMs[rand.Intn(len(creepyDMs))]
uc, err := bot().Session.UserChannelCreate(subID)
if err != nil {
return err
}
_, err = bot().Session.ChannelMessageSend(uc.ID, dm)
return err
}
for subscriberID := range creepyDMSubs {
wg.Add(1)
go func(subID string) {
defer wg.Done()
if err := sendDM(subID); err != nil {
log.Error(err)
}
}(subscriberID)
}
}
func isSubbedToCreepyDMs(subscriberID, subscriberName string) bool {
creepyDMSubsMutex.RLock()
defer creepyDMSubsMutex.RUnlock()
if ok, isSubbed := creepyDMSubs[subscriberID]; !ok || !isSubbed {
return false
}
return true
}
func writeCreepyDmSubscribersToConfig() error {
creepyDmSubscribersFileMutex.Lock()
defer creepyDmSubscribersFileMutex.Unlock()
creepyDMSubsMutex.RLock()
defer creepyDMSubsMutex.RUnlock()
cfg := creepyDmSubscribersConfig{
Subs: creepyDMSubs,
Odds: creepyDMOdds,
}
fileBytes, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return err
}
return ioutil.WriteFile(creepyDmSubscribersFilepath, fileBytes, 0664)
}