forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
284 lines (236 loc) · 7.48 KB
/
bot.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
package customcommands
import (
"fmt"
"github.com/jonas747/dcmd"
"github.com/jonas747/discordgo"
"github.com/jonas747/dutil/dstate"
"github.com/jonas747/yagpdb/bot"
"github.com/jonas747/yagpdb/bot/eventsystem"
"github.com/jonas747/yagpdb/commands"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/common/templates"
"github.com/mediocregopher/radix.v2/redis"
log "github.com/sirupsen/logrus"
"regexp"
"strings"
"time"
"unicode/utf8"
)
var cmdListCommands = &commands.YAGCommand{
CmdCategory: commands.CategoryTool,
Name: "CustomCommands",
Aliases: []string{"cc"},
Description: "Shows a custom command specified by id or trigger, or lists them all",
ArgumentCombos: [][]int{[]int{0}, []int{1}, []int{}},
Arguments: []*dcmd.ArgDef{
&dcmd.ArgDef{Name: "ID", Type: dcmd.Int},
&dcmd.ArgDef{Name: "Trigger", Type: dcmd.String},
},
RunFunc: func(data *dcmd.Data) (interface{}, error) {
ccs, _, err := GetCommands(data.Context().Value(commands.CtxKeyRedisClient).(*redis.Client), data.GS.ID())
if err != nil {
return "Failed retrieving custom commands", err
}
foundCCS, provided := FindCommands(ccs, data)
if len(foundCCS) < 1 {
list := StringCommands(ccs)
if provided {
return "No command by that name or id found, here is a list of them all:\n" + list, nil
} else {
return "No id or trigger provided, here is a list of all server commands:\n" + list, nil
}
}
if len(foundCCS) > 1 {
return "More than 1 matched command\n" + StringCommands(foundCCS), nil
}
cc := foundCCS[0]
return fmt.Sprintf("%s: `%s` - Case sensitive trigger: `%t` ```\n%s\n```", cc.TriggerType, cc.Trigger, cc.CaseSensitive, cc.Response), nil
},
}
func FindCommands(ccs []*CustomCommand, data *dcmd.Data) (foundCCS []*CustomCommand, provided bool) {
foundCCS = make([]*CustomCommand, 0, len(ccs))
provided = true
if data.Args[0].Value != nil {
// Find by ID
id := data.Args[0].Int()
for _, v := range ccs {
if v.ID == id {
foundCCS = append(foundCCS, v)
}
}
} else if data.Args[1].Value != nil {
// Find by name
name := data.Args[1].Str()
for _, v := range ccs {
if strings.EqualFold(name, v.Trigger) {
foundCCS = append(foundCCS, v)
}
}
} else {
provided = false
}
return
}
func StringCommands(ccs []*CustomCommand) string {
out := ""
for _, cc := range ccs {
out += fmt.Sprintf("%s: `%s`\n", cc.Trigger, cc.TriggerType.String())
}
return out
}
func shouldIgnoreChannel(evt *discordgo.MessageCreate, userID int64, cState *dstate.ChannelState) bool {
if cState == nil {
log.Warn("Channel not found in state")
return true
}
if userID == evt.Author.ID || evt.Author.Bot || cState.IsPrivate() {
return true
}
channelPerms, err := cState.Guild.MemberPermissions(true, cState.ID(), userID)
if err != nil {
log.WithFields(log.Fields{"guild": cState.Guild.ID(), "channel": cState.ID()}).WithError(err).Error("Failed checking channel perms")
return true
}
if channelPerms&discordgo.PermissionSendMessages == 0 {
return true
}
// Passed all checks, custom commands should not ignore this channel
return false
}
func HandleMessageCreate(evt *eventsystem.EventData) {
client := bot.ContextRedis(evt.Context())
botUser := bot.State.User(true)
cs := bot.State.Channel(true, evt.MessageCreate.ChannelID)
if shouldIgnoreChannel(evt.MessageCreate, botUser.ID, cs) {
return
}
cmds, _, err := GetCommands(client, cs.Guild.ID())
if err != nil {
log.WithError(err).WithField("guild", cs.Guild.ID()).Error("Failed retrieving comamnds")
return
}
if len(cmds) < 1 {
return
}
prefix, err := commands.GetCommandPrefix(client, cs.Guild.ID())
if err != nil {
log.WithError(err).Error("Failed getting prefix")
return
}
member, err := bot.GetMember(cs.Guild.ID(), evt.MessageCreate.Author.ID)
if err != nil {
return
}
var matched *CustomCommand
var stripped string
for _, cmd := range cmds {
if !cmd.RunsInChannel(evt.MessageCreate.ChannelID) || !cmd.RunsForUser(member) {
continue
}
if m, s := CheckMatch(prefix, cmd, evt.MessageCreate.Content); m {
matched = cmd
stripped = s
break
}
}
if matched == nil || matched.Response == "" {
return
}
channel := cs.Copy(true, true)
log.WithFields(log.Fields{
"trigger": matched.Trigger,
"trigger_type": matched.TriggerType,
"guild": channel.GuildID,
"channel_name": channel.Name,
}).Info("Custom command triggered")
out, delTrigger, delResponse, err := ExecuteCustomCommand(matched, stripped, client, bot.ContextSession(evt.Context()), evt.MessageCreate)
if err != nil {
log.WithField("guild", channel.GuildID).WithError(err).Error("Error executing custom command")
out += "\nAn error caused the execution of the custom command template to stop:\n"
out += common.EscapeSpecialMentions(err.Error())
}
if strings.TrimSpace(out) != "" {
m, err := common.BotSession.ChannelMessageSend(evt.MessageCreate.ChannelID, out)
if err != nil {
log.WithError(err).Error("Failed sending message")
} else {
if delResponse {
go common.DelayedMessageDelete(common.BotSession, time.Second*10, m.ChannelID, m.ID)
}
}
}
if delTrigger {
go common.DelayedMessageDelete(common.BotSession, time.Second*10, evt.MessageCreate.ChannelID, evt.MessageCreate.ID)
}
}
func ExecuteCustomCommand(cmd *CustomCommand, stripped string, client *redis.Client, s *discordgo.Session, m *discordgo.MessageCreate) (resp string, delTrigger bool, delResponse bool, err error) {
cs := bot.State.Channel(true, m.ChannelID)
member, err := bot.GetMember(cs.Guild.ID(), m.Author.ID)
if err != nil {
err = err
return
}
tmplCtx := templates.NewContext(bot.State.User(true).User, cs.Guild, cs, member)
tmplCtx.Redis = client
tmplCtx.Msg = m.Message
args := dcmd.SplitArgs(m.Content)
argsStr := make([]string, len(args))
for k, v := range args {
argsStr[k] = v.Str
}
tmplCtx.Data["Args"] = argsStr
tmplCtx.Data["StrippedMsg"] = stripped
out, err := tmplCtx.Execute(client, cmd.Response)
if utf8.RuneCountInString(out) > 2000 {
out = "Custom command response was longer than 2k (contact an admin on the server...)"
}
resp = out
delTrigger = tmplCtx.DelTrigger
delResponse = tmplCtx.DelResponse
return
}
func CheckMatch(globalPrefix string, cmd *CustomCommand, msg string) (match bool, stripped string) {
// set to globalprefix+" "+localprefix for command, and just local prefix for startwith
startsWith := ""
trigger := cmd.Trigger
if !cmd.CaseSensitive && cmd.TriggerType != CommandTriggerRegex {
msg = strings.ToLower(msg)
trigger = strings.ToLower(cmd.Trigger)
globalPrefix = strings.ToLower(globalPrefix)
}
switch cmd.TriggerType {
// Simpler triggers
case CommandTriggerStartsWith:
startsWith = trigger
case CommandTriggerCommand:
split := strings.SplitN(msg, " ", 2)
if len(split) > 0 && split[0] == globalPrefix+trigger {
if len(split) > 1 {
stripped = strings.TrimSpace(split[1])
}
return true, stripped
} else {
return false, ""
}
// Special trigger types
case CommandTriggerContains:
return strings.Contains(msg, trigger), msg
case CommandTriggerRegex:
rTrigger := cmd.Trigger
if !cmd.CaseSensitive && !strings.HasPrefix(rTrigger, "(?i)") {
rTrigger = "(?i)" + rTrigger
}
ok, err := regexp.Match(rTrigger, []byte(msg))
if err != nil {
log.WithError(err).Error("Failed compiling regex")
}
return ok, msg
case CommandTriggerExact:
return msg == trigger, ""
}
if strings.HasPrefix(msg, startsWith) {
stripped = msg[:len(startsWith)]
return true, stripped
}
return false, ""
}