-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
73 lines (66 loc) · 1.87 KB
/
index.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
var https = require("https");
var express = require("express");
var app = express();
var PORT = process.env.PORT || 5000;
app.use(express.json()).post("/", async (req, res) => {
var whId, whToken;
try {
[whId, whToken] = getWebhookParts(req.query["q"]);
}
catch {
res.status(400);
res.end(`Send a POST request with Discord webhook address as query parameter q.\n
For example, "/?q=https://discordapp.com/api/webhooks/728789913434980374/DIUrFtsKzpHePKP895wnIK6lSbTaBIhn6xQaaL48e9E8gP5ZEpNesTQGeLRuXvrMNRUd"
`);
return;
}
var text, url;
try {
var {
message: { text },
resource: { _links: { web: { href: url } } },
} = req.body;
} catch {
res.status(400);
res.end(
"Request body must conform to { 'message': { 'text' : <string> }, 'resource': { '_links': { 'web' : { 'href' : <string> } } } }"
);
return;
}
var discordRequest = https.request(
{
method: "POST",
host: "discordapp.com",
path: `/api/webhooks/${whId}/${whToken}`,
},
(discordRes) => {
res.status(discordRes.statusCode);
discordRes.setEncoding("utf8");
discordRes.on("data", (chunk) => {
console.log("Discord Response: " + chunk);
res.write(chunk);
});
discordRes.on("end", () => {
res.end();
});
}
);
discordRequest.setHeader("Content-Type", "application/json");
discordRequest.write(
JSON.stringify({
content: !!url ? `${text}\r\n${url}` : text,
})
);
discordRequest.end();
});
app.listen(PORT, function () {
console.log(`Example app listening on port ${PORT}!`);
});
function getWebhookParts(str) {
var whRegex = /(\d+)\/([\w\d]+)\/?$/;
var whParts = whRegex.exec(str);
if (whParts.length !== 3) {
throw new Error("Discord webhook address must have format of '.../<webhook id>/<webhook token>'");
}
return [whParts[1], whParts[2]];
}