-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhelper.ts
205 lines (191 loc) · 5.44 KB
/
helper.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import { InlineKeyboard } from "https://deno.land/x/grammy@v1.14.1/mod.ts";
import { InlineQueryResult } from "https://deno.land/x/grammy@v1.14.1/types.ts";
interface Dictionary {
partOfSpeech: string;
language: string;
definitions: Definition[];
}
interface Definition {
definition: string;
examples?: string[];
}
interface List {
word: string;
language: string;
partOfSpeech: string;
definition: string;
examples?: string[];
}
export const API_URL = "https://en.wiktionary.org/api/rest_v1/page/definition";
function escape(text: string) {
return text
.replace(/<[^>]*>/g, "")
.replaceAll(" ", "")
.split(".\n ")
.map((str) => str.trim())
.join(".\n")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll("&", "&");
}
const outliers = [
"Alternative letter-case form of ",
"Misspelling of ",
"Alternative form of ",
"Alternative spelling of ",
"plural of ",
"Obsolete form of ",
"present participle of ",
"simple past tense and past participle of ",
"simple past tense of ",
"past participle of ",
"present participle and gerund of ",
"simple past and past participle of ",
"imperative of ",
] as const;
const languageCodes = ["en", "ml", "ta", "mr", "ja", "hi", "sa"];
async function api(word: string): Promise<List[]> {
const f = performance.now();
const dictionary = await fetch(`${API_URL}/${word}`)
.then((res) => res.json())
.then((res) => {
console.log(`API fetch time: ${performance.now() - f} ms`);
if (!res || ("title" in res && res.title == "Not found.")) return [];
const mainLanguages: Dictionary[] = [];
const otherLanguages: Dictionary[] = [];
for (const [key, value] of Object.entries(res)) {
if (languageCodes.includes(key)) {
mainLanguages.push(value as Dictionary);
} else {
otherLanguages.push(value as Dictionary);
}
}
return mainLanguages.concat(otherLanguages).flat();
})
.catch(() => []);
if (!dictionary?.length) return [];
const words = (dictionary as Dictionary[]).flatMap((dict) =>
dict.definitions.map((def) => ({
word: escape(word),
language: escape(dict.language),
partOfSpeech: escape(dict.partOfSpeech),
definition: escape(def.definition),
examples: def?.examples?.map((example) => escape(example)),
}))
);
return words;
}
async function recursiveFetch(list: List[]) {
const words = await Promise.all(
list.map(async (ele) => {
if (outliers.some((outlier) => ele.definition.startsWith(outlier))) {
const word = ele.definition
.split(" ")
.at(-1)
?.match(/[\s_\-'"\w]+/)
?.toString();
if (!word || typeof word !== "string") return [];
const relatedWords = await api(word);
return [ele, ...relatedWords];
}
return ele;
}),
);
return words.flat();
}
function filter(list: List[]) {
const unique = new Set<string>();
return list.filter((word) => {
const def = word.definition.trim();
if (!def.trim()) return false;
if (unique.has(word.definition.toLowerCase())) return false;
if ([outliers[0], outliers[1]].some((outlier) => def.startsWith(outlier))) {
return false;
}
unique.add(def);
return true;
});
}
function format({
word,
language,
partOfSpeech,
definition,
examples,
}: {
word: string;
language: string;
partOfSpeech: string;
definition: string;
examples: string[];
}) {
return (
`<b>${word}</b> (${partOfSpeech.toLowerCase()})` +
`\n[${language}]` +
"\n\n" +
`${definition}` +
"\n\n" +
`${
examples.length
? `Examples: \n${
examples
.slice(0, 10)
.map((eg) => `- <i>${eg.trim()}</i>`)
.join("\n")
}`
: ""
}`
);
}
export function createResults(
word: string,
dictionaries: List[],
): InlineQueryResult[] {
return dictionaries.map((def, widx) => {
return {
type: "article",
id: `${def.word}${widx}`,
title: `${def.language}: ${def.word} (${def.partOfSpeech.toLowerCase()})`,
description: def.definition,
input_message_content: {
message_text: format({
word,
language: def.language,
definition: def.definition,
examples: def.examples?.length ? def.examples.slice(0, 10) : [],
partOfSpeech: def.partOfSpeech,
}).slice(0, 4096),
parse_mode: "HTML",
},
reply_markup: new InlineKeyboard()
.row()
.switchInlineCurrent("Other definitions", word),
};
});
}
function emptyResult(word: string): InlineQueryResult[] {
return [
{
type: "article",
id: "thewatbotnotfoundtheword",
title: `No result found`,
input_message_content: {
message_text: `No definitions found for "<i>${word.toLowerCase()}</i>”`,
parse_mode: "HTML",
},
reply_markup: new InlineKeyboard()
.row()
.switchInlineCurrent("Try another word", word.slice(0, -1)),
},
];
}
export async function pipeline(word: string) {
if (typeof word !== "string" || word.trim() == "") return emptyResult(word);
const dictionaries = await api(word);
if (!dictionaries.length) return emptyResult(word);
const words = await recursiveFetch(dictionaries);
if (!words.length) return emptyResult(word);
const filtered = filter(words);
if (!filtered.length) return emptyResult(word);
return createResults(word, filtered);
}