-
Notifications
You must be signed in to change notification settings - Fork 908
/
plugin_bot.go
268 lines (231 loc) · 8.19 KB
/
plugin_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
package reminders
import (
"fmt"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/jinzhu/gorm"
"github.com/jonas747/dcmd/v2"
"github.com/jonas747/discordgo"
"github.com/jonas747/yagpdb/bot"
"github.com/jonas747/yagpdb/commands"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/common/scheduledevents2"
seventsmodels "github.com/jonas747/yagpdb/common/scheduledevents2/models"
)
var logger = common.GetPluginLogger(&Plugin{})
var _ bot.BotInitHandler = (*Plugin)(nil)
var _ commands.CommandProvider = (*Plugin)(nil)
func (p *Plugin) AddCommands() {
commands.AddRootCommands(p, cmds...)
}
func (p *Plugin) BotInit() {
// scheduledevents.RegisterEventHandler("reminders_check_user", checkUserEvtHandlerLegacy)
scheduledevents2.RegisterHandler("reminders_check_user", int64(0), checkUserScheduledEvent)
scheduledevents2.RegisterLegacyMigrater("reminders_check_user", migrateLegacyScheduledEvents)
}
// Reminder management commands
var cmds = []*commands.YAGCommand{
{
CmdCategory: commands.CategoryTool,
Name: "Remindme",
Description: "Schedules a reminder, example: 'remindme 1h30min are you alive still?'",
Aliases: []string{"remind", "reminder"},
RequiredArgs: 2,
Arguments: []*dcmd.ArgDef{
{Name: "Time", Type: &commands.DurationArg{}},
{Name: "Message", Type: dcmd.String},
},
SlashCommandEnabled: true,
DefaultEnabled: true,
RunFunc: func(parsed *dcmd.Data) (interface{}, error) {
currentReminders, _ := GetUserReminders(parsed.Author.ID)
if len(currentReminders) >= 25 {
return "You can have a maximum of 25 active reminders, list your reminders with the `reminders` command", nil
}
fromNow := parsed.Args[0].Value.(time.Duration)
durString := common.HumanizeDuration(common.DurationPrecisionSeconds, fromNow)
when := time.Now().Add(fromNow)
tStr := when.UTC().Format(time.RFC822)
if when.After(time.Now().Add(time.Hour * 24 * 366)) {
return "Can be max 365 days from now...", nil
}
_, err := NewReminder(parsed.Author.ID, parsed.GuildData.GS.ID, parsed.ChannelID, parsed.Args[1].Str(), when)
if err != nil {
return nil, err
}
return "Set a reminder in " + durString + " from now (" + tStr + ")\nView reminders with the reminders command", nil
},
},
{
CmdCategory: commands.CategoryTool,
Name: "Reminders",
Description: "Lists your active reminders",
SlashCommandEnabled: true,
DefaultEnabled: true,
RunFunc: func(parsed *dcmd.Data) (interface{}, error) {
currentReminders, err := GetUserReminders(parsed.Author.ID)
if err != nil {
return nil, err
}
out := "Your reminders:\n"
out += stringReminders(currentReminders, false)
out += "\nRemove a reminder with `delreminder/rmreminder (id)` where id is the first number for each reminder above.\nTo clear all reminders, use `delreminder` with the `-a` switch."
return out, nil
},
},
{
CmdCategory: commands.CategoryTool,
Name: "CReminders",
Description: "Lists reminders in channel, only users with 'manage server' permissions can use this.",
SlashCommandEnabled: true,
DefaultEnabled: true,
RunFunc: func(parsed *dcmd.Data) (interface{}, error) {
ok, err := bot.AdminOrPermMS(parsed.ChannelID, parsed.GuildData.MS, discordgo.PermissionManageChannels)
if err != nil {
return nil, err
}
if !ok {
return "You do not have access to this command (requires manage channel permission)", nil
}
currentReminders, err := GetChannelReminders(parsed.ChannelID)
if err != nil {
return nil, err
}
out := "Reminders in this channel:\n"
out += stringReminders(currentReminders, true)
out += "\nRemove a reminder with `delreminder/rmreminder (id)` where id is the first number for each reminder above"
return out, nil
},
},
{
CmdCategory: commands.CategoryTool,
Name: "DelReminder",
Aliases: []string{"rmreminder"},
Description: "Deletes a reminder. You can delete reminders from other users provided you are running this command in the same guild the reminder was created in and have the Manage Channel permission in the channel the reminder was created in.",
RequiredArgs: 0,
Arguments: []*dcmd.ArgDef{
{Name: "ID", Type: dcmd.Int},
},
ArgSwitches: []*dcmd.ArgDef{
{Name: "a", Help: "All"},
},
SlashCommandEnabled: true,
DefaultEnabled: true,
RunFunc: func(parsed *dcmd.Data) (interface{}, error) {
var reminder Reminder
clearAll := parsed.Switch("a").Value != nil && parsed.Switch("a").Value.(bool)
if clearAll {
db := common.GORM.Where("user_id = ?", parsed.Author.ID).Delete(&reminder)
err := db.Error
if err != nil {
return "Error clearing reminders", err
}
count := db.RowsAffected
if count == 0 {
return "No reminders to clear", nil
}
return fmt.Sprintf("Cleared %d reminders", count), nil
}
if len(parsed.Args) == 0 || parsed.Args[0].Value == nil {
return "No reminder ID provided", nil
}
err := common.GORM.Where(parsed.Args[0].Int()).First(&reminder).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return "No reminder by that id found", nil
}
return "Error retrieving reminder", err
}
// Check perms
if reminder.UserID != discordgo.StrID(parsed.Author.ID) {
if reminder.GuildID != parsed.GuildData.GS.ID {
return "You can only delete reminders that are not your own in the guild the reminder was originally created", nil
}
ok, err := bot.AdminOrPermMS(reminder.ChannelIDInt(), parsed.GuildData.MS, discordgo.PermissionManageChannels)
if err != nil {
return nil, err
}
if !ok {
return "You need manage channel permission in the channel the reminder is in to delete reminders that are not your own", nil
}
}
// Do the actual deletion
err = common.GORM.Delete(reminder).Error
if err != nil {
return nil, err
}
// Check if we should remove the scheduled event
currentReminders, err := GetUserReminders(reminder.UserIDInt())
if err != nil {
return nil, err
}
delMsg := fmt.Sprintf("Deleted reminder **#%d**: '%s'", reminder.ID, limitString(reminder.Message))
// If there is another reminder with the same timestamp, do not remove the scheduled event
for _, v := range currentReminders {
if v.When == reminder.When {
return delMsg, nil
}
}
return delMsg, nil
},
},
}
func stringReminders(reminders []*Reminder, displayUsernames bool) string {
out := ""
for _, v := range reminders {
parsedCID, _ := strconv.ParseInt(v.ChannelID, 10, 64)
t := time.Unix(v.When, 0)
timeFromNow := common.HumanizeTime(common.DurationPrecisionMinutes, t)
tStr := t.Format(time.RFC822)
if !displayUsernames {
channel := "<#" + discordgo.StrID(parsedCID) + ">"
out += fmt.Sprintf("**%d**: %s: '%s' - %s from now (%s)\n", v.ID, channel, limitString(v.Message), timeFromNow, tStr)
} else {
member, _ := bot.GetMember(v.GuildID, v.UserIDInt())
username := "Unknown user"
if member != nil {
username = member.Username
}
out += fmt.Sprintf("**%d**: %s: '%s' - %s from now (%s)\n", v.ID, username, limitString(v.Message), timeFromNow, tStr)
}
}
return out
}
func checkUserScheduledEvent(evt *seventsmodels.ScheduledEvent, data interface{}) (retry bool, err error) {
// !important! the evt.GuildID can be 1 in cases where it was migrated from the legacy scheduled event system
userID := *data.(*int64)
reminders, err := GetUserReminders(userID)
if err != nil {
return true, err
}
now := time.Now()
nowUnix := now.Unix()
for _, v := range reminders {
if v.When <= nowUnix {
err := v.Trigger()
if err != nil {
// possibly try again
return scheduledevents2.CheckDiscordErrRetry(err), err
}
}
}
return false, nil
}
func migrateLegacyScheduledEvents(t time.Time, data string) error {
split := strings.Split(data, ":")
if len(split) < 2 {
logger.Error("invalid check user scheduled event: ", data)
return nil
}
parsed, _ := strconv.ParseInt(split[1], 10, 64)
return scheduledevents2.ScheduleEvent("reminders_check_user", 1, t, parsed)
}
func limitString(s string) string {
if utf8.RuneCountInString(s) < 50 {
return s
}
runes := []rune(s)
return string(runes[:47]) + "..."
}