-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
85 lines (76 loc) · 2.93 KB
/
server.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
82
83
84
85
import fastify from "fastify";
import rawBody from 'fastify-raw-body';
import { InteractionResponseType, InteractionType, verifyKey } from "discord-interactions";
import { SLAP_COMMAND, INVITE_COMMAND } from './commands.js';
const INVITE_URL = `https://discord.com/oauth2/authorize?client_id=${process.env.APPLICATION_ID}&scope=applications.commands`;
const server = fastify({
logger: true,
});
server.register(rawBody, {
runFirst: true,
});
server.get("/", (request, response) => {
server.log.info("Handling GET request");
});
server.addHook('preHandler', async (request, response) => {
// We don't want to check GET requests to our root url
if (request.method === 'POST') {
const signature = request.headers['x-signature-ed25519'];
const timestamp = request.headers['x-signature-timestamp'];
const isValidRequest = verifyKey(
request.rawBody,
signature,
timestamp,
process.env.PUBLIC_KEY
);
if (!isValidRequest) {
server.log.info('Invalid Request');
return response.status(401).send({ error: 'Bad request signature ' });
}
}
});
server.post("/", async (request, response) => {
const message = request.body;
if (message.type === InteractionType.PING) {
server.log.info("Handling Ping request");
response.send({
type: InteractionResponseType.PONG,
});
} else if (message.type === InteractionType.APPLICATION_COMMAND) {
switch (message.data.name.toLowerCase()) {
case SLAP_COMMAND.name.toLowerCase():
response.status(200).send({
type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: `*<@${message.member.user.id}> slaps <@${message.data.options[0].value}> around a bit with a large trout*`,
},
});
server.log.info('Slap Request');
break;
case INVITE_COMMAND.name.toLowerCase():
response.status(200).send({
type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: INVITE_URL,
flags: 64,
},
});
server.log.info('Invite request');
break;
default:
server.log.error('Unknown Command');
response.status(400).send({ error: 'Unknown Type' });
break;
}
} else {
server.log.error("Unknown Type");
response.status(400).send({ error: "Unknown Type" });
}
});
server.listen(3000, async (error, address) => {
if (error) {
server.log.error(error);
process.exit(1);
}
server.log.info(`server listening on ${address}`);
});