Skip to content

Commit 772c9ca

Browse files
committed
Added fromTemplate method.
1 parent 21d88fd commit 772c9ca

File tree

1 file changed

+56
-28
lines changed

1 file changed

+56
-28
lines changed

src/BetterEmbed.ts

Lines changed: 56 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,36 @@
11
import {MessageEmbed, MessageEmbedOptions} from 'discord.js';
22

3+
type AnyObject = { [k: string] : any};
4+
5+
const templates = {
6+
basic: {
7+
footer: {
8+
text: '${client.user.username}',
9+
iconURL: '${client.user.displayAvatarURL()}',
10+
},
11+
timestamp: new Date(),
12+
},
13+
color: {
14+
color: '#4b5afd',
15+
},
16+
get complete() {
17+
return {
18+
...this.basic,
19+
...this.color,
20+
title: '${title}',
21+
description: '${description}',
22+
};
23+
},
24+
get image() {
25+
return {
26+
...this.complete,
27+
image: {
28+
url: '${image}',
29+
},
30+
};
31+
},
32+
};
33+
334
export default class BetterEmbed extends MessageEmbed {
435
public static limits = {
536
author: {
@@ -17,34 +48,31 @@ export default class BetterEmbed extends MessageEmbed {
1748
},
1849
};
1950

20-
public static templates = {
21-
basic: {
22-
footer: {
23-
text: '${client.user.username}',
24-
iconURL: '${client.user.displayAvatarURL()}',
25-
},
26-
timestamp: new Date(),
27-
},
28-
color: {
29-
color: '#4b5afd',
30-
},
31-
get complete() {
32-
return {
33-
...this.basic,
34-
...this.color,
35-
title: '${title}',
36-
description: '${description}',
37-
};
38-
},
39-
get image() {
40-
return {
41-
...this.complete,
42-
image: {
43-
url: '${image}',
44-
},
45-
};
46-
},
47-
};
51+
static fromTemplate(template: keyof typeof templates | typeof templates | MessageEmbedOptions, values: AnyObject) {
52+
if (typeof template === 'string')
53+
if (templates[template]) template = templates[template];
54+
else throw new Error(`Template '${template}' not found.`);
55+
56+
template = JSON.parse(JSON.stringify(template));
57+
58+
function setValues(object: AnyObject, values: AnyObject): MessageEmbedOptions {
59+
for (const [name, value] of Object.entries(object)) {
60+
if (!object.hasOwnProperty(name)) continue;
61+
if (Array.isArray(value)) object[name] = value.map(v => setValues(v, values));
62+
if (typeof value === 'object') {
63+
object[name] = setValues(value, values);
64+
continue;
65+
}
66+
67+
const code = value.replace(/\$\{([^}]+)\}/gu, (_: any, value: string) => (values.hasOwnProperty(value.split('.')[0]) ? `\${values.${value}}` : value));
68+
object[name] = eval(`\`${code}\``);
69+
}
70+
71+
return object;
72+
}
73+
74+
return new BetterEmbed(setValues(template as AnyObject, values));
75+
}
4876

4977
public constructor(data?: MessageEmbed | MessageEmbedOptions) {
5078
super(data);

0 commit comments

Comments
 (0)