forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 5
/
plugin_bot.go
339 lines (284 loc) · 9.27 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
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
package timezonecompanion
import (
"context"
"database/sql"
"fmt"
"github.com/jonas747/dcmd"
"github.com/jonas747/discordgo"
"github.com/jonas747/yagpdb/bot"
"github.com/jonas747/yagpdb/bot/eventsystem"
"github.com/jonas747/yagpdb/bot/paginatedmessages"
"github.com/jonas747/yagpdb/commands"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/timezonecompanion/models"
"github.com/volatiletech/sqlboiler/boil"
"math"
"strings"
"time"
)
var _ bot.BotInitHandler = (*Plugin)(nil)
var _ commands.CommandProvider = (*Plugin)(nil)
func (p *Plugin) BotInit() {
eventsystem.AddHandlerAsyncLastLegacy(p, p.handleMessageCreate, eventsystem.EventMessageCreate)
}
func (p *Plugin) AddCommands() {
commands.AddRootCommands(&commands.YAGCommand{
CmdCategory: commands.CategoryTool,
Name: "settimezone",
Aliases: []string{"setz", "tzset"},
Description: "Sets your timezone, used for various purposes such as auto conversion. Give it your country.",
Arguments: []*dcmd.ArgDef{
&dcmd.ArgDef{Name: "Timezone", Type: dcmd.String},
},
ArgSwitches: []*dcmd.ArgDef{
&dcmd.ArgDef{Switch: "u", Name: "Display current"},
&dcmd.ArgDef{Switch: "d", Name: "Delete TZ record"},
},
RunFunc: func(parsed *dcmd.Data) (interface{}, error) {
localTZ := time.Now().Location()
userZone, userOffset := time.Now().In(localTZ).Zone()
getUserTZ := GetUserTimezone(parsed.Msg.Author.ID)
tzState := "server's"
if getUserTZ != nil {
userZone, userOffset = time.Now().In(getUserTZ).Zone()
localTZ = getUserTZ
tzState = "registered to"
}
humanizeOffset := fmt.Sprintf("%+d", userOffset/3600)
if (userOffset % 3600 / 60) != 0 {
humanizeOffset += fmt.Sprintf(":%d", int(math.Abs(float64(userOffset%3600/60))))
}
userTZ := fmt.Sprintf("Your current time zone is %s: `%s` %s (UTC%s)", tzState, localTZ, userZone, humanizeOffset)
if parsed.Switches["u"].Value != nil && parsed.Switches["u"].Value.(bool) {
return userTZ, nil
}
if parsed.Switches["d"].Value != nil && parsed.Switches["d"].Value.(bool) && getUserTZ != nil {
m := &models.UserTimezone{
UserID: parsed.Msg.Author.ID,
TimezoneName: localTZ.String(),
}
_, err := m.DeleteG(parsed.Context())
if err != nil {
return nil, err
}
return "Deleted", nil
} else if parsed.Switches["d"].Value != nil && parsed.Switches["d"].Value.(bool) {
return "You don't have a registered time zone", nil
}
zones := FindZone(parsed.Args[0].Str())
if len(zones) < 1 {
return fmt.Sprintf("Unknown timezone, enter a country or timezone (not abbreviation like CET). there's a timezone picker here: <http://kevalbhatt.github.io/timezone-picker> you can use, enter the `Area/City` result\n\n%s", userTZ), nil
}
if len(zones) > 1 {
if len(zones) > 10 {
_, err := paginatedmessages.CreatePaginatedMessage(
parsed.GS.ID, parsed.CS.ID, 1, int(math.Ceil(float64(len(zones))/10)), paginatedTimezones(zones))
return nil, err
}
out := "More than 1 result, reuse the command with a one of the following:\n"
for _, v := range zones {
if s := StrZone(v); s != "" {
out += s + "\n"
}
}
out += "\n" + userTZ
return out, nil
}
loc, err := time.LoadLocation(zones[0])
if err != nil {
return "Unknown timezone", nil
}
name, _ := time.Now().In(loc).Zone()
zone := zones[0]
m := &models.UserTimezone{
UserID: parsed.Msg.Author.ID,
TimezoneName: zone,
}
err = m.UpsertG(parsed.Context(), true, []string{"user_id"}, boil.Infer(), boil.Infer())
if err != nil {
return nil, err
}
return fmt.Sprintf("Set your timezone to `%s`: %s\n", zone, name), nil
},
}, &commands.YAGCommand{
CmdCategory: commands.CategoryTool,
Name: "ToggleTimeConversion",
Aliases: []string{"toggletconv"},
Description: "Toggles automatic time conversion for people with registered timezones (setz) in this channel, its on by default, toggle all channels by giving it `all`",
RequireDiscordPerms: []int64{discordgo.PermissionManageMessages, discordgo.PermissionManageServer},
Arguments: []*dcmd.ArgDef{
&dcmd.ArgDef{Name: "flags", Type: dcmd.String},
},
RunFunc: func(parsed *dcmd.Data) (interface{}, error) {
allStr := parsed.Args[0].Str()
all := false
if strings.EqualFold(allStr, "all") || strings.EqualFold(allStr, "*") {
all = true
}
insert := false
conf, err := models.FindTimezoneGuildConfigG(parsed.Context(), parsed.GS.ID)
if err != nil {
if err == sql.ErrNoRows {
conf = &models.TimezoneGuildConfig{
GuildID: parsed.GS.ID,
}
insert = true
} else {
return nil, err
}
}
resp := ""
if all {
if conf.NewChannelsDisabled {
conf.NewChannelsDisabled = false
conf.DisabledInChannels = []int64{}
resp = "Enabled time conversion in all channels."
} else {
conf.NewChannelsDisabled = true
conf.EnabledInChannels = []int64{}
resp = "Disabled time conversion in all channels, including newly created channels."
}
} else {
status := "off"
found := false
for i, v := range conf.DisabledInChannels {
if v == parsed.CS.ID {
found = true
conf.DisabledInChannels = append(conf.DisabledInChannels[:i], conf.DisabledInChannels[i+1:]...)
status = "on"
if conf.NewChannelsDisabled {
conf.EnabledInChannels = append(conf.EnabledInChannels, parsed.CS.ID)
}
break
}
}
if !found {
conf.DisabledInChannels = append(conf.DisabledInChannels, parsed.CS.ID)
for i, v := range conf.EnabledInChannels {
if v == parsed.CS.ID {
conf.EnabledInChannels = append(conf.EnabledInChannels[:i], conf.EnabledInChannels[i+1:]...)
}
}
}
resp = fmt.Sprintf("Automatic time conversion in this channel toggled `%s`", status)
}
if insert {
err = conf.InsertG(parsed.Context(), boil.Infer())
} else {
_, err = conf.UpdateG(parsed.Context(), boil.Infer())
}
if err != nil {
return nil, err
}
return resp, nil
},
})
}
func StrZone(zone string) string {
loc, err := time.LoadLocation(zone)
if err != nil {
return ""
}
name, _ := time.Now().In(loc).Zone()
return fmt.Sprintf("`%s`: %s", zone, name)
}
func paginatedTimezones(timezones []string) func(p *paginatedmessages.PaginatedMessage, page int) (*discordgo.MessageEmbed, error) {
return func(p *paginatedmessages.PaginatedMessage, page int) (*discordgo.MessageEmbed, error) {
numSkip := (page - 1) * 10
out := ""
numAdded := 0
for i := numSkip; i < len(timezones); i++ {
if s := StrZone(timezones[i]); s != "" {
out += s + "\n"
numAdded++
if numAdded >= 10 {
break
}
}
}
return &discordgo.MessageEmbed{
Description: "Please redo the command with one of the following:\n" + out,
}, nil
}
}
func GetUserTimezone(userID int64) *time.Location {
m, err := models.FindUserTimezoneG(context.Background(), userID)
if err != nil {
return nil
}
loc, err := time.LoadLocation(m.TimezoneName)
if err != nil {
logger.WithError(err).Error("failed loading location")
return nil
}
return loc
}
func FindZone(in string) []string {
lowerIn := strings.ToLower(in)
inSpaceReplaced := strings.ReplaceAll(lowerIn, " ", "_")
ccs := make([]string, 0)
for country, code := range CountryCodes {
if strings.Contains(strings.ToLower(country), lowerIn) {
ccs = appendIfNotExists(ccs, code)
}
}
matchesZones := make([]string, 0)
for code, zones := range CCToZones {
// if common.ContainsString()
// check if we specified the country
if common.ContainsStringSlice(ccs, code) || strings.EqualFold(code, lowerIn) {
for _, v := range zones {
matchesZones = appendIfNotExists(matchesZones, v)
}
continue
}
for _, v := range zones {
if strings.Contains(strings.ToLower(v), inSpaceReplaced) {
matchesZones = appendIfNotExists(matchesZones, v)
}
}
}
return matchesZones
}
func appendIfNotExists(in []string, elem string) []string {
if !common.ContainsStringSlice(in, elem) {
return append(in, elem)
}
return in
}
func (p *Plugin) handleMessageCreate(evt *eventsystem.EventData) {
m := evt.MessageCreate()
if m.GuildID == 0 {
return
}
result, err := p.DateParser.Parse(m.Content, time.Now())
if err != nil || result == nil {
return
}
conf, err := models.FindTimezoneGuildConfigG(evt.Context(), m.GuildID)
if err != nil {
if err != sql.ErrNoRows {
logger.WithError(err).WithField("guild", m.GuildID).Error("failed fetching guild config")
return
}
} else if common.ContainsInt64Slice(conf.DisabledInChannels, m.ChannelID) || (conf.NewChannelsDisabled && !common.ContainsInt64Slice(conf.EnabledInChannels, m.ChannelID)) {
// disabled in this channel
return
}
zone := GetUserTimezone(m.Author.ID)
if zone == nil {
return
}
// re-parse it with proper context
result, err = p.DateParser.Parse(m.Content, time.Now().In(zone))
if err != nil || result == nil {
return
}
common.BotSession.ChannelMessageSendEmbed(m.ChannelID, &discordgo.MessageEmbed{
Timestamp: result.Time.Format(time.RFC3339),
Footer: &discordgo.MessageEmbedFooter{
Text: "Above time (" + result.Time.Format("15:04 MST") + ") in your local time",
},
})
// common.BotSession.ChannelMessageSend(m.ChannelID, "Time: `"+result.Time.Format(time.RFC822)+"`")
}