Search code examples
reactjstokenslack-api

How to post a message in an existing DM as a Slack Bot


My understanding of the chat.postMessage method of the Slack Web API is that you can, as a bot with a bot token, post messaged to public channels. However, if you want to post to DMs - you would need to request a user token and then post on behalf of the user

However, I've used a few apps that are able to post into DMs as an app (and therefore, I assume, are using a bot token). To me this is ideal, so you're not bugging every person in the Slack workspace to get their user token

Can anyone tell me how this is done?

For reference, here is the code I use to post a message as a bot. It does not work for DMs or for private channels the bot has not been invited to. Would love to fix that. Thanks

function getQueryString(data = {}) {
        return Object.entries(data)
          .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
          .join('&');
  }

function postMessageInSlack(bot_token, channelID, userID, message, send_blocks, endpoint) {
        const options = {
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        };
        const data = {
            token: bot_token,
            channel: channelID,
            text: `${message} from <@${userID}>`,
            blocks: JSON.stringify(send_blocks),
        }
        delete axios.defaults.headers.common["Content-Type"];
        axios.post(endpoint,
            data, {
            options,
            transformRequest: getQueryString}
        )
        .then(res => console.log("result is ", res))
        .catch(err => console.log("the error is ", err))
}

Solution

  • You need to open a new conversation with the user, that's if there was none open. To so this you need the conversations.open method. This will return a response that contains the conversation id. You can now use the conversation id in place of the channel id in your chat.postMessage method.