paint-brush
Writing a Slack Bot that Responds to Action Commandsby@tommyvn
1,320 reads
1,320 reads

Writing a Slack Bot that Responds to Action Commands

by Tom VNSeptember 24th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Writing a Slack Bot that Responds to Action Commands is a great place to start, but what wasn’t clear to me was that the example describes events, not actions, which is what I’ll describe here. You need to tell bolt that you want to listen for commands, not just events. Make sure your code explicitly says this because the example, at the time of writing this, doesn't mention this:const { App, LogLevel, ExpressReceiver } = require ( '@slack/bolt' )

Company Mentioned

Mention Thumbnail
featured image - Writing a Slack Bot that Responds to Action Commands
Tom VN HackerNoon profile picture

I recently wrote a slack bot that responds to action commands (like /ech yolo ) but I ran into some trouble finding exactly how to do this, so I’m documenting it here for other peeps to find. The exact error I hit was

/echo failed with the error "dispatch_failed"
 .

https://slack.dev/bolt-js/tutorial/getting-started Is a great place to start, but what wasn’t clear to me was that the example describes events, not actions, which is what I’ll describe here.

You need to tell bolt that you want to listen for commands, not just events. Make sure your code explicitly says this because the example, at the time of writing this, doesn’t mention this:

const { App, LogLevel, ExpressReceiver } = require('@slack/bolt');
const app = new App({
  token: process.env.SLACK_BOT_TOKEN,
  logLevel: LogLevel.DEBUG,
  signingSecret: process.env.SLACK_SIGNING_SECRET,
  endpoints: {
     events: '/slack/events',
     commands: '/slack/commands'  // explicitly enable commands
   },
});
/* Add functionality here */
app.command('/echo', async ({ command, ack, say }) => {
  // Acknowledge command request
  await ack();
  await say(`${command.text}`);
});


app.error((error) => {
  // Check the details of the error to handle cases where you should retry sending a message or stop the app
  console.error(error);
});
(async () => {
  // Start the app
  await app.start(process.env.PORT || 3000);
console.log('⚡️ Bolt app is running!');
})();

You need to set your webhook server’s url, including the /slack/commands path, in your slack apps command request URL like so:

If you would like a quick way to develop a slack app like this one locally check out my service https://localhost.run, it lets you put your local development environment on an internet accessible domain name with a single command, and it uses SSH so no signup or client download necessary.

Try it with this app now by running

ssh -R80:127.0.0.1:3000 localhost.run