Skip to content

Instantly share code, notes, and snippets.

@naveenarun naveenarun/slack.sh
Last active Jul 13, 2019

Embed
What would you like to do?
Bash function for sending a verbose slack message (containing path, command, error code, and custom message) after a process or series of processes exit
# Place this in your .bashrc
# Covers several corner cases such as nested apostrophes, history extraction in screens/subshells, Slack being down, etc.
# Strings to replace with your own credentials:
## {your email address} (1 instance)
## {slack webhook url} (1 instance) (see guide below)
## {your computer name} (2 instances)
# How to set up a Slack webhook (as of Jul 2019):
## Go here: https://api.slack.com/apps?new_app=1.
## Click “incoming webhooks” and turn the slider on
## Click “add new webhook to workspace”, select the “Slackbot” channel, and click Install
## Copy the webhook url that it creates. (You can then replace {slack webhook url} below with that url.)
slack() {
# Get slack message when a command exits
# Example usage: python long_job.py; slack
# Example usage: python long_job_1.py; slack 'job 1 done'; python long_job_2.py; slack 'job 2 done';
errorcode=$? # This has to go first; extracts error code
if [ -z "$1" ] # Allows you to attach a message as an argument for multi-step commands
then
message=" "
else
message=" with message '$1' "
fi
if [[ $errorcode -eq 0 ]] # Add emoji based on error code
then
erroremoji=":white_check_mark:"
else
erroremoji=":x:"
fi
myhistory=$(history | tail -n1 | sed 's/^ *[0-9]* *//g; s/\"/\\\"/g;') # Extract command from history
mydata='{"text":"`[{your computer name}:'$PWD']$ '$myhistory'` exited with status '$errorcode' '$erroremoji'"}'
returnstatus=$(curl -X POST -H 'Content-type: application/json' --data "$mydata" {slack webhook url})
if [[ $returnstatus == 'ok' ]] # Catch case when Slack is down or error message is syntactically invalid
then
echo 'Success'
else
echo 'bad request'
$(echo "Slack is down or message is invalid. Process finished at '$PWD'." | mail -s '{your computer name}: Slack is down or requested message is invalid.' '{your email address}')
fi
}
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.