-
-
Save stympy/cbb6108cf0c454f72a0fd062b8f1380d to your computer and use it in GitHub Desktop.
Function for sending a verbose slack message (containing path, command, error code, and custom message) after a process or series of processes exit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) | |
## {your computer name} (2 instances) | |
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