Stretch0
Stretch0

Reputation: 9275

How to message a user in a slack App via API?

When creating a slack app, it creates a new "channel" in the left hand menu. I want to be able to send a message to specific users and not to all users in a workspace who have integrated with the app.

For example, if I make the following request:

curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/ABxxx/CDxxx/EFxxxxxx

It will send a message to all users who have integrated with my app with the text "Hello World".

But I only want to send a message to user A without User B being notified.

I don't want to message a user directly and it to appear to come from slack bot. I want the message to appear to come from my bot / app.

How can this be achieved via slack API?

I found this quite hard to explain so please let me know if you'd like me to clarify anything.

enter image description here

Upvotes: 4

Views: 8889

Answers (1)

Ruslan Isay
Ruslan Isay

Reputation: 1011

The problem of your request that you are using a hook URL which is bound to a particular channel (you pick it during Slack App installation).

To send a direct message to the user on behalf of your bot, you need to consider the following things (this is not the single way to achieve it, but works for me):

  1. Ensure you have a bot registered for your Slack App.
  2. Ask for bot and chat:write:bot permissions during App installation process (example for Slack Install button and here).
  3. Store the bot access token on successful installation (see for details).
  4. Now using the bot access token you can send Slack API requests.
  5. To achieve what you need, use chat.postMessage API method. channel argument can be user ID (e.g. U0G9QF9C6). By setting up as_user argument to true, your message will be always sent on behalf (name and icon) of your bot (seems for bot tokens it's always like this, but it's recommend it to specify it explicitly).

Hope it helps. Feel free to ask for details.

Upvotes: 3

Related Questions