/
customcommands.go
349 lines (281 loc) · 8.26 KB
/
customcommands.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
package customcommands
//go:generate sqlboiler --no-hooks psql
import (
"context"
"encoding/json"
"fmt"
"sort"
"strings"
"github.com/jonas747/discordgo"
"github.com/jonas747/dstate"
"github.com/jonas747/retryableredis"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/customcommands/models"
"github.com/jonas747/yagpdb/premium"
"github.com/jonas747/yagpdb/web"
"github.com/karlseguin/ccache"
"github.com/volatiletech/null"
)
var (
RegexCache = *ccache.New(ccache.Configure())
logger = common.GetPluginLogger(&Plugin{})
)
func KeyCommands(guildID int64) string { return "custom_commands:" + discordgo.StrID(guildID) }
type Plugin struct{}
func RegisterPlugin() {
common.InitSchema(DBSchema, "customcommands")
plugin := &Plugin{}
common.RegisterPlugin(plugin)
}
func (p *Plugin) PluginInfo() *common.PluginInfo {
return &common.PluginInfo{
Name: "Custom Commands",
SysName: "custom_commands",
Category: common.PluginCategoryCore,
}
}
type CommandTriggerType int
const (
CommandTriggerCommand CommandTriggerType = 0
CommandTriggerStartsWith CommandTriggerType = 1
CommandTriggerContains CommandTriggerType = 2
CommandTriggerRegex CommandTriggerType = 3
CommandTriggerExact CommandTriggerType = 4
CommandTriggerInterval CommandTriggerType = 5
)
var (
AllTriggerTypes = []CommandTriggerType{
CommandTriggerCommand,
CommandTriggerStartsWith,
CommandTriggerContains,
CommandTriggerRegex,
CommandTriggerExact,
CommandTriggerInterval,
}
triggerStrings = map[CommandTriggerType]string{
CommandTriggerCommand: "Command",
CommandTriggerStartsWith: "StartsWith",
CommandTriggerContains: "Contains",
CommandTriggerRegex: "Regex",
CommandTriggerExact: "Exact",
CommandTriggerInterval: "Interval",
}
)
func (t CommandTriggerType) String() string {
return triggerStrings[t]
}
type CustomCommand struct {
TriggerType CommandTriggerType `json:"trigger_type"`
TriggerTypeForm string `json:"-" schema:"type"`
Trigger string `json:"trigger" schema:"trigger" valid:",0,1000"`
// TODO: Retire the legacy Response field.
Response string `json:"response,omitempty" schema:"response" valid:"template,10000"`
Responses []string `json:"responses" schema:"responses" valid:"template,10000"`
CaseSensitive bool `json:"case_sensitive" schema:"case_sensitive"`
ID int64 `json:"id"`
ContextChannel int64 `schema:"context_channel" valid:"channel,true"`
TimeTriggerInterval int `schema:"time_trigger_interval"`
TimeTriggerExcludingDays []int64 `schema:"time_trigger_excluding_days"`
TimeTriggerExcludingHours []int64 `schema:"time_trigger_excluding_hours"`
// If set, then the following channels are required, otherwise they are ignored
RequireChannels bool `json:"require_channels" schema:"require_channels"`
Channels []int64 `json:"channels" schema:"channels"`
// If set, then one of the following channels are required, otherwise they are ignored
RequireRoles bool `json:"require_roles" schema:"require_roles"`
Roles []int64 `json:"roles" schema:"roles"`
GroupID int64
}
var _ web.CustomValidator = (*CustomCommand)(nil)
func (cc *CustomCommand) Validate(tmpl web.TemplateData) (ok bool) {
if len(cc.Responses) > MaxUserMessages {
tmpl.AddAlerts(web.ErrorAlert(fmt.Sprintf("Too many responses, max %d", MaxUserMessages)))
return false
}
foundOkayResponse := false
for _, v := range cc.Responses {
if strings.TrimSpace(v) != "" {
foundOkayResponse = true
break
}
}
if !foundOkayResponse {
tmpl.AddAlerts(web.ErrorAlert("No response set"))
return false
}
combinedSize := 0
for _, v := range cc.Responses {
combinedSize += len(v)
}
if combinedSize > 10000 {
tmpl.AddAlerts(web.ErrorAlert("Max combined command size can be 10k"))
return false
}
return true
}
func (cc *CustomCommand) ToDBModel() *models.CustomCommand {
pqCommand := &models.CustomCommand{
TriggerType: int(cc.TriggerType),
TextTrigger: cc.Trigger,
TextTriggerCaseSensitive: cc.CaseSensitive,
Channels: cc.Channels,
ChannelsWhitelistMode: cc.RequireChannels,
Roles: cc.Roles,
RolesWhitelistMode: cc.RequireRoles,
TimeTriggerInterval: cc.TimeTriggerInterval,
TimeTriggerExcludingDays: cc.TimeTriggerExcludingDays,
TimeTriggerExcludingHours: cc.TimeTriggerExcludingHours,
ContextChannel: cc.ContextChannel,
Responses: cc.Responses,
}
if cc.TimeTriggerExcludingDays == nil {
pqCommand.TimeTriggerExcludingDays = []int64{}
}
if cc.TimeTriggerExcludingHours == nil {
pqCommand.TimeTriggerExcludingHours = []int64{}
}
if cc.GroupID != 0 {
pqCommand.GroupID = null.Int64From(cc.GroupID)
}
if cc.TriggerTypeForm == "interval_hours" {
pqCommand.TimeTriggerInterval *= 60
}
return pqCommand
}
func CmdRunsInChannel(cc *models.CustomCommand, channel int64) bool {
if cc.GroupID.Valid {
// check group restrictions
if common.ContainsInt64Slice(cc.R.Group.IgnoreChannels, channel) {
return false
}
if len(cc.R.Group.WhitelistChannels) > 0 {
if !common.ContainsInt64Slice(cc.R.Group.WhitelistChannels, channel) {
return false
}
}
}
// check command specifc restrictions
for _, v := range cc.Channels {
if v == channel {
if cc.ChannelsWhitelistMode {
return true
}
// Ignore the channel
return false
}
}
// Not found
if cc.ChannelsWhitelistMode {
return false
}
// Not in ignore list
return true
}
func CmdRunsForUser(cc *models.CustomCommand, ms *dstate.MemberState) bool {
if cc.GroupID.Valid {
// check group restrictions
if common.ContainsInt64SliceOneOf(cc.R.Group.IgnoreRoles, ms.Roles) {
return false
}
if len(cc.R.Group.WhitelistRoles) > 0 && !common.ContainsInt64SliceOneOf(cc.R.Group.WhitelistRoles, ms.Roles) {
return false
}
}
// check command specific restrictions
if len(cc.Roles) == 0 {
// Fast path
if cc.RolesWhitelistMode {
return false
}
return true
}
for _, v := range cc.Roles {
if common.ContainsInt64Slice(ms.Roles, v) {
if cc.RolesWhitelistMode {
return true
}
return false
}
}
// Not found
if cc.RolesWhitelistMode {
return false
}
return true
}
// Migrate modifies a CustomCommand to remove legacy fields.
func (cc *CustomCommand) Migrate() *CustomCommand {
cc.Responses = filterEmptyResponses(cc.Response, cc.Responses...)
cc.Response = ""
if len(cc.Responses) > MaxUserMessages {
cc.Responses = cc.Responses[:MaxUserMessages]
}
return cc
}
func LegacyGetCommands(guild int64) ([]*CustomCommand, int64, error) {
var hashMap map[string]string
err := common.RedisPool.Do(retryableredis.Cmd(&hashMap, "HGETALL", KeyCommands(guild)))
if err != nil {
return nil, 0, err
}
highest := int64(0)
result := make([]*CustomCommand, len(hashMap))
// Decode the commands, and also calculate the highest id
i := 0
for k, raw := range hashMap {
var decoded *CustomCommand
err = json.Unmarshal([]byte(raw), &decoded)
if err != nil {
logger.WithError(err).WithField("guild", guild).WithField("custom_command", k).Error("Failed decoding custom command")
result[i] = &CustomCommand{}
} else {
result[i] = decoded.Migrate()
if decoded.ID > highest {
highest = decoded.ID
}
}
i++
}
// Sort by id
sort.Sort(CustomCommandSlice(result))
return result, highest, nil
}
type CustomCommandSlice []*CustomCommand
// Len is the number of elements in the collection.
func (c CustomCommandSlice) Len() int {
return len(c)
}
// Less reports whether the element with
// index i should sort before the element with index j.
func (c CustomCommandSlice) Less(i, j int) bool {
return c[i].ID < c[j].ID
}
// Swap swaps the elements with indexes i and j.
func (c CustomCommandSlice) Swap(i, j int) {
temp := c[i]
c[i] = c[j]
c[j] = temp
}
func filterEmptyResponses(s string, ss ...string) []string {
result := make([]string, 0, len(ss)+1)
if s != "" {
result = append(result, s)
}
for _, s := range ss {
if s != "" {
result = append(result, s)
}
}
return result
}
const (
MaxCommands = 100
MaxCommandsPremium = 250
MaxUserMessages = 20
MaxGroups = 50
)
func MaxCommandsForContext(ctx context.Context) int {
if premium.ContextPremium(ctx) {
return MaxCommandsPremium
}
return MaxCommands
}