import { httpGET } from '@squeebot/core/lib/common'; import { logger } from '@squeebot/core/lib/core'; import { Plugin, Configurable, EventListener, DependencyLoad } from '@squeebot/core/lib/plugin'; import { IMessage } from '@squeebot/core/lib/types'; const poslist = [ 'noun', 'verb', 'adjective', 'adverb', 'participle', 'article', 'pronoun', 'preposition', 'conjunction', 'interjection', 'determiner', ]; let lastQuery = 0; @Configurable({ lexicala: { username: '', password: '', }, cooldown: 5, }) class DictionPlugin extends Plugin { @EventListener('pluginUnload') public unloadEventHandler(plugin: string | Plugin): void { if (plugin === this.name || plugin === this) { this.emit('pluginUnloaded', this); } } @DependencyLoad('simplecommands') addCommands(cmd: any): void { const user = this.config.get('lexicala.username'); const passwd = this.config.get('lexicala.password'); const rate = this.config.get('cooldown', 5); const rauth = 'Basic ' + Buffer.from(`${user}:${passwd}`).toString('base64'); if (!user || !passwd) { logger.warn('Lexicala define command is disabled due to no credentials.'); return; } cmd.registerCommand({ name: 'define', plugin: this.name, execute: async (msg: IMessage, spec: any, prefix: string, ...simplified: any[]): Promise => { if (lastQuery > Date.now() - rate * 1000) { msg.resolve('You\'re doing that too fast!'); return true; } let pos: string | null = simplified[0]; if (pos && poslist.indexOf(pos.toLowerCase()) !== -1 && simplified.length > 1) { pos = '&pos=' + pos; } else { pos = ''; } const word = encodeURIComponent(simplified.slice(pos ? 1 : 0).join(' ')); if (!word) { msg.resolve('Please specifiy a word or term!'); return true; } lastQuery = Date.now(); let response; try { const s = `https://dictapi.lexicala.com/search?source=global&language=en${pos}&text=${word}`; response = await httpGET(s, { Authorization: rauth }); response = JSON.parse(response); } catch (e) { msg.resolve('Server did not respond.'); return true; } if (!response.n_results || response.n_results === 0 || !response.results) { msg.resolve('Nothing found.'); return true; } const resolve = []; for (const def of response.results) { const wd = def.headword.text; const wdp = def.headword.pos; const results = def.senses.map((rep: any) => rep.definition).slice(0, 4); resolve.push({ word: wd, type: wdp, results, }); } const str = resolve.slice(0, 4).map((rep: any) => { return `${rep.word} (${rep.type}):\n` + rep.results.join('\n'); }).join('\n'); msg.resolve(str); return true; }, match: /define (\w*)/, aliases: ['df'], description: 'Find definitions for words', usage: '[] ' }); } } module.exports = DictionPlugin;