forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tmplexec.go
258 lines (214 loc) · 7.06 KB
/
tmplexec.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
package commands
import (
"context"
"strconv"
"strings"
"emperror.dev/errors"
"github.com/botlabs-gg/yagpdb/v2/bot"
"github.com/botlabs-gg/yagpdb/v2/bot/paginatedmessages"
"github.com/botlabs-gg/yagpdb/v2/common"
"github.com/botlabs-gg/yagpdb/v2/common/templates"
"github.com/botlabs-gg/yagpdb/v2/lib/dcmd"
"github.com/botlabs-gg/yagpdb/v2/lib/discordgo"
)
func init() {
templates.RegisterSetupFunc(func(ctx *templates.Context) {
execUser, execBot := TmplExecCmdFuncs(ctx, 5, false)
ctx.ContextFuncs["exec"] = execUser
ctx.ContextFuncs["execAdmin"] = execBot
ctx.ContextFuncs["userArg"] = tmplUserArg(ctx)
})
}
// Returns a user from either id, mention string or if the input is just a user, a user...
func tmplUserArg(tmplCtx *templates.Context) interface{} {
return func(v interface{}) (interface{}, error) {
if tmplCtx.IncreaseCheckGenericAPICall() {
return nil, templates.ErrTooManyAPICalls
}
if num := templates.ToInt64(v); num != 0 {
// Assume it's an id
member, _ := bot.GetMember(tmplCtx.GS.ID, num)
if member != nil {
return &member.User, nil
}
return nil, nil
}
if str, ok := v.(string); ok {
// Mention string
if len(str) < 5 {
return nil, nil
}
str = strings.TrimSpace(str)
if strings.HasPrefix(str, "<@") && strings.HasSuffix(str, ">") {
trimmed := str[2 : len(str)-1]
if trimmed[0] == '!' {
trimmed = trimmed[1:]
}
id, _ := strconv.ParseInt(trimmed, 10, 64)
member, _ := bot.GetMember(tmplCtx.GS.ID, id)
if member != nil {
// Found member
return &member.User, nil
}
}
// No more cases we can handle
return nil, nil
}
// Just return whatever we passed
return v, nil
}
}
type cmdExecFunc func(cmd string, args ...interface{}) (interface{}, error)
// Returns 2 functions to execute commands in user or bot context with limited about of commands executed
func TmplExecCmdFuncs(ctx *templates.Context, maxExec int, dryRun bool) (userCtxCommandExec cmdExecFunc, botCtxCommandExec cmdExecFunc) {
execUser := func(cmd string, args ...interface{}) (interface{}, error) {
messageCopy := *ctx.Msg
if ctx.CurrentFrame.CS != nil { //Check if CS is not a nil pointer
messageCopy.ChannelID = ctx.CurrentFrame.CS.ID
}
mc := &discordgo.MessageCreate{Message: &messageCopy}
if maxExec < 1 {
return "", errors.New("Max number of commands executed in custom command")
}
maxExec -= 1
return execCmd(ctx, dryRun, mc, cmd, args...)
}
execBot := func(cmd string, args ...interface{}) (interface{}, error) {
botUserCopy := *common.BotUser
botUserCopy.Username = "YAGPDB (cc: " + ctx.Msg.Author.String() + ")"
messageCopy := *ctx.Msg
messageCopy.Author = &botUserCopy
if ctx.CurrentFrame.CS != nil { //Check if CS is not a nil pointer
messageCopy.ChannelID = ctx.CurrentFrame.CS.ID
}
botMember, err := bot.GetMember(messageCopy.GuildID, common.BotUser.ID)
if err != nil {
return "", errors.New("Failed fetching member")
}
messageCopy.Member = botMember.DgoMember()
mc := &discordgo.MessageCreate{Message: &messageCopy}
if maxExec < 1 {
return "", errors.New("Max number of commands executed in custom command")
}
maxExec -= 1
return execCmd(ctx, dryRun, mc, cmd, args...)
}
return execUser, execBot
}
func execCmd(tmplCtx *templates.Context, dryRun bool, m *discordgo.MessageCreate, cmd string, args ...interface{}) (interface{}, error) {
fakeMsg := *m.Message
fakeMsg.Mentions = make([]*discordgo.User, 0)
cmdLine := cmd + " "
for _, arg := range args {
if arg == nil {
return "", errors.New("Nil arg passed")
}
switch t := arg.(type) {
case string:
if strings.HasPrefix(t, "-") {
// Don't put quotes around switches
cmdLine += t
} else if strings.HasPrefix(t, "\\-") {
// Escaped -
cmdLine += "\"" + t[1:] + "\""
} else {
cmdLine += "\"" + t + "\""
}
case int:
cmdLine += strconv.FormatInt(int64(t), 10)
case int32:
cmdLine += strconv.FormatInt(int64(t), 10)
case int64:
cmdLine += strconv.FormatInt(t, 10)
case uint:
cmdLine += strconv.FormatUint(uint64(t), 10)
case uint8:
cmdLine += strconv.FormatUint(uint64(t), 10)
case uint16:
cmdLine += strconv.FormatUint(uint64(t), 10)
case uint32:
cmdLine += strconv.FormatUint(uint64(t), 10)
case uint64:
cmdLine += strconv.FormatUint(t, 10)
case float32:
cmdLine += strconv.FormatFloat(float64(t), 'E', -1, 32)
case float64:
cmdLine += strconv.FormatFloat(t, 'E', -1, 64)
case *discordgo.User:
cmdLine += "<@" + strconv.FormatInt(t.ID, 10) + ">"
fakeMsg.Mentions = append(fakeMsg.Mentions, t)
case discordgo.User:
cmdLine += "<@" + strconv.FormatInt(t.ID, 10) + ">"
fakeMsg.Mentions = append(fakeMsg.Mentions, &t)
case []string:
for i, str := range t {
if i != 0 {
cmdLine += " "
}
cmdLine += str
}
default:
return "", errors.New("Unknown type in exec, only strings, numbers, users and string slices are supported")
}
cmdLine += " "
}
logger.Infof("Custom template is executing a command: %s for guild %v", cmdLine, tmplCtx.Msg.GuildID)
fakeMsg.Content = cmdLine
data, err := CommandSystem.FillDataLegacyMessage(common.BotSession, &fakeMsg)
if err != nil {
return "", errors.WithMessage(err, "tmplExecCmd")
}
data.TraditionalTriggerData.MessageStrippedPrefix = fakeMsg.Content
foundCmd, foundContainer, rest := CommandSystem.Root.AbsFindCommandWithRest(cmdLine)
if foundCmd == nil {
return "Unknown command", nil
}
data.TraditionalTriggerData.MessageStrippedPrefix = rest
data.Cmd = foundCmd
data.ContainerChain = []*dcmd.Container{CommandSystem.Root}
if foundContainer != CommandSystem.Root {
data.ContainerChain = append(data.ContainerChain, foundContainer)
}
data = data.WithContext(context.WithValue(data.Context(), paginatedmessages.CtxKeyNoPagination, true))
data = data.WithContext(context.WithValue(data.Context(), CtxKeyExecutedByCC, true))
cast := foundCmd.Command.(*YAGCommand)
err = dcmd.ParseCmdArgs(data)
if err != nil {
return "", errors.WithMessage(err, "exec/execadmin, parseArgs")
}
runFunc := cast.RunFunc
for i := range foundCmd.Trigger.Middlewares {
runFunc = foundCmd.Trigger.Middlewares[len(foundCmd.Trigger.Middlewares)-1-i](runFunc)
}
for i := range data.ContainerChain {
if i == len(data.ContainerChain)-1 {
// skip middlewares in original container to bypass cooldowns and stuff
continue
}
runFunc = data.ContainerChain[len(data.ContainerChain)-1-i].BuildMiddlewareChain(runFunc, foundCmd)
}
// Check guild scope cooldown
cd, err := cast.GuildScopeCooldownLeft(data.ContainerChain, tmplCtx.GS.ID)
if err != nil {
return "", errors.WithStackIf(err)
}
if cd > 0 {
return "", errors.NewPlain("this command is on guild scope cooldown")
}
resp, err := runFunc(data)
if err != nil {
return "", errors.WithMessage(err, "exec/execadmin, run")
}
cast.SetCooldownGuild(data.ContainerChain, tmplCtx.GS.ID)
switch v := resp.(type) {
case error:
return "Error: " + v.Error(), nil
case string:
return v, nil
case *discordgo.MessageEmbed:
return v, nil
case []*discordgo.MessageEmbed:
return v, nil
}
return "", nil
}