curlslackslack-apihipchat

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


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?


Solution

  • @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