longer definition on non-short protocols

This commit is contained in:
Evert Prants 2023-08-07 17:49:36 +03:00
parent 04e90fc084
commit fdc9494fbd
Signed by: evert
GPG Key ID: 1688DA83D222D0B5
3 changed files with 89 additions and 36 deletions

View File

@ -2,7 +2,7 @@
"main": "plugin.js", "main": "plugin.js",
"name": "diction", "name": "diction",
"description": "Find definitions for words", "description": "Find definitions for words",
"version": "1.2.3", "version": "1.3.0",
"tags": ["commands", "utility", "dictionary"], "tags": ["commands", "utility", "dictionary"],
"dependencies": ["simplecommands", "cron"], "dependencies": ["simplecommands", "cron"],
"npmDependencies": [] "npmDependencies": []

View File

@ -4,9 +4,13 @@ import {
Plugin, Plugin,
Configurable, Configurable,
EventListener, EventListener,
DependencyLoad DependencyLoad,
} from '@squeebot/core/lib/plugin'; } from '@squeebot/core/lib/plugin';
import { IMessage, MessageResolver } from '@squeebot/core/lib/types'; import {
IMessage,
MessageResolver,
ProtocolFeatureFlag,
} from '@squeebot/core/lib/types';
interface IDefinition { interface IDefinition {
partOfSpeech: string; partOfSpeech: string;
@ -55,7 +59,11 @@ function flushCache(): void {
delete wordCache[item]; delete wordCache[item];
}); });
logger.log(`[diction] Dictionary cleared of the previous words ${oldestWords.join(', ')}.`); logger.log(
`[diction] Dictionary cleared of the previous words ${oldestWords.join(
', '
)}.`
);
} }
@Configurable({ @Configurable({
@ -85,8 +93,17 @@ class DictionPlugin extends Plugin {
cmd.registerCommand({ cmd.registerCommand({
name: 'define', name: 'define',
plugin: this.name, plugin: this.name,
execute: async (msg: IMessage, msr: MessageResolver, spec: any, prefix: string, ...simplified: any[]): Promise<boolean> => { execute: async (
msg: IMessage,
msr: MessageResolver,
spec: any,
prefix: string,
...simplified: any[]
): Promise<boolean> => {
const word = simplified.join(' '); const word = simplified.join(' ');
const short = msg.source.supports(
ProtocolFeatureFlag.SHORT_FORM_MESSAGING
);
if (!word) { if (!word) {
msg.resolve('Please specifiy a word or term!'); msg.resolve('Please specifiy a word or term!');
@ -98,7 +115,8 @@ class DictionPlugin extends Plugin {
return true; return true;
} }
let chosenDefinition: IDefinition; const skip = short ? 1 : 5;
let chosenDefinitions: IDefinition[];
let definitionCount = 0; let definitionCount = 0;
let definitionIndex = 0; let definitionIndex = 0;
@ -106,29 +124,35 @@ class DictionPlugin extends Plugin {
const userTarget = msg.fullSenderID as string; const userTarget = msg.fullSenderID as string;
if (wordCache[word]) { if (wordCache[word]) {
const cached = wordCache[word]; const cached = wordCache[word];
const alreadyAsked = cached.lastIndex.find((item) => item.name === userTarget); const alreadyAsked = cached.lastIndex.find(
(item) => item.name === userTarget
);
definitionCount = cached.definitions.length; definitionCount = cached.definitions.length;
if (alreadyAsked) { if (alreadyAsked) {
let nextI = alreadyAsked.index + 1; let startIndex = alreadyAsked.index;
if (nextI >= cached.definitions.length) {
nextI = 0;
}
if (alreadyAsked.lastTime < Date.now() - 5 * 60 * 1000) { if (alreadyAsked.lastTime < Date.now() - 5 * 60 * 1000) {
nextI = 0; startIndex = 0;
} }
const nextIndex =
startIndex + skip >= cached.definitions.length
? 0
: startIndex + skip;
alreadyAsked.lastTime = Date.now(); alreadyAsked.lastTime = Date.now();
alreadyAsked.index = nextI; alreadyAsked.index = nextIndex;
definitionIndex = nextI; definitionIndex = startIndex;
chosenDefinition = cached.definitions[nextI]; chosenDefinitions = cached.definitions.slice(
startIndex,
startIndex + skip
);
} else { } else {
chosenDefinition = cached.definitions[0]; chosenDefinitions = cached.definitions.slice(0, skip);
cached.lastIndex.push({ cached.lastIndex.push({
name: userTarget, name: userTarget,
index: 0, index: skip,
lastTime: Date.now(), lastTime: Date.now(),
}); });
} }
@ -139,7 +163,9 @@ class DictionPlugin extends Plugin {
let response; let response;
try { try {
const s = `https://api.wordnik.com/v4/word.json/${encodedWord}/definitions?limit=${limit}&api_key=${key}`; const s = `https://api.wordnik.com/v4/word.json/${encodedWord}/definitions?limit=${
short ? limit : 100
}&api_key=${key}`;
response = await httpGET(s); response = await httpGET(s);
response = JSON.parse(response); response = JSON.parse(response);
} catch (e) { } catch (e) {
@ -156,47 +182,74 @@ class DictionPlugin extends Plugin {
lastIndex: [ lastIndex: [
{ {
name: userTarget, name: userTarget,
index: 0, index: skip,
lastTime: Date.now(), lastTime: Date.now(),
} },
], ],
definitions: (response as Record<string, string>[]) definitions: (response as Record<string, string>[])
.filter(entry => entry.text) .filter((entry) => entry.text)
.map((data) => ({ .map((data) => ({
partOfSpeech: data.partOfSpeech, partOfSpeech: data.partOfSpeech,
text: data.text.replace(/(<([^>]+)>)/ig, ''), text: data.text.replace(/(<([^>]+)>)/gi, ''),
})), })),
inserted: Date.now(), inserted: Date.now(),
}; };
wordCache[word] = cached; wordCache[word] = cached;
chosenDefinition = cached.definitions[0]; chosenDefinitions = cached.definitions.slice(0, skip);
definitionCount = cached.definitions.length; definitionCount = cached.definitions.length;
logger.log(`[diction] Dictionary cached the word "${word}"`); logger.log(`[diction] Dictionary cached the word "${word}"`);
} }
const { partOfSpeech, text } = chosenDefinition; 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'
)
);
}
msg.resolve(`(${definitionIndex + 1}/${definitionCount}) ${word}${ generatedMessages.push(` ${definition.text}`);
partOfSpeech ? ` - ${partOfSpeech}` : '' }
} - ${text}`);
if (definitionIndex + skip < definitionCount) {
generatedMessages.push(
`(${definitionCount - definitionIndex - skip} more...)`
);
}
msg.resolve(generatedMessages.join('\n'));
}
return true; return true;
}, },
match: /define (\w*)/, match: /define (\w*)/,
aliases: ['df', 'word'], aliases: ['df', 'word'],
description: 'Find definitions for words. Call again to advance to next definition', description:
usage: '<word>' 'Find definitions for words. Call again to advance to next definition',
usage: '<word>',
}); });
} }
@DependencyLoad('cron') @DependencyLoad('cron')
public cronLoaded(cron: any): void { public cronLoaded(cron: any): void {
cron.registerTimer( cron.registerTimer(this, '0 0 * * *', () => flushCache());
this,
'0 0 * * *',
() => flushCache(),
);
} }
} }

View File

@ -11,7 +11,7 @@
}, },
{ {
"name": "diction", "name": "diction",
"version": "1.2.3" "version": "1.3.0"
}, },
{ {
"name": "fun", "name": "fun",