forked from Southclaws/cj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot_commands.go
331 lines (293 loc) · 10.5 KB
/
bot_commands.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
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"time"
"go.uber.org/zap"
"fmt"
"github.com/bwmarrin/discordgo"
gocache "github.com/patrickmn/go-cache"
)
// LoadCommands is called on initialisation and is responsible for registering
// all commands and binding them to functions.
func LoadCommands(app *App) map[string]Command {
return map[string]Command{
"verify": {
Function: commandVerify,
Source: CommandSourcePRIVATE,
Description: "Verify you are the owner of a SA:MP forum account",
Usage: "verify",
ParametersRange: CommandParametersRange{
Minimum: -1,
Maximum: -1,
},
RequireVerified: false,
RequireAdmin: false,
Context: true,
},
"/say": {
Function: commandSay,
Source: CommandSourceADMINISTRATIVE,
Description: app.locale.GetLangString("en", "CommandSayDescription"),
Usage: "/say [text]",
Example: "/say Hello!",
ParametersRange: CommandParametersRange{
Minimum: 1,
Maximum: -1,
},
RequireVerified: false,
RequireAdmin: false,
Context: false,
},
"/userinfo": {
Function: commandUserInfo,
Source: CommandSourcePRIMARY,
Description: app.locale.GetLangString("en", "CommandUserInfoDescription"),
Usage: "/userinfo [user(s)]",
Example: "/userinfo @Southclaws#1657",
ParametersRange: CommandParametersRange{
Minimum: 1,
Maximum: 5,
},
ErrorMessage: app.locale.GetLangString("en", "CommandErrorNoMention"),
RequireVerified: true,
RequireAdmin: false,
Context: false,
},
"/whois": {
Function: commandWhois,
Source: CommandSourcePRIMARY,
Description: app.locale.GetLangString("en", "CommandWhoisDescription", "%s"),
Usage: "/whois [user(s)]",
Example: "/whois @Southclaws#1657",
ParametersRange: CommandParametersRange{
Minimum: 1,
Maximum: 5,
},
ErrorMessage: app.locale.GetLangString("en", "CommandErrorNoMention"),
RequireVerified: true,
RequireAdmin: false,
Context: false,
},
"cj": {
Function: commandCJQuote,
Source: CommandSourcePRIMARY,
Description: "",
Usage: "cj",
ParametersRange: CommandParametersRange{
Minimum: -1,
Maximum: -1,
},
ErrorMessage: app.locale.GetLangString("en", "CommandErrorNoMention", "%s"),
RequireVerified: true,
RequireAdmin: false,
Context: false,
},
}
}
// CommandSource represents the source of a command.
type CommandSource int8
const (
// CommandSourceADMINISTRATIVE are commands in the administrator channel,
// mainly for admin work that may clutter up the primary channel.
CommandSourceADMINISTRATIVE CommandSource = iota
// CommandSourcePRIMARY are primary channel commands visible to all users
// and mainly used for fun and group activity commands.
CommandSourcePRIMARY CommandSource = iota
// CommandSourcePRIVATE are private channel commands for dealing with
// sensitive information such as verification.
CommandSourcePRIVATE CommandSource = iota
// CommandSourceOTHER represents any other channel that does not fall into
// the above sources.
CommandSourceOTHER CommandSource = iota
)
// CommandManager stores command state
type CommandManager struct {
App *App
Commands map[string]Command
Contexts *gocache.Cache
}
// CommandParametersRange represents minimum value and maximum value number of parameters for a command
type CommandParametersRange struct {
Minimum int
Maximum int
}
// Command represents a public, private or administrative command
type Command struct {
commandManager *CommandManager
Function func(cm CommandManager, args string, message discordgo.Message, contextual bool) (bool, bool, error)
Source CommandSource
ParametersRange CommandParametersRange
Description string
Usage string
Example string
ErrorMessage string
RequireVerified bool
RequireAdmin bool
Context bool
}
// StartCommandManager creates a command manager for the app
func (app *App) StartCommandManager() {
app.commandManager = &CommandManager{
App: app,
Commands: make(map[string]Command),
Contexts: gocache.New(5*time.Minute, 30*time.Second),
}
app.commandManager.Commands = LoadCommands(app)
}
// Process is called on a command string to check whether it's a valid command
// and, if so, call the associated function.
// nolint:gocyclo
func (cm CommandManager) Process(message discordgo.Message) (exists bool, source CommandSource, errs []error) {
var err error
source = cm.getCommandSource(message.ChannelID)
contextCommand, found := cm.Contexts.Get(message.Author.ID)
if found {
contextCommand := contextCommand.(Command)
if contextCommand.Source == source {
var continueContext bool
continueContext, errs = cm.ProcessContext(contextCommand, message.Content, message)
if !continueContext {
cm.Contexts.Delete(message.Author.ID)
}
return true, source, errs
}
}
commandAndParameters := strings.SplitN(message.Content, " ", 2)
commandParametersCount := 0
commandTrigger := strings.ToLower(commandAndParameters[0])
commandArgument := ""
if len(commandAndParameters) > 1 {
commandArgument = commandAndParameters[1]
commandParametersCount = strings.Count(commandArgument, " ") + 1
}
commandObject, exists := cm.Commands[commandTrigger]
commandObject.commandManager = &cm
if !exists {
return exists, source, nil
}
if source == commandObject.Source {
switch source {
case CommandSourceADMINISTRATIVE:
if message.ChannelID != cm.App.config.AdministrativeChannel {
return exists, source, errs
}
case CommandSourcePRIMARY:
if message.ChannelID != cm.App.config.PrimaryChannel {
return exists, source, errs
}
}
// Check if the user is an administrator.
if commandObject.RequireAdmin && cm.App.config.Admin != message.Author.ID {
_, err = cm.App.discordClient.ChannelMessageSend(message.ChannelID, cm.App.locale.GetLangString("en", "CommandRequireAdministrator", message.Author.ID))
if err != nil {
errs = append(errs, err)
}
return exists, source, errs
}
// Check if the user is verified.
verified, err := cm.App.IsUserVerified(message.Author.ID)
if err != nil {
errs = append(errs, err)
return exists, source, errs
}
if commandObject.RequireVerified && !verified {
_, err = cm.App.discordClient.ChannelMessageSend(message.ChannelID, cm.App.locale.GetLangString("en", "CommandRequireVerification", message.Author.ID))
if err != nil {
errs = append(errs, err)
}
return exists, source, errs
}
// Check if we have the required number of parameters.
if commandObject.ParametersRange.Minimum > -1 && commandParametersCount < commandObject.ParametersRange.Minimum {
_, err = cm.App.discordClient.ChannelMessageSend(message.ChannelID, cm.App.locale.GetLangString("en", "CommandUsageTemplate", commandObject.Usage, commandObject.Description, commandObject.Example))
if err != nil {
errs = append(errs, err)
}
return exists, source, errs
} else if commandObject.ParametersRange.Maximum > -1 && commandParametersCount > commandObject.ParametersRange.Maximum {
_, err = cm.App.discordClient.ChannelMessageSend(message.ChannelID, cm.App.locale.GetLangString("en", "TooManyParameters", commandObject.ParametersRange.Maximum))
if err != nil {
errs = append(errs, err)
}
return exists, source, errs
}
var (
success bool
enterContext bool
)
// Execute the command.
success, enterContext, err = commandObject.Function(cm, commandArgument, message, false)
errs = append(errs, err)
if enterContext {
if commandObject.Context {
cm.Contexts.Set(message.Author.ID, commandObject, gocache.DefaultExpiration)
}
}
if !success {
if commandObject.ErrorMessage != "" {
// Format it if we have a mention in the error message.
if strings.Contains(commandObject.ErrorMessage, "<@%s>") {
_, err = cm.App.discordClient.ChannelMessageSend(message.ChannelID, fmt.Sprintf(commandObject.ErrorMessage, message.Author.ID))
} else {
_, err = cm.App.discordClient.ChannelMessageSend(message.ChannelID, commandObject.ErrorMessage)
}
errs = append(errs, err)
} else {
_, err = cm.App.discordClient.ChannelMessageSend(message.ChannelID, cm.App.locale.GetLangString("en", "CommandUsageTemplate", commandObject.Usage, commandObject.Description, commandObject.Example))
if err != nil {
errs = append(errs, err)
}
return exists, source, errs
}
}
}
return exists, source, errs
}
// ProcessContext re-runs a Command function if the user is currently in a
// Command's context.
func (cm CommandManager) ProcessContext(command Command, cmdtext string, message discordgo.Message) (continueContext bool, errs []error) {
_, continueContext, err := command.Function(cm, cmdtext, message, true)
if err != nil {
errs = append(errs, err)
}
return continueContext, errs
}
func (cm CommandManager) getCommandSource(channel string) CommandSource {
if channel == cm.App.config.AdministrativeChannel {
return CommandSourceADMINISTRATIVE
} else if channel == cm.App.config.PrimaryChannel {
return CommandSourcePRIMARY
} else {
// discordgo has not implemented private channel objects (DM Channels)
// so we have to perform the request manually and unmarshal the response
// object into a `ChannelDM` object.
var err error
var req *http.Request
var response *http.Response
var body []byte
if req, err = http.NewRequest("GET", discordgo.EndpointChannel(channel), nil); err != nil {
logger.Warn("failed to get discord API", zap.Error(err))
}
req.Header.Add("Authorization", "Bot "+cm.App.config.DiscordToken)
if response, err = cm.App.httpClient.Do(req); err != nil {
logger.Warn("failed to authorise against discord API", zap.Error(err))
}
if body, err = ioutil.ReadAll(response.Body); err != nil {
logger.Warn("failed to read response", zap.Error(err))
}
channel := ChannelDM{}
err = json.Unmarshal(body, &channel)
if err != nil {
logger.Warn("failed to unmarshal response", zap.Error(err))
}
// Now we have one of these:
// https://discordapp.com/developers/docs/resources/channel#dm-channel-object
if channel.Private {
return CommandSourcePRIVATE
}
}
return CommandSourceOTHER
}