Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
set -e
# Send a private message to someone on slack
# from the command line.
# Print a usage message and exit.
local name=$(basename "$0")
cat >&2 <<-EOF
${name} [user] [message]
You will also need to set \$SLACK_TOKEN for authentication.
You can generate a Web Api Token here:
exit 1
[ "$SLACK_TOKEN" ] || usage
# Print usage with --help or -h
if [ "$#" -lt 2 ]; then
local nick=$1
# get the users
local users=$(curl -sSL -X POST \
--data-urlencode "token=${SLACK_TOKEN}" \
--data-urlencode "presence=1" \ | jq '.members')
# find the user we want
local user=$(echo $users | jq '.[] | select(.name == "'${nick}'")')
if [[ -z "$user" ]]; then
echo "Could not find user with nick ${nick}."
return 1
# set presence and userid
presence=$(echo $user | jq --raw-output '.presence')
userid=$(echo $user | jq --raw-output '.id')
echo "Sending private message to:"
echo " User: ${nick}"
echo " Status: ${presence}"
local user=$1
# get the im channels
local channels=$(curl -sSL -X POST \
--data-urlencode "token=${SLACK_TOKEN}" \ | jq '.ims')
# find the user we want
local channel=$(echo $channels | jq '.[] | select(.user == "'${user}'")')
if [[ -z "$channel" ]]; then
echo "Could not find im channel with user id ${user}."
return 1
# set channelid
channelid=$(echo $channel | jq --raw-output '.id')
local nick=$1
local message=${*:2}
# get the users id
nick_to_userid ${nick}
# get the channel id for the im with this user
user_to_channelid ${userid}
local postresp=$(curl -sSL -X POST \
--data-urlencode "token=${SLACK_TOKEN}" \
--data-urlencode "channel=${channelid}" \
--data-urlencode "text=${message}" \
--data-urlencode "as_user=1" \
echo $postresp | jq .
send_message $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.