plugins-evert/diction/plugin.ts

257 lines
6.8 KiB
TypeScript
Raw Normal View History

2020-12-05 10:00:00 +00:00
import { httpGET } from '@squeebot/core/lib/common';
import { logger } from '@squeebot/core/lib/core';
import {
Plugin,
Configurable,
EventListener,
DependencyLoad,
2020-12-05 10:00:00 +00:00
} from '@squeebot/core/lib/plugin';
import {
IMessage,
MessageResolver,
ProtocolFeatureFlag,
} from '@squeebot/core/lib/types';
2020-12-05 10:00:00 +00:00
2021-09-15 18:50:28 +00:00
interface IDefinition {
partOfSpeech: string;
text: string;
}
interface IWordCache {
lastIndex: {
name: string;
index: number;
lastTime: number;
}[];
definitions: IDefinition[];
inserted: number;
}
2020-12-05 10:00:00 +00:00
let lastQuery = 0;
2021-09-15 18:50:28 +00:00
const wordCache: Record<string, IWordCache> = {};
/**
* Find and remove words that haven't been looked up for a day
*/
2021-10-02 09:31:46 +00:00
function flushCache(): void {
const oldestWords: string[] = [];
2021-09-15 18:50:28 +00:00
Object.keys(wordCache).forEach((word) => {
const cached = wordCache[word];
let notOld = false;
for (const person of cached.lastIndex) {
if (person.lastTime > Date.now() - 24 * 60 * 60 * 1000) {
notOld = true;
break;
}
}
if (!notOld) {
oldestWords.push(word);
}
});
if (!oldestWords.length) {
return;
}
oldestWords.forEach((item) => {
delete wordCache[item];
});
logger.log(
`[diction] Dictionary cleared of the previous words ${oldestWords.join(
', '
)}.`
);
2021-09-15 18:50:28 +00:00
}
2020-12-05 10:00:00 +00:00
@Configurable({
2021-09-15 18:50:28 +00:00
wordnik: '',
2020-12-05 10:00:00 +00:00
cooldown: 5,
2021-09-15 18:50:28 +00:00
limit: 5,
2020-12-05 10:00:00 +00:00
})
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 {
2021-09-15 18:50:28 +00:00
const key = this.config.get('wordnik');
2020-12-05 10:00:00 +00:00
const rate = this.config.get('cooldown', 5);
2021-09-15 18:50:28 +00:00
const limit = this.config.get('limit', 5);
2020-12-05 10:00:00 +00:00
2021-09-15 18:50:28 +00:00
if (!key) {
logger.warn('Wordnik define command is disabled due to no credentials.');
2020-12-05 10:00:00 +00:00
return;
}
cmd.registerCommand({
name: 'define',
plugin: this.name,
execute: async (
msg: IMessage,
msr: MessageResolver,
spec: any,
prefix: string,
...simplified: any[]
): Promise<boolean> => {
2021-09-15 18:50:28 +00:00
const word = simplified.join(' ');
const short = msg.source.supports(
ProtocolFeatureFlag.SHORT_FORM_MESSAGING
);
2020-12-05 10:00:00 +00:00
if (!word) {
msg.resolve('Please specifiy a word or term!');
return true;
}
2021-09-15 18:50:28 +00:00
if (lastQuery > Date.now() - rate * 1000 && !wordCache[word]) {
msg.resolve('You\'re doing that too fast!');
2020-12-05 10:00:00 +00:00
return true;
}
const skip = short ? 1 : 5;
let chosenDefinitions: IDefinition[];
2021-09-15 18:50:28 +00:00
let definitionCount = 0;
let definitionIndex = 0;
// Check cached definitions
const userTarget = msg.fullSenderID as string;
if (wordCache[word]) {
const cached = wordCache[word];
const alreadyAsked = cached.lastIndex.find(
(item) => item.name === userTarget
);
2021-09-15 18:50:28 +00:00
definitionCount = cached.definitions.length;
if (alreadyAsked) {
let startIndex = alreadyAsked.index;
2021-09-15 18:50:28 +00:00
if (alreadyAsked.lastTime < Date.now() - 5 * 60 * 1000) {
startIndex = 0;
2021-09-15 18:50:28 +00:00
}
const nextIndex =
startIndex + skip >= cached.definitions.length
? 0
: startIndex + skip;
2021-09-15 18:50:28 +00:00
alreadyAsked.lastTime = Date.now();
alreadyAsked.index = nextIndex;
definitionIndex = startIndex;
chosenDefinitions = cached.definitions.slice(
startIndex,
startIndex + skip
);
2021-09-15 18:50:28 +00:00
} else {
chosenDefinitions = cached.definitions.slice(0, skip);
2021-09-15 18:50:28 +00:00
cached.lastIndex.push({
name: userTarget,
index: skip,
2021-09-15 18:50:28 +00:00
lastTime: Date.now(),
});
}
} else {
// Request definition
const encodedWord = encodeURIComponent(word);
lastQuery = Date.now();
let response;
try {
const s = `https://api.wordnik.com/v4/word.json/${encodedWord}/definitions?limit=${
short ? limit : 100
}&api_key=${key}`;
2021-09-15 18:50:28 +00:00
response = await httpGET(s);
response = JSON.parse(response);
} catch (e) {
msg.resolve('Server did not respond.');
return true;
}
if (!response || !response.length) {
msg.resolve('No definitions found.');
return true;
}
const cached: IWordCache = {
lastIndex: [
{
name: userTarget,
index: skip,
2021-09-15 18:50:28 +00:00
lastTime: Date.now(),
},
2021-09-15 18:50:28 +00:00
],
2021-09-19 08:39:34 +00:00
definitions: (response as Record<string, string>[])
.filter((entry) => entry.text)
2021-10-02 09:31:46 +00:00
.map((data) => ({
partOfSpeech: data.partOfSpeech,
text: data.text.replace(/(<([^>]+)>)/gi, ''),
2021-09-19 08:39:34 +00:00
})),
2021-09-15 18:50:28 +00:00
inserted: Date.now(),
2021-10-02 09:31:46 +00:00
};
2021-09-15 18:50:28 +00:00
wordCache[word] = cached;
chosenDefinitions = cached.definitions.slice(0, skip);
2021-09-15 18:50:28 +00:00
definitionCount = cached.definitions.length;
logger.log(`[diction] Dictionary cached the word "${word}"`);
2020-12-05 10:00:00 +00:00
}
if (short) {
const { partOfSpeech, text } = chosenDefinitions[0];
msg.resolve(
`(${definitionIndex + 1}/${definitionCount}) ${word}${
partOfSpeech ? ` - ${partOfSpeech}` : ''
} - ${text}`
);
} else {
const generatedMessages: string[] = [word];
let lastPartOfSpeech = '';
for (const definition of chosenDefinitions) {
if (
!lastPartOfSpeech ||
lastPartOfSpeech !== definition.partOfSpeech
) {
lastPartOfSpeech = definition.partOfSpeech;
generatedMessages.push(
msg.source.format.format(
'bold',
definition.partOfSpeech || 'other'
)
);
}
2020-12-05 10:00:00 +00:00
generatedMessages.push(` ${definition.text}`);
}
if (definitionIndex + skip < definitionCount) {
generatedMessages.push(
`(${definitionCount - definitionIndex - skip} more...)`
);
}
msg.resolve(generatedMessages.join('\n'));
}
2020-12-05 10:00:00 +00:00
return true;
},
2020-12-05 16:14:35 +00:00
match: /define (\w*)/,
2021-09-19 08:39:34 +00:00
aliases: ['df', 'word'],
description:
'Find definitions for words. Call again to advance to next definition',
usage: '<word>',
2020-12-05 10:00:00 +00:00
});
}
2021-10-02 09:31:46 +00:00
@DependencyLoad('cron')
public cronLoaded(cron: any): void {
cron.registerTimer(this, '0 0 * * *', () => flushCache());
2021-10-02 09:31:46 +00:00
}
2020-12-05 10:00:00 +00:00
}
module.exports = DictionPlugin;