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

a 夏天 提交于 2019-12-11 11:30:16

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/54659096/how-to-message-a-user-in-a-slack-app-via-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!