repl.it
@VesterDE/

Slack Slash Command Handler

Express

Small express app to show how to handle custom slack slash commands in an express app.

fork
loading
Files
  • index.js
  • Packager files
  • package-lock.json
  • package.json
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
const express = require('express');
const { WebClient } = require('@slack/client');
const bodyParser = require('body-parser');

// An access token (from your Slack app or custom integration - xoxp, xoxb)
// On repl.it this is defined inside the .env file, which is hidden to the public
// So if you fork this repl, create a .env file and put your own token inside it.
const token = process.env.SLACK_TOKEN;

// Create and authenticate a working Slack client with the token.
// To read more about this client, and the other available tools,
// go to https://slack.dev/node-slack-sdk/getting_started
const web = new WebClient(token);

// This argument can be a channel ID, a DM ID, a MPDM ID, or a group ID
// In this example case, the #testing channel is chosen. If you're unsure,
// type #random, which usually exists.
const conversationId = '#testing';

// Initialise the express app
const app = express();

// This will make req.body contain what we expect it to contain
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', (req, res) => {
	res.send('This is a get response. You can ignore it, as Slack sends post requests.');
});

app.post('/', (req, res) => {
  // req.body is where all the Slack data will be located
  const slackData = req.body;

  // It's completely ok to just send a response immediately, if the app makes 
  // sure to respond withing Slack's max request time of 150ms.
	res.send('Hello Slack! The user ' + slackData.user_name + " sent the " + slackData.command + " command with the text: " + slackData.text);

  // But if complex things need to happen, you can respond later, with the client.
  // Or even both ways, as we are doing in this app.
  complexRequestHandler(slackData);

});

async function complexRequestHandler(slackData){
  // Use the `auth.test` method to find information about the installing user
  const res = await web.auth.test()

  // Find your user id to know where to send messages to
  const userId = res.user_id

  const currentTime = new Date().toTimeString();
  // Use the `chat.postMessage` method to send a message from this app
  await web.chat.postMessage({
    channel: conversationId,
    text: `The current time is ${currentTime}, asked by the user ${userId}`,
  });
}
app.listen(3000, () => console.log('Server started!'));
?