Search code examples
node.jsslack-apislack

Respond with a rich message as a Slack bot


I'm working on a Node.js slack app containing a bot user. But I don't know how to respond to a user with a rich message as a bot.

Example:

I can respond with simple messages without problems using this code:

import * as SlackClient from '@slack/client';

slackBot = new SlackClient.RtmClient(bot_access_token)
slackBot.on(SlackClient.RTM_EVENTS.MESSAGE, message => {
    slackBot.sendMessage('Hello', message.channel);
});
slackBot.start();

But RTM API doesn't support rich messages:

The RTM API only supports posting simple messages formatted using our default message formatting mode. It does not support attachments or other message formatting modes. To post a more complex message as a user clients can call the chat.postMessage Web API method with as_user set to true.

so I tried to use the web client to respond with rich messages and moved to this code:

import * as SlackClient from '@slack/client';

slackWebClient = new SlackClient.WebClient(access_token);
slackBot = new SlackClient.RtmClient(bot_access_token)
slackBot.on(SlackClient.RTM_EVENTS.MESSAGE, message => {
    slackWebClient.chat.postMessage(message.channel, 'Hello', { attachments: myAttachments });
});
slackBot.start();

this approach is working when I testing the bot with my account. But if an other team user writes a DM to the bot, slackWebClient.chat.postMessage fails with the error error: channel_not_found. (I also tried to add a parameter as_user: true - but behaviour is the same, except that messages are signed with my name instead of bot name).


Solution

  • Solved: I created a SlackClient.WebClient instance with the Bot User OAuth Access Token instead of the OAuth Access Token (also with as_user set to true) and now it works as intended. I didn't know that the Bot User OAuth Access Token can be also used as a token for the Web API client.

    Working code:

    import * as SlackClient from '@slack/client';
    
    slackWebClient = new SlackClient.WebClient(bot_access_token);
    slackBot = new SlackClient.RtmClient(bot_access_token)
    slackBot.on(SlackClient.RTM_EVENTS.MESSAGE, message => {
        slackWebClient.chat.postMessage(message.channel, 'Hello', { attachments: myAttachments, as_user: true });
    });
    slackBot.start();