/
discord.ts
81 lines (66 loc) · 2.42 KB
/
discord.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
import {Link, Store} from '../store/model';
import Discord from 'discord.js';
import {config} from '../config';
import {logger} from '../logger';
const {notifyGroup, webhooks, notifyGroupSeries} = config.notifications.discord;
function getIdAndToken(webhook: string) {
const match = /.*\/webhooks\/(\d+)\/(.+)/.exec(webhook);
if (!match) {
throw new Error('could not get discord webhook');
}
return {
id: match[1],
token: match[2],
};
}
export function sendDiscordMessage(link: Link, store: Store) {
if (webhooks.length > 0) {
logger.debug('↗ sending discord message');
(async () => {
try {
const embed = new Discord.MessageEmbed()
.setTitle('_**Stock alert!**_')
.setDescription(
'> provided by [streetmerchant](https://github.com/jef/streetmerchant) with :heart:'
)
.setThumbnail(
'https://raw.githubusercontent.com/jef/streetmerchant/main/docs/assets/images/streetmerchant-logo.png'
)
.setColor('#52b788')
.setTimestamp();
embed.addField('Store', store.name, true);
if (link.price)
embed.addField('Price', `${store.currency}${link.price}`, true);
embed.addField('Product Page', link.url);
if (link.cartUrl) embed.addField('Add to Cart', link.cartUrl);
embed.addField('Brand', link.brand, true);
embed.addField('Model', link.model, true);
embed.addField('Series', link.series, true);
embed.setTimestamp();
let notifyText: string[] = [];
if (notifyGroup) {
notifyText = notifyText.concat(notifyGroup);
}
if (Object.keys(notifyGroupSeries).indexOf(link.series) !== -1) {
notifyText = notifyText.concat(notifyGroupSeries[link.series]);
}
const promises = [];
for (const webhook of webhooks) {
const {id, token} = getIdAndToken(webhook);
const client = new Discord.WebhookClient(id, token);
promises.push({
client,
message: client.send(notifyText.join(' '), {
embeds: [embed],
username: 'streetmerchant',
}),
});
}
(await Promise.all(promises)).forEach(({client}) => client.destroy());
logger.info('✔ discord message sent');
} catch (error: unknown) {
logger.error("✖ couldn't send discord message", error);
}
})();
}
}