-
Notifications
You must be signed in to change notification settings - Fork 26
/
main.go
416 lines (349 loc) · 11.5 KB
/
main.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
package main
import (
"container/list"
"fmt"
"log"
"math/rand"
"os"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"unicode"
"github.com/bwmarrin/discordgo"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/joho/godotenv"
"github.com/jyap808/go-gemini"
"github.com/ubiq/tars-discord/optionalchannelscmd"
"github.com/ubiq/tars-discord/textcmd"
)
// Variables used for command line parameters
var (
geminiAPIKey = ""
geminiAPISecret = ""
appHomeDir = dcrutil.AppDataDir("ubq-tars-discord", false)
defaultConfigFile = filepath.Join(appHomeDir, "secrets.env")
// Flood
terminatorMemberFlag = false
)
const (
// Flood
floodMemberAddInterval = 3
floodMilliseconds = 60000 // 60 seconds
floodAlertChannel = "504427120236167207"
moderatorRoleID = "348038402148532227"
terminatorTimerSeconds = 60
tradingChannelID = "348036278673211392"
turdRoleID = "1072302088232636436"
verifiedRoleID = "350127755079319552"
)
func checkTradingChannel(channelID string) *string {
message := ""
if channelID != tradingChannelID {
message = fmt.Sprintf("This price related command is only allowed in the <#%s> channel", tradingChannelID)
}
return &message
}
func btcPrice() *string {
message := ""
gemini := gemini.New(geminiAPIKey, geminiAPISecret)
tickerName := "btcusd"
ticker, err := gemini.GetTicker(tickerName)
if err != nil {
log.Println(err)
message = "Error retrieving price from remote API's"
return &message
}
lastPrice := ticker.Last
if err != nil {
log.Println(err)
message = "Error retrieving price from remote API's"
} else {
message = fmt.Sprintf("```Gemini BTC price: %.2f```", lastPrice)
}
return &message
}
func keysString(m map[string]bool) string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
return strings.Join(keys, ", ")
}
func isASCII(s string) bool {
for i := 0; i < len(s); i++ {
if s[i] > unicode.MaxASCII {
return false
}
}
return true
}
func handleMessage(s *discordgo.Session, m *discordgo.MessageCreate) *string {
vals := &m.Content
asciiMatched := isASCII(*vals)
httpMatched, _ := regexp.MatchString(`http`, *vals)
uniSpamMatched, _ := regexp.MatchString(`[uU]n[iⅰ].*a[iⅰ]r[dԁ]rop`, *vals)
axieInfinitySpamMatched, _ := regexp.MatchString(`[aA]x[iⅰ]e.*[iI]nf[iⅰ]n[iⅰ]ty`, *vals)
if ((!asciiMatched && httpMatched) || uniSpamMatched || axieInfinitySpamMatched) && len(m.Member.Roles) == 0 {
go terminateMember(s, m.GuildID, m.Author.ID, "Link spam")
return nil
}
valSplit := strings.Split(*vals, " ")
message := ""
if len(*vals) == 0 {
return nil
}
command := valSplit[0]
arguments := valSplit[1:]
var optionalChannels = map[string]bool{
"decred-stakepool": true,
"gamers": true,
"music": true,
"nsfw": true,
"sports": true,
}
switch command {
case "!price":
channelCheck := *checkTradingChannel(m.ChannelID)
if channelCheck != "" {
message = channelCheck
break
}
if len(arguments) == 0 {
message = "Usage: !price [TICKER]"
break
}
ticker := strings.ToUpper(arguments[0])
// Special case to handle BTC price
if ticker == "BTC" {
message = *btcPrice()
} else {
message = "```Currently only supports BTC price lookups```"
}
// Delete originating message
s.ChannelMessageDelete(m.ChannelID, m.ID)
message = fmt.Sprintf("%sRequested by: %s", message, m.Author.Mention())
// Text commands
// Keep this in alphabetical order. Where possible just use the singular term.
case "!ann", "!backup", "!bots", "!bridge", "!caps", "!commands", "!compare", "!dojo", "!escher", "!escrow", "!ethunits", "!exchange", "!explorer", "!github", "!hide", "!hidechannels", "!invite", "!market", "!miner", "!mp", "!monetarypolicy", "!nft", "!nfts", "!nucleus", "!odin", "!onepage", "!pools", "!quarterly", "!redshift", "!roadmap", "!shinobi", "!site", "!social", "!solidity", "!stats", "!transparency", "!wallet", "!website", "!vyper":
s.ChannelMessageDelete(m.ChannelID, m.ID)
message = fmt.Sprintf("%sRequested by: %s", *textcmd.Commands(command), m.Author.Mention())
case "!join":
usageStr := "**Usage:** !join [OPTIONAL_CHANNEL]\n\n"
usageStr += fmt.Sprintf("**Optional Channels:** %s", keysString(optionalChannels))
if len(arguments) == 0 {
message = usageStr
break
}
channel := strings.ToLower(arguments[0])
channel = strings.TrimPrefix(channel, "#")
if optionalChannels[channel] {
message = *optionalchannelscmd.Join(s, m, channel)
} else {
message = usageStr
}
case "!leave":
usageStr := "**Usage:** !leave [OPTIONAL_CHANNEL]\n\n"
usageStr += fmt.Sprintf("**Optional Channels:** %s", keysString(optionalChannels))
if len(arguments) == 0 {
message = usageStr
break
}
channel := strings.ToLower(arguments[0])
channel = strings.TrimPrefix(channel, "#")
if optionalChannels[channel] {
message = *optionalchannelscmd.Leave(s, m, channel)
} else {
message = usageStr
}
case "!echo":
if len(arguments) == 0 {
message = "Usage: !echo [TEXT]"
}
valSplit2 := strings.SplitN(*vals, " ", 2)
message = fmt.Sprintf("*Echo:* %s", valSplit2[1])
default:
}
return &message
}
func main() {
godotenv.Load(defaultConfigFile)
token := os.Getenv("DISCORD_API_TOKEN")
// Create the home directory if it doesn't already exist.
err := os.MkdirAll(appHomeDir, 0700)
if err != nil {
// Show a nicer error message if it's because a symlink is
// linked to a directory that does not exist (probably because
// it's not mounted).
if e, ok := err.(*os.PathError); ok && os.IsExist(err) {
if link, lerr := os.Readlink(e.Path); lerr == nil {
str := "is symlink %s -> %s mounted?"
err = fmt.Errorf(str, e.Path, link)
}
}
log.Fatalf("Failed to create config directory: %s", err)
}
// Create a new Discord session using the provided bot token.
dg, err := discordgo.New("Bot " + token)
if err != nil {
log.Println("error creating Discord session,", err)
return
}
// Register the messageCreate func as a callback for MessageCreate events.
dg.AddHandler(messageCreate)
dg.AddHandler(guildMemberAdd)
dg.Identify.Intents = discordgo.MakeIntent(discordgo.IntentsGuildMembers | discordgo.IntentsGuildMessages)
// Open a websocket connection to Discord and begin listening.
err = dg.Open()
if err != nil {
log.Println("error opening connection,", err)
return
}
// Wait here until CTRL-C or other term signal is received.
log.Println("Bot is now running. Press CTRL-C to exit.")
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
<-sc
// Cleanly close down the Discord session.
dg.Close()
}
// This function will be called (due to AddHandler above) every time a new
// message is created on any channel that the authenticated bot has access to.
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
// Ignore all messages created by the bot itself
// This isn't required in this specific example but it's a good practice.
if m.Author.ID == s.State.User.ID {
return
}
if len(m.Content) > 0 {
message := handleMessage(s, m)
if message != nil {
s.ChannelMessageSend(m.ChannelID, *message)
}
}
}
var floodStack list.List
type floodCheck struct {
userID string
addTime time.Time
}
func terminateMember(s *discordgo.Session, guildID string, userID string, reason string) {
banUserMessage := fmt.Sprintf("Terminated: <@%s>, Reason: %s", userID, reason)
err := s.GuildBanCreateWithReason(guildID, userID, reason, 1)
if err != nil {
log.Printf("err: +%v\n", err)
} else {
s.ChannelMessageSend(floodAlertChannel, banUserMessage)
}
}
// Originally ported from https://github.com/hugonun/discordid2date/blob/master/main.js#L5
// Binary conversion and manipulation steps have been replaced with a bit shift operation
// to extract the relevant bits representing the timestamp.
func convertIDtoCreationTime(id string) time.Time {
idInt, _ := strconv.ParseInt(id, 10, 64)
unixCreationTime := (idInt >> 22) + 1420070400000
creationTime := time.Unix(0, unixCreationTime*int64(time.Millisecond))
return creationTime
}
func turdTimer(s *discordgo.Session, m *discordgo.GuildMemberAdd) {
if len(m.Roles) == 0 {
// Perform actions for users without roles
turdMessage := fmt.Sprintf("Smelly turd: <@%s> account Unverified after 24 hours", m.User.ID)
s.GuildMemberRoleAdd(m.GuildID, m.User.ID, turdRoleID)
s.ChannelMessageSend(floodAlertChannel, turdMessage)
}
}
// This function is called on GuildMemberAdd event
// Currently just performs Flood handling
func guildMemberAdd(s *discordgo.Session, m *discordgo.GuildMemberAdd) {
// Check and Terminate
if terminatorMemberFlag {
go terminateMember(s, m.GuildID, m.User.ID, "Flood join")
return
}
if checkSpamUsername(s, m) {
return
}
// Check new user Creation Time
memberCreationTime := convertIDtoCreationTime(m.User.ID)
t1 := time.Now()
diff := t1.Sub(memberCreationTime)
if diff.Hours() < 24*30 {
turdMessage := fmt.Sprintf("Smelly turd: <@%s> account created %f hours ago", m.User.ID, diff.Hours())
s.GuildMemberRoleAdd(m.GuildID, m.User.ID, turdRoleID)
s.ChannelMessageSend(floodAlertChannel, turdMessage)
}
if floodStack.Len() < floodMemberAddInterval {
floodStack.PushBack(floodCheck{m.User.ID, time.Now()})
}
if floodStack.Len() == floodMemberAddInterval {
t1 := time.Now()
floodStackFirst := floodStack.Front().Value.(floodCheck)
diff := t1.Sub(floodStackFirst.addTime)
if diff.Milliseconds() < floodMilliseconds {
// Terminate all members in floodStack
terminatorMemberFlag = true
for member := floodStack.Front(); member != nil; member = member.Next() {
go terminateMember(s, m.GuildID, member.Value.(floodCheck).userID, "Flood join")
}
// Set TerminatorTimer
terminatorTimer := time.NewTicker(terminatorTimerSeconds * time.Second)
go func() {
floodMessage := fmt.Sprintf("<@&%s> 🚨 Flood detected. %d Joins in %.1f seconds", moderatorRoleID, floodMemberAddInterval, diff.Seconds())
s.ChannelMessageSend(floodAlertChannel, floodMessage)
<-terminatorTimer.C
terminatorMemberFlag = false
terminatorQuotes := []string{"You just can't go around killing people",
"Your foster parents are dead",
"Hasta la vista, baby",
"My mission is to protect you",
"Come with me if you want to live"}
terminatorOffMessage := fmt.Sprintf("Terminator OFF - %s", terminatorQuotes[rand.Intn(len(terminatorQuotes))])
s.ChannelMessageSend(floodAlertChannel, terminatorOffMessage)
}()
// Clear floodStack
floodStack.Init()
} else {
floodStack.Remove(floodStack.Front())
floodStack.PushBack(floodCheck{m.User.ID, time.Now()})
}
}
// Run a 24-hour timer for the user, calling turdTimer after 24 hours
go func() {
time.Sleep(24 * time.Hour)
turdTimer(s, m)
}()
}
// Check if the username matches any of the given patterns
func isUsernameSpam(username string, patterns []string) bool {
for _, pattern := range patterns {
matched, _ := regexp.MatchString(pattern, username)
if matched {
return true
}
}
return false
}
// Check for spam usernames and terminate member if conditions are met
func checkSpamUsername(s *discordgo.Session, m *discordgo.GuildMemberAdd) bool {
patterns := []string{
`(?i)Admin`,
`(?i)Announcement`,
`(?i)[CС][aа][pр]t[cс]h[aа]`,
`(?i)FAQ`,
`(?i)Giveaway`,
`(?i)Helpdesk`,
`(?i)Manager`,
`(?i)MEE6`,
`(?i)Support`,
}
username := m.User.Username
if isUsernameSpam(username, patterns) && len(m.Roles) == 0 {
go terminateMember(s, m.GuildID, m.User.ID, "Username spam")
return true
}
return false
}