/
cooldown.js
344 lines (300 loc) · 16 KB
/
cooldown.js
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
/* @flow */
'use strict'
// 3rdparty libraries
const _ = require('lodash')
const XRegExp = require('xregexp')
const commons = require('../commons');
// bot libraries
import { command, default_permission, rollback, parser } from '../decorators';
import { permission } from '../permissions';
import System from './_interface'
import constants from '../constants'
const Expects = require('../expects.js')
const Parser = require('../parser')
/*
* !cooldown [keyword|!command] [global|user] [seconds] [true/false] - set cooldown for keyword or !command - 0 for disable, true/false set quiet mode
* !cooldown toggle moderators [keyword|!command] [global|user] - enable/disable specified keyword or !command cooldown for moderators
* !cooldown toggle owners [keyword|!command] [global|user] - enable/disable specified keyword or !command cooldown for owners
* !cooldown toggle subscribers [keyword|!command] [global|user] - enable/disable specified keyword or !command cooldown for owners
* !cooldown toggle followers [keyword|!command] [global|user] - enable/disable specified keyword or !command cooldown for owners
* !cooldown toggle enabled [keyword|!command] [global|user] - enable/disable specified keyword or !command cooldown
*/
class Cooldown extends System {
constructor () {
const settings = {
cooldownNotifyAsWhisper: false,
cooldownNotifyAsChat: true
}
super({ settings })
this.addMenu({ category: 'manage', name: 'cooldown', id: 'cooldown/list' })
}
@command('!cooldown')
@default_permission(permission.CASTERS)
async main (opts: Object) {
const match = XRegExp.exec(opts.parameters, constants.COOLDOWN_REGEXP_SET)
if (_.isNil(match)) {
let message = await commons.prepare('cooldowns.cooldown-parse-failed')
commons.sendMessage(message, opts.sender)
return false
}
if (parseInt(match.seconds, 10) === 0) {
await global.db.engine.remove(this.collection.data, { key: match.command, type: match.type })
let message = await commons.prepare('cooldowns.cooldown-was-unset', { type: match.type, command: match.command })
commons.sendMessage(message, opts.sender)
return
}
let cooldown = await global.db.engine.findOne(this.collection.data, { key: match.command, type: match.type })
if (_.isEmpty(cooldown)) await global.db.engine.update(this.collection.data, { key: match.command, type: match.type }, { miliseconds: parseInt(match.seconds, 10) * 1000, type: match.type, timestamp: 0, quiet: _.isNil(match.quiet) ? false : match.quiet, enabled: true, owner: false, moderator: false, subscriber: true, follower: true })
else await global.db.engine.update(this.collection.data, { key: match.command, type: match.type }, { miliseconds: parseInt(match.seconds, 10) * 1000 })
let message = await commons.prepare('cooldowns.cooldown-was-set', { seconds: match.seconds, type: match.type, command: match.command })
commons.sendMessage(message, opts.sender)
}
@parser({ priority: constants.HIGH })
async check (opts: Object) {
var data, viewer, timestamp, now
const [command, subcommand] = new Expects(opts.message)
.command({ optional: true })
.string({ optional: true })
.toArray()
if (!_.isNil(command)) { // command
let key = subcommand ? `${command} ${subcommand}` : command
const parsed = await (new Parser().find(subcommand ? `${command} ${subcommand}` : command))
if (parsed) {
key = parsed.command
} else {
// search in custom commands as well
if (global.systems.customCommands.isEnabled()) {
let commands = await global.db.engine.find(global.systems.customCommands.collection.data)
commands = _(commands).flatMap().sortBy(o => -o.command.length).value()
const customparsed = await (new Parser().find(subcommand ? `${command} ${subcommand}` : command, commands))
if (customparsed) {
key = customparsed.command
}
}
}
let cooldown = await global.db.engine.findOne(this.collection.data, { key })
if (_.isEmpty(cooldown)) { // command is not on cooldown -> recheck with text only
const replace = new RegExp(`${XRegExp.escape(key)}`, 'ig')
opts.message = opts.message.replace(replace, '')
if (opts.message.length > 0) return this.check(opts)
else return true
}
data = [{
key: cooldown.key,
miliseconds: cooldown.miliseconds,
type: cooldown.type,
lastTimestamp: cooldown.lastTimestamp,
timestamp: cooldown.timestamp,
quiet: typeof cooldown.quiet === 'undefined' ? true : cooldown.quiet,
enabled: typeof cooldown.enabled === 'undefined' ? true : cooldown.enabled,
moderator: typeof cooldown.moderator === 'undefined' ? true : cooldown.moderator,
subscriber: typeof cooldown.subscriber === 'undefined' ? true : cooldown.subscriber,
follower: typeof cooldown.follower === 'undefined' ? true : cooldown.follower,
owner: typeof cooldown.owner === 'undefined' ? true : cooldown.owner
}]
} else { // text
let [keywords, cooldowns] = await Promise.all([global.db.engine.find(global.systems.keywords.collection.data), global.db.engine.find(this.collection.data)])
keywords = _.filter(keywords, function (o) {
return opts.message.toLowerCase().search(new RegExp('^(?!\\!)(?:^|\\s).*(' + _.escapeRegExp(o.keyword.toLowerCase()) + ')(?=\\s|$|\\?|\\!|\\.|\\,)', 'gi')) >= 0
})
data = []
_.each(keywords, (keyword) => {
let cooldown = _.find(cooldowns, (o) => o.key.toLowerCase() === keyword.keyword.toLowerCase())
if (keyword.enabled && !_.isEmpty(cooldown)) {
data.push({
key: cooldown.key,
miliseconds: cooldown.miliseconds,
type: cooldown.type,
lastTimestamp: cooldown.lastTimestamp,
timestamp: cooldown.timestamp,
quiet: typeof cooldown.quiet === 'undefined' ? true : cooldown.quiet,
enabled: typeof cooldown.enabled === 'undefined' ? true : cooldown.enabled,
moderator: typeof cooldown.moderator === 'undefined' ? true : cooldown.moderator,
subscriber: typeof cooldown.subscriber === 'undefined' ? true : cooldown.subscriber,
follower: typeof cooldown.follower === 'undefined' ? true : cooldown.follower,
owner: typeof cooldown.owner === 'undefined' ? true : cooldown.owner
})
}
})
}
if (!_.some(data, { enabled: true })) { // parse ok if all cooldowns are disabled
return true
}
const user = await global.users.getById(opts.sender.userId)
let result = false
const isMod = typeof opts.sender.badges.moderator !== 'undefined'
const isSubscriber = typeof opts.sender.badges.subscriber !== 'undefined'
const isFollower = user.is && user.is.follower ? user.is.follower : false
for (let cooldown of data) {
if ((commons.isOwner(opts.sender) && !cooldown.owner) || (isMod && !cooldown.moderator) || (isSubscriber && !cooldown.subscriber) || (isFollower && !cooldown.follower)) {
result = true
continue
}
viewer = await global.db.engine.findOne(this.collection.viewers, { username: opts.sender.username, key: cooldown.key })
if (cooldown.type === 'global') {
timestamp = cooldown.timestamp || 0
} else {
timestamp = _.isNil(viewer.timestamp) ? 0 : viewer.timestamp
}
now = new Date().getTime()
if (now - timestamp >= cooldown.miliseconds) {
if (cooldown.type === 'global') {
await global.db.engine.update(this.collection.data, { key: cooldown.key, type: 'global' }, { lastTimestamp: timestamp, timestamp: now, key: cooldown.key, type: 'global' })
} else {
await global.db.engine.update(this.collection.viewers, { username: opts.sender.username, key: cooldown.key }, { lastTimestamp: timestamp, timestamp: now })
}
result = true
continue
} else {
if (!cooldown.quiet && this.settings['cooldownNotifyAsWhisper']) {
opts.sender['message-type'] = 'whisper' // we want to whisp cooldown message
let message = await commons.prepare('cooldowns.cooldown-triggered', { command: cooldown.key, seconds: Math.ceil((cooldown.miliseconds - now + timestamp) / 1000) })
await commons.sendMessage(message, opts.sender)
}
if (!cooldown.quiet && this.settings['cooldownNotifyAsChat']) {
opts.sender['message-type'] = 'chat'
let message = await commons.prepare('cooldowns.cooldown-triggered', { command: cooldown.key, seconds: Math.ceil((cooldown.miliseconds - now + timestamp) / 1000) })
await commons.sendMessage(message, opts.sender)
}
result = false
break // disable _.each and updateQueue with false
}
}
return result
}
@rollback()
async cooldownRollback (opts: Object) {
// TODO: redundant duplicated code (search of cooldown), should be unified for check and cooldownRollback
var data, viewer
const [command, subcommand] = new Expects(opts.message)
.command({ optional: true })
.string({ optional: true })
.toArray()
if (!_.isNil(command)) { // command
let key = subcommand ? `${command} ${subcommand}` : command
const parsed = await (new Parser().find(subcommand ? `${command} ${subcommand}` : command))
if (parsed) {
key = parsed.command
} else {
// search in custom commands as well
if (global.systems.customCommands.isEnabled()) {
let commands = await global.db.engine.find(global.systems.customCommands.collection.data)
commands = _(commands).flatMap().sortBy(o => -o.command.length).value()
const customparsed = await (new Parser().find(subcommand ? `${command} ${subcommand}` : command, commands))
if (customparsed) {
key = customparsed.command
}
}
}
let cooldown = await global.db.engine.findOne(this.collection.data, { key })
if (_.isEmpty(cooldown)) { // command is not on cooldown -> recheck with text only
const replace = new RegExp(`${XRegExp.escape(key)}`, 'ig')
opts.message = opts.message.replace(replace, '')
if (opts.message.length > 0) return this.cooldownRollback(opts)
else return true
}
data = [{
key: cooldown.key,
miliseconds: cooldown.miliseconds,
type: cooldown.type,
lastTimestamp: cooldown.lastTimestamp,
timestamp: cooldown.timestamp,
quiet: typeof cooldown.quiet === 'undefined' ? true : cooldown.quiet,
enabled: typeof cooldown.enabled === 'undefined' ? true : cooldown.enabled,
moderator: typeof cooldown.moderator === 'undefined' ? true : cooldown.moderator,
subscriber: typeof cooldown.subscriber === 'undefined' ? true : cooldown.subscriber,
follower: typeof cooldown.follower === 'undefined' ? true : cooldown.follower,
owner: typeof cooldown.owner === 'undefined' ? true : cooldown.owner
}]
} else { // text
let [keywords, cooldowns] = await Promise.all([global.db.engine.find(global.systems.keywords.collection.data), global.db.engine.find(this.collection.data)])
keywords = _.filter(keywords, function (o) {
return opts.message.toLowerCase().search(new RegExp('^(?!\\!)(?:^|\\s).*(' + _.escapeRegExp(o.keyword.toLowerCase()) + ')(?=\\s|$|\\?|\\!|\\.|\\,)', 'gi')) >= 0
})
data = []
_.each(keywords, (keyword) => {
let cooldown = _.find(cooldowns, (o) => o.key.toLowerCase() === keyword.keyword.toLowerCase())
if (keyword.enabled && !_.isEmpty(cooldown)) {
data.push({
key: cooldown.key,
miliseconds: cooldown.miliseconds,
type: cooldown.type,
lastTimestamp: cooldown.lastTimestamp,
timestamp: cooldown.timestamp,
quiet: typeof cooldown.quiet === 'undefined' ? true : cooldown.quiet,
enabled: typeof cooldown.enabled === 'undefined' ? true : cooldown.enabled,
moderator: typeof cooldown.moderator === 'undefined' ? true : cooldown.moderator,
subscriber: typeof cooldown.subscriber === 'undefined' ? true : cooldown.subscriber,
follower: typeof cooldown.follower === 'undefined' ? true : cooldown.follower,
owner: typeof cooldown.owner === 'undefined' ? true : cooldown.owner
})
}
})
}
if (!_.some(data, { enabled: true })) { // parse ok if all cooldowns are disabled
return true
}
const user = await global.users.getById(opts.sender.userId)
const isMod = typeof opts.sender.badges.moderator !== 'undefined'
const isSubscriber = typeof opts.sender.badges.subscriber !== 'undefined'
const isFollower = user.is && user.is.follower ? user.is.follower : false
for (let cooldown of data) {
if ((commons.isOwner(opts.sender) && !cooldown.owner) || (isMod && !cooldown.moderator) || (isSubscriber && !cooldown.subscriber) || (isFollower && !cooldown.follower)) {
continue
}
viewer = await global.db.engine.findOne(this.collection.viewers, { username: opts.sender.username, key: cooldown.key })
// rollback to lastTimestamp
if (cooldown.type === 'global') {
await global.db.engine.update(this.collection.data, { key: cooldown.key, type: 'global' }, { lastTimestamp: cooldown.lastTimestamp, timestamp: cooldown.lastTimestamp, key: cooldown.key, type: 'global' })
} else {
await global.db.engine.update(this.collection.viewers, { username: opts.sender.username, key: cooldown.key }, { lastTimestamp: viewer.lastTimestamp, timestamp: viewer.lastTimestamp })
}
}
}
async toggle (opts: Object, type: string) {
const match = XRegExp.exec(opts.parameters, constants.COOLDOWN_REGEXP)
if (_.isNil(match)) {
let message = await commons.prepare('cooldowns.cooldown-parse-failed')
commons.sendMessage(message, opts.sender)
return false
}
const cooldown = await global.db.engine.findOne(this.collection.data, { key: match.command, type: match.type })
if (_.isEmpty(cooldown)) {
let message = await commons.prepare('cooldowns.cooldown-not-found', { command: match.command })
commons.sendMessage(message, opts.sender)
return false
}
if (type === 'type') {
cooldown[type] = cooldown[type] === 'global' ? 'user' : 'global'
} else cooldown[type] = !cooldown[type]
delete cooldown._id
await global.db.engine.update(this.collection.data, { key: match.command, type: match.type }, cooldown)
let path = ''
let status = cooldown[type] ? 'enabled' : 'disabled'
if (type === 'moderator') path = '-for-moderators'
if (type === 'owner') path = '-for-owners'
if (type === 'subscriber') path = '-for-subscribers'
if (type === 'follower') path = '-for-followers'
if (type === 'quiet' || type === 'type') return // those two are setable only from dashboard
let message = await commons.prepare(`cooldowns.cooldown-was-${status}${path}`, { command: cooldown.key })
commons.sendMessage(message, opts.sender)
}
@command('!cooldown toggle enabled')
@default_permission(permission.CASTERS)
async toggleEnabled (opts: Object) { await this.toggle(opts, 'enabled') }
@command('!cooldown toggle moderators')
@default_permission(permission.CASTERS)
async toggleModerators (opts: Object) { await this.toggle(opts, 'moderator') }
@command('!cooldown toggle owners')
@default_permission(permission.CASTERS)
async toggleOwners (opts: Object) { await this.toggle(opts, 'owner') }
@command('!cooldown toggle subscribers')
@default_permission(permission.CASTERS)
async toggleSubscribers (opts: Object) { await this.toggle(opts, 'subscriber') }
@command('!cooldown toggle followers')
@default_permission(permission.CASTERS)
async toggleFollowers (opts: Object) { await this.toggle(opts, 'follower') }
async toggleNotify (opts: Object) { await this.toggle(opts, 'quiet') }
async toggleType (opts: Object) { await this.toggle(opts, 'type') }
}
module.exports = new Cooldown()