chipmunkbot3/commands/urban.js

79 lines
2 KiB
JavaScript
Raw Permalink Normal View History

2024-04-02 17:53:10 -04:00
const { literal, argument, greedyString } = require('brigadier-commands')
const ud = require('urban-dictionary')
2024-02-11 21:23:41 -05:00
2024-04-02 17:53:10 -04:00
module.exports = {
register (dispatcher) {
const node = dispatcher.register(
literal('urban')
.then(
argument('word', greedyString())
.executes(c => this.urbanCommand(c))
2024-04-02 17:53:10 -04:00
)
)
2024-02-11 21:23:41 -05:00
2024-04-02 17:53:10 -04:00
node.description = 'Shows word definitions from the Urban Dictionary'
node.permissionLevel = 0
},
2024-02-11 21:23:41 -05:00
2024-04-02 17:53:10 -04:00
async urbanCommand (context) {
const source = context.source
const definitions = await ud.define(context.getArgument('word'))
.catch(error => source.sendError(error.toString()))
if (!definitions) return
2024-02-11 21:23:41 -05:00
const msg = [{ text: '', color: 'gray' }]
2024-04-02 17:53:10 -04:00
for (const definition of definitions) {
msg.push(
{ text: '[', color: 'dark_gray' },
{ text: 'Urban', color: 'red' },
{ text: '] ', color: 'dark_gray' },
{ text: `${definition.word} `, bold: true },
...this.parseDefinitionText(definition.definition, source),
'\n'
)
}
msg.pop()
source.sendFeedback(msg, false)
},
parseDefinitionText (text, source) {
const prefix = source.bot.commands.prefixes[0]
2024-04-02 17:53:10 -04:00
const texts = []
let string = ''
const state = { i: 0 }
2024-04-02 17:53:10 -04:00
while (state.i < text.length) {
texts.push(this.readUntil(text, '[', state))
state.i++
2024-04-02 17:53:10 -04:00
if (state.i >= text.length) break // we are already done reading
const subword = this.readUntil(text, ']', state)
texts.push({ text: subword, underlined: true, clickEvent: { action: 'suggest_command', value: prefix + 'urban ' + subword } })
state.i++
}
return texts
},
readUntil (string, terminator, state) {
let substr = ''
for (; state.i < string.length && string[state.i] !== terminator; state.i++) {
const i = state.i
const c = string[i]
if (c === '\r') {
substr += '\n'
state.i += string[i + 1] === '\n' ? 2 : 1
2024-04-02 17:53:10 -04:00
continue
2024-02-11 21:23:41 -05:00
}
substr += c
2024-04-02 17:53:10 -04:00
}
return substr
2024-04-02 17:53:10 -04:00
}
}