How to send direct slack messages to users without a webhook?

3.3k views Asked by At

I am migrating some code from hipchat to slack. There is one hipchat curl command I used to send dm's to users that I want to convert over to slack:

msg='hello world'

curl --fail -d "$(jq -c -n --arg msg "${msg}" '{"message_format": "text", "message": $msg}')" \
  -H "Content-Type: application/json"  \
  -X POST "https://my.hipchat.server.com/v2/user/$USERS_EMAIL/message?auth_token=$HIPCHAT_TOKEN"

Lets say all I have is a bot token and the email of the user account I want to send a message to (with no webhook setup). How can I send a message to that user? What is the exact curl structure I would use?

2

There are 2 answers

0
Alex Cohen On BEST ANSWER

@Savageman had it mostly correct. The only difference is that you need to use im.open. Here is my working code:

msg='the text yall want to send'
user_id="$(curl -X GET -H "Authorization: Bearer $SLACK_TOKEN" \
  -H 'Content-type: application/x-www-form-urlencoded' \
  "https://slack.com/api/users.lookupByEmail?email=$EMAIL" | jq -r .user.id)"

channel_id="$(curl -X POST -H "Authorization: Bearer $SLACK_TOKEN" \
  -H 'Content-type: application/x-www-form-urlencoded' \
  "https://slack.com/api/im.open?user=$user_id" | jq -r .channel.id)"

curl -X POST -H "Authorization: Bearer $SLACK_TOKEN" \
  -H 'Content-type: application/json' \
  --data "$(jq -c -n --arg msg "${msg}" --arg channel "${channel_id}" '{"channel":$channel,"text": $msg}')" \
  https://slack.com/api/chat.postMessage
0
Savageman On

You can't do it in a single command.

  1. Get the User ID using users.lookupByEmail
  2. Make sure the DM is open using dm.open (this will also give you the channel ID for the direct message with that user)
  3. Send the message with chat.postMessage