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",
"name": "diction",
"description": "Find definitions for words",
"version": "1.2.3",
"version": "1.3.0",
"tags": ["commands", "utility", "dictionary"],
"dependencies": ["simplecommands", "cron"],
"npmDependencies": []

View File

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

View File

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