This repository has been archived by the owner on Mar 30, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
214 lines (176 loc) · 5.15 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
package main
import (
"CrackWatchDiscordBot/crackwatch"
"errors"
"flag"
"fmt"
"log"
"math"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
"unicode"
"github.com/bwmarrin/discordgo"
"golang.org/x/text/language"
"golang.org/x/text/message"
)
var (
discordBotToken = flag.String("token", "", "Discord bot token.")
botCommand = flag.String("command", "!crack", "Message prefix to"+
" activate the bot. Can't contain spaces.")
)
type guildID = string
var discordMsgLock = map[guildID]*sync.Mutex{}
func main() {
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
if err := parseFlags(); err != nil {
log.Fatalln("Error while parsing flags: " + err.Error())
}
discordBot, err := newDiscordBot(*discordBotToken)
if err != nil {
log.Fatalln("Unable to create Discord bot: " + err.Error())
}
defer discordBot.Close()
discordBot.AddHandler(onMessageReceived)
waitForSignal()
}
func parseFlags() error {
flag.Parse()
if *discordBotToken == "" {
return errors.New("A Discord bot token is required in order for this" +
" application to function.")
}
for _, run := range *botCommand {
if unicode.IsSpace(run) {
return errors.New("botCommand has a space in it, which will break" +
" parsing!")
}
}
return nil
}
// NOTE: Be sure to run .Close() on the bot session once you're done using it.
func newDiscordBot(token string) (*discordgo.Session, error) {
discordSession, err := discordgo.New("Bot " + token)
if err != nil {
return nil, errors.New("Unable to create the Discord session: " +
err.Error())
}
if err = discordSession.Open(); err != nil {
return nil, errors.New("Unable to open the Discord session: " +
err.Error())
}
return discordSession, nil
}
func onMessageReceived(s *discordgo.Session, m *discordgo.MessageCreate) {
// Ignore own messages.
if m.Author.ID == s.State.User.ID {
return
}
messageFields := strings.Fields(strings.ToLower(m.Content))
if len(messageFields) < 2 ||
!strings.HasPrefix(messageFields[0], *botCommand) {
return
}
page := 0
if len(messageFields[0]) > len(*botCommand) {
pageStr := messageFields[0][len(*botCommand):]
pageInt, err := strconv.Atoi(pageStr)
if err != nil {
sendDiscordMessage(s, m, "You've entered an incorrect page number.")
return
}
page = pageInt - 1
}
searchTerm := strings.Join(messageFields[1:], " ")
searchResults, err := crackwatch.Search(searchTerm, page)
if err != nil {
sendDiscordMessage(s, m, "Couldn't connect to crackwatch.com—please "+
"try again later!")
return
} else if len(searchResults.Games) == 0 {
sendDiscordMessage(s, m, "No games found which matched your query!")
return
}
for _, messageChunk := range resultsToDiscordChunks(searchResults, page+1) {
sendDiscordMessage(s, m, messageChunk)
}
}
func resultsToDiscordChunks(
searchResults crackwatch.SearchResults, pageNum int,
) []string {
var strBuilder strings.Builder
for i, game := range searchResults.Games {
// Game hasn't been cracked yet.
if game.CrackDate.IsZero() {
numFollowersStr := message.NewPrinter(language.English).
Sprintf("%d", game.NumFollowers)
peopleStr := "people"
if game.NumFollowers == 1 {
peopleStr = "person"
}
strBuilder.WriteString(
fmt.Sprintf("🛑%q has %s %s waiting for a crack!",
game.Name, numFollowersStr, peopleStr),
)
if i != len(searchResults.Games)-1 {
strBuilder.WriteString("\n")
}
continue
}
strBuilder.WriteString(
fmt.Sprintf("🟢%s | %s | %s | %s | %s",
game.Name, game.ReleaseDate,
crackwatch.NormalizeDRMNames(game.DRM),
strings.Join(game.CrackedBy, "/"),
game.CrackDate),
)
if i != len(searchResults.Games)-1 {
strBuilder.WriteString("\n")
}
}
const crackWatchMaxNumResults float64 = 30
footer := fmt.Sprintf("\nPage %d/%.0f```",
pageNum,
math.Ceil(float64(searchResults.Num)/crackWatchMaxNumResults))
const discordMaxMsgLen = 2000
const header = "```Game Name | Release Date | DRM | Cracked By | Date" +
" Cracked\n"
maxMsgLen := discordMaxMsgLen - len(header+footer)
msg := strBuilder.String()
messageChunks := []string{}
for len(msg) > maxMsgLen {
idxLastNewline := strings.LastIndex(msg[:maxMsgLen], "\n")
messageChunks = append(messageChunks,
header+msg[:idxLastNewline]+footer)
// +1 to skip the newline character.
msg = msg[idxLastNewline+1:]
}
messageChunks = append(messageChunks, header+msg+footer)
return messageChunks
}
func sendDiscordMessage(
s *discordgo.Session, m *discordgo.MessageCreate, msg string,
) {
mutex, ok := discordMsgLock[m.GuildID]
if !ok {
discordMsgLock[m.GuildID] = &sync.Mutex{}
mutex = discordMsgLock[m.GuildID]
}
mutex.Lock()
// We purposely ignore all errors when sending messages to Discord, since in
// the rare worst-case scenario, the user just has to send another query.
_, _ = s.ChannelMessageSend(m.ChannelID, msg)
time.Sleep(time.Second)
mutex.Unlock()
}
func waitForSignal() {
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
fmt.Printf(time.Now().Format("2006-01-02 @ 15:04:05 MST ")+
"CrackWatchDiscordBot has shut down due to the %q signal being caught."+
"\n", <-signalChan)
}