Search code examples
slackslack-api

How to post ephemeral messages in all direct messages channels?


I have created a Slack app which after a user performs an action, is supposed to post an ephemeral message with the result of this action. However, when trying to send a message into a direct messages channel in which the user who installed the app isn't part of, I get a channel_not_found error.

With the legacy workspace apps, this problem was easily solvable as the slack app could be invited to a direct messages channel and hence would get the permission to post to the channel. However, with the new approach forced by Slack to use only bot and user tokens, it doesn't seem very easy to solve. The bot can't join a direct message channel and hence can't get the permission to post in these channels.

Are there any straight forward ways to solve this issue ?


Solution

  • If you want to post an ephemeral message in response to an action you just have to use the response_url from slack's request and send a POST request to this url with a JSON payload containing the ephemeral message.

    See https://api.slack.com/actions #Responding to Action for further information.

    Here is my code in Golang (I am using the slack package from nlopes : https://godoc.org/github.com/nlopes/slack)

        msg := slack.Msg{
            Attachments: []slack.Attachment{
                attach,
            },
            ResponseType: "ephemeral",
        }
    
        b, err := json.Marshal(msg)
        if err != nil {
            err = errors.Wrap(err, "Post failed")
            logger.LogError(err)
            return nil
        }
        reader := bytes.NewReader(b)
        _, err = http.Post(
            c.ResponseURL, // the response URL from slack request
            "application/json",
            reader,
        )