-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemegen.js
81 lines (68 loc) · 1.94 KB
/
memegen.js
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
require('dotenv').config();
const fetch = require('node-fetch');
const NodeCache = require('node-cache');
const BASE_URL = process.env.MEMEGEN_URI || 'https://api.memegen.link';
const cache = new NodeCache();
// Mostly because of too heavy
const excludedTemplates = { ptj: true };
const getMemeTemplatesNoCache = async () => {
const templatesLink = `${BASE_URL}/templates`;
try {
const resp = await fetch(templatesLink);
const list = await resp.json();
const templates = {};
const ids = [];
list.forEach((temp) => {
if (!excludedTemplates[temp.id]) {
templates[temp.id] = temp;
ids.push(temp.id);
}
});
return [ids, templates];
} catch (err) {
console.error('List meme err:', err);
return [[], {}];
}
};
const getMemeTemplates = async () => {
const cacheKey = 'templatesCache';
const result = cache.get(cacheKey);
if (!result) {
const data = await getMemeTemplatesNoCache();
if (data[0].length) {
cache.set(cacheKey, data);
}
return data;
}
return result;
};
const buildUrl = (key, texts, bg, height) => {
const textPath = texts.map((t) => t || '_').join('/') || '_';
const url = new URL(`${BASE_URL}/images/${key}/${textPath}.jpg`);
const font = texts && texts.length ? 'notosans' : null;
if (font) {
url.searchParams.set('font', font);
}
if (bg) {
url.searchParams.set('background', bg);
}
if (height) {
url.searchParams.set('height', height);
}
return url.toString();
};
const buildAttachments = (from, key, texts, bg) => {
const memeUrl = buildUrl(key, texts, bg);
return [
{
text: `From @${from}`,
image_url: memeUrl,
fallback: texts.join(' | '),
},
];
};
module.exports = {
getMemeTemplates,
buildAttachments,
buildUrl,
};