-
Notifications
You must be signed in to change notification settings - Fork 910
/
rolecommands.go
397 lines (327 loc) · 9.44 KB
/
rolecommands.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
// rolecommands is a plugin which allows users to assign roles to themselves
package rolecommands
//go:generate sqlboiler --no-hooks psql
import (
"context"
"fmt"
"github.com/jonas747/discordgo"
"github.com/jonas747/dutil/dstate"
"github.com/jonas747/yagpdb/bot"
"github.com/jonas747/yagpdb/commands"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/rolecommands/models"
"github.com/jonas747/yagpdb/web"
"github.com/sirupsen/logrus"
"github.com/tidwall/buntdb"
"github.com/volatiletech/sqlboiler/queries/qm"
"sort"
"strconv"
"time"
)
type Plugin struct {
}
func (p *Plugin) Name() string {
return "RoleCommands"
}
const (
GroupModeNone = iota
GroupModeSingle
GroupModeMultiple
)
const (
RoleMenuStateSettingUp = 0
RoleMenuStateDone = 1
)
var (
_ common.Plugin = (*Plugin)(nil)
_ web.Plugin = (*Plugin)(nil)
_ bot.BotInitHandler = (*Plugin)(nil)
_ commands.CommandProvider = (*Plugin)(nil)
cooldownsDB *buntdb.DB
)
func RegisterPlugin() {
cooldownsDB, _ = buntdb.Open(":memory:")
p := &Plugin{}
common.RegisterPlugin(p)
_, err := common.PQ.Exec(DBSchema)
if err != nil {
logrus.WithError(err).Fatal("Failed initializing db schema")
}
}
type CommandGroupPair struct {
Command *models.RoleCommand
Group *models.RoleGroup
}
func FindAssignRole(ctx context.Context, guildID int64, ms *dstate.MemberState, name string) (gaveRole bool, err error) {
cmd, err := models.RoleCommands(qm.Where("guild_id=?", guildID), qm.Where("name ILIKE ?", name)).OneG(ctx)
if err != nil {
return false, err
}
var group *models.RoleGroup
if cmd.RoleGroupID.Valid {
group, err = cmd.RoleGroup().OneG(ctx)
if err != nil {
return false, err
}
}
return AssignRole(ctx, guildID, ms, &CommandGroupPair{Command: cmd, Group: group})
}
// AssignRole attempts to assign the given role command, returns an error if the role does not exists
// or is unable to receie said role
func AssignRole(ctx context.Context, guildID int64, ms *dstate.MemberState, cmd *CommandGroupPair) (gaveRole bool, err error) {
onCD := false
// First check cooldown
if cmd.Group != nil && cmd.Group.Mode == GroupModeSingle {
err = cooldownsDB.Update(func(tx *buntdb.Tx) error {
_, replaced, _ := tx.Set(discordgo.StrID(ms.ID), "1", &buntdb.SetOptions{Expires: true, TTL: time.Second * 1})
if replaced {
onCD = true
}
return nil
})
if onCD {
return false, NewSimpleError("You're on cooldown")
}
}
if err := CanAssignRoleCmdTo(cmd.Command, ms.Roles); err != nil {
return false, err
}
// This command belongs to a group, let the group handle it
if cmd.Group != nil {
return GroupAssignRoleToMember(ctx, cmd.Group, guildID, ms, cmd.Command)
}
// This is a single command, just toggle it
return ToggleRole(guildID, ms, cmd.Command.Role)
}
// ToggleRole toggles the role of a guildmember, adding it if the member does not have the role and removing it if they do
func ToggleRole(guildID int64, ms *dstate.MemberState, role int64) (gaveRole bool, err error) {
if common.ContainsInt64Slice(ms.Roles, role) {
err = common.BotSession.GuildMemberRoleRemove(guildID, ms.ID, role)
gaveRole = false
return
}
err = common.BotSession.GuildMemberRoleAdd(guildID, ms.ID, role)
gaveRole = true
return
}
// AssignRoleToMember attempts to assign the given role command, part of this group
// to the member
func GroupAssignRoleToMember(ctx context.Context, rg *models.RoleGroup, guildID int64, ms *dstate.MemberState, targetRole *models.RoleCommand) (gaveRole bool, err error) {
if len(rg.RequireRoles) > 0 {
if !CheckRequiredRoles(rg.RequireRoles, ms.Roles) {
err = NewSimpleError("Missing a required role")
return
}
}
if len(rg.IgnoreRoles) > 0 {
if err = CheckIgnoredRoles(rg.IgnoreRoles, ms.Roles); err != nil {
return
}
}
// Default behaviour of groups is no more restrictions than reuiqred and ignore roles
if rg.Mode == GroupModeNone {
return ToggleRole(guildID, ms, targetRole.Role)
}
// First retrieve role commands for this group
commands, err := rg.RoleCommands().AllG(ctx)
if err != nil {
return
}
if rg.Mode == GroupModeSingle {
// If user already has role it's attempting to give itself
if common.ContainsInt64Slice(ms.Roles, targetRole.Role) {
if rg.SingleRequireOne {
return false, NewGroupError("Need atleast one role in group **%s**", rg)
}
err = common.BotSession.GuildMemberRoleRemove(guildID, ms.ID, targetRole.Role)
gaveRole = false
return
}
// Check if the user has any other role commands in this group
for _, v := range commands {
if common.ContainsInt64Slice(ms.Roles, v.Role) {
if rg.SingleAutoToggleOff {
common.BotSession.GuildMemberRoleRemove(guildID, ms.ID, v.Role)
} else {
return false, NewGroupError("Max 1 role in group **%s** is allowed", rg)
}
}
}
// Finally give the role
err = common.BotSession.GuildMemberRoleAdd(guildID, ms.ID, targetRole.Role)
return true, err
}
// Handle multiple mode
// Count roles in group and check against min-max
// also check if we already have said role
hasRoles := 0
hasTargetRole := false
for _, role := range commands {
if common.ContainsInt64Slice(ms.Roles, role.Role) {
hasRoles++
if role.ID == targetRole.ID {
hasTargetRole = true
}
}
}
if hasTargetRole {
if hasRoles-1 < int(rg.MultipleMin) {
err = NewLmitError("Minimum of `%d` roles required in this group", int(rg.MultipleMin))
return
}
} else {
if hasRoles+1 > int(rg.MultipleMax) {
err = NewLmitError("Maximum of `%d` roles allowed in this group", int(rg.MultipleMax))
return
}
}
return ToggleRole(guildID, ms, targetRole.Role)
}
func CanAssignRoleCmdTo(r *models.RoleCommand, memberRoles []int64) error {
if len(r.RequireRoles) > 0 {
if !CheckRequiredRoles(r.RequireRoles, memberRoles) {
return NewSimpleError("Missing a required role")
}
}
if len(r.IgnoreRoles) > 0 {
if err := CheckIgnoredRoles(r.IgnoreRoles, memberRoles); err != nil {
return err
}
}
return nil
}
func CheckRequiredRoles(requireOneOf []int64, has []int64) bool {
for _, r := range requireOneOf {
if common.ContainsInt64Slice(has, r) {
// Only 1 role required
return true
}
}
return false
}
func CheckIgnoredRoles(ignore []int64, has []int64) error {
for _, r := range ignore {
if common.ContainsInt64Slice(has, r) {
return NewRoleError("Has ignored role", r)
}
}
return nil
}
// Just a simple type but distinguishable from errors.Error
type SimpleError string
func (s SimpleError) Error() string {
return string(s)
}
func NewSimpleError(format string, args ...interface{}) error {
return SimpleError(fmt.Sprintf(format, args...))
}
type RoleError struct {
Role int64
Message string
}
func NewRoleError(msg string, role int64) error {
return &RoleError{
Role: role,
Message: msg,
}
}
func (r *RoleError) Error() string {
if r.Role == 0 {
return r.Message
}
return r.Message + ": " + strconv.FormatInt(r.Role, 10)
}
// Uses the role name from one of the passed roles with matching id instead of the id
func (r *RoleError) PrettyError(roles []*discordgo.Role) string {
if r.Role == 0 {
return r.Message
}
idStr := strconv.FormatInt(r.Role, 10)
roleStr := ""
for _, v := range roles {
if v.ID == r.Role {
roleStr = "**" + v.Name + "**"
break
}
}
if roleStr == "" {
roleStr = "(unknown role " + idStr + ")"
}
return r.Message + ": " + roleStr
}
type LmitError struct {
Limit int
Message string
}
func NewLmitError(msg string, limit int) error {
return &LmitError{
Limit: limit,
Message: msg,
}
}
func (r *LmitError) Error() string {
return fmt.Sprintf(r.Message, r.Limit)
}
type GroupError struct {
Group *models.RoleGroup
Message string
}
func NewGroupError(msg string, group *models.RoleGroup) error {
return &GroupError{
Group: group,
Message: msg,
}
}
func (r *GroupError) Error() string {
return fmt.Sprintf(r.Message, r.Group.Name)
}
func IsRoleCommandError(err error) bool {
switch err.(type) {
case *LmitError, *RoleError, *GroupError, SimpleError, *SimpleError:
return true
default:
return false
}
}
func RoleCommandsLessFunc(slice []*models.RoleCommand) func(int, int) bool {
return func(i, j int) bool {
// Compare timestamps if positions are equal, for deterministic output
if slice[i].Position == slice[j].Position {
return slice[i].CreatedAt.After(slice[j].CreatedAt)
}
if slice[i].Position > slice[j].Position {
return false
}
return true
}
}
func GetAllRoleCommandsSorted(ctx context.Context, guildID int64) (groups []*models.RoleGroup, grouped map[*models.RoleGroup][]*models.RoleCommand, unGrouped []*models.RoleCommand, err error) {
commands, err := models.RoleCommands(qm.Where(models.RoleCommandColumns.GuildID+"=?", guildID)).AllG(ctx)
if err != nil {
return
}
grps, err := models.RoleGroups(qm.Where(models.RoleGroupColumns.GuildID+"=?", guildID)).AllG(ctx)
if err != nil {
return
}
groups = grps
grouped = make(map[*models.RoleGroup][]*models.RoleCommand)
for _, group := range groups {
grouped[group] = make([]*models.RoleCommand, 0, 10)
for _, cmd := range commands {
if cmd.RoleGroupID.Valid && cmd.RoleGroupID.Int64 == group.ID {
grouped[group] = append(grouped[group], cmd)
}
}
sort.Slice(grouped[group], RoleCommandsLessFunc(grouped[group]))
}
unGrouped = make([]*models.RoleCommand, 0, 10)
for _, cmd := range commands {
if !cmd.RoleGroupID.Valid {
unGrouped = append(unGrouped, cmd)
}
}
sort.Slice(unGrouped, RoleCommandsLessFunc(unGrouped))
err = nil
return
}