Slack notifications from scripts

Slack icon

I find Slack extremely useful for collaborating with a team. It's also great for quickly and easily getting notifications about the status of a script that's running on a remote computer somewhere. In my case, I'm running bioinformatics pipelines that take hours or days to run. Slack notifications tell me when programs finish running, or if something odd has happened.

Below are two code snippets I've found useful:

Python class to set up Slack notifications

I wrote the SlackNotifier() class below to send out messages during major steps in my computational pipelines. It gets initialized in the beginning (webhook URL, channel name, etc.), and the "sendMessage()" method gets called every time I want to send a notification to the Slack channel.

  1. import json
  2. import requests
  3. import socket # just to get hostname. Use os.uname()[1] if already importing os
  4.  
  5. class SlackNotifier(object):
  6. """
  7. A class to help send informative messages to our slack channel
  8. about the progress of pipeline scripts that can run for hours or days.
  9.  
  10. To use:
  11.  
  12. 1) Turn on "Incoming webhooks" for the slack channel you want:
  13. In the Slack web interface, pick a channel and "add an app"
  14. Find "Incoming WebHooks" and add it.
  15. This will give you the webhook URL to use
  16.  
  17. 2) Import the code here into your project, and then declare a SlackNotifier object,
  18. with the webhook and channel name as arguments.
  19.  
  20. 3) Use the sendMessage(msg,title) method to send msg to the channel
  21.  
  22. Example:
  23.  
  24. slack = SlackNotifier("webhook_url_for_slack_api", "channel-name")
  25.  
  26. slack.sendMessage(msg='This is a test message from SlackNotifier()',
  27. title='Test message title',
  28. subtitle='subtitle',
  29. emoji=':computer:')
  30.  
  31.  
  32. List of emojis can be found here:
  33. <a href="https://www.webpagefx.com/tools/emoji-cheat-sheet/
  34. ">https://www.webpagefx.com/tools/emoji-cheat-sheet/
  35. </a>
  36.  
  37. Armin Hinterwirth, 2017
  38.  
  39. """
  40. def __init__(self, webhook_url, channel_name):
  41. self.webhook_url = webhook_url
  42. self.channel_name = channel_name
  43. self.host_name = socket.gethostname() # Uses the current computers host
  44. # name for the header of the message
  45.  
  46. def sendMessage(self, msg, title, subtitle='Message', emoji=":sunglasses:"):
  47. """
  48. Send the msg as JSON object to specified channel
  49.  
  50. JSON format found in: <a href="https://github.com/sulhome/bash-slack
  51. ">https://github.com/sulhome/bash-slack
  52. </a> Emojis: <a href="https://www.webpagefx.com/tools/emoji-cheat-sheet/
  53. ">https://www.webpagefx.com/tools/emoji-cheat-sheet/
  54. </a> """
  55. self.msgdata = {
  56. "channel": self.channel_name,
  57. "username": self.host_name,
  58. "icon_emoji": emoji,
  59. "attachments": [
  60. {
  61. "fallback": title,
  62. "color": "good",
  63. "title": title,
  64. "fields": [{
  65. "title": subtitle,
  66. "value": msg,
  67. "short": False
  68. }]
  69. }
  70. ]
  71. }
  72. # contact the Slack server:
  73. response = requests.post(
  74. self.webhook_url,
  75. data=json.dumps(self.msgdata),
  76. headers={'Content-Type': 'application/json'}
  77. )
  78.  
  79. if response.status_code != 200:
  80. raise ValueError(
  81. 'Request to Slack returned error:\n{}. Response is:\n{}'.format( \
  82. response.status_code,
  83. response.text)
  84. )
Code is also here:

https://bitbucket.org/snippets/amphioxus/yeoREy/slacknotifier-to-send-me...

Get notified on Slack about a change in the IP address of your server

It happens rarely, but sometimes my ISP assigns a new IP address to my home server. If this happened while I'm away, it would be impossible for me to log into my computer. I use the following shell script to get notified of such a change. (I set it up to run once every hour with a cron job.)

#!/usr/bin/env bash
 
# Settings for slack notification:
WEBHOOK_URL="THE-URL-YOU-GET-WHEN-SETTING-UP-WEBHOOK-FOR-A-CHANNEL"
CHANNEL="channel-name"
USERNAME="username"
LASTIPFILE='/home/youruser/.last_ip_address'; # Where the last checked IP address is stored
 
# Get public ip address
# See: unix.stackexchange.com/a/81699
MYIP=$(dig +short myip.opendns.com @resolver1.opendns.com);
 
LASTIP=$(cat ${LASTIPFILE});
 
if [[ ${MYIP} != ${LASTIP} ]]
then    
        echo "New IP Address = ${MYIP}"
        echo ${MYIP} > ${LASTIPFILE};
        MESSAGETEXT="IP address has changed. It is now: $MYIP"
        JSON="{\"channel\": \"$CHANNEL\", \"username\":\"$USERNAME\", \"icon_emoji\":\"house\", \"attachments\":[{\"color\":\"danger\" , \"text\": \"$MESSAGETEXT\"}]}"
 
        curl -s -d "payload=$JSON" "$WEBHOOK_URL"
else
    echo "IP address (${MYIP}) has not changed."
fi

Code snippets on Bitbucket

https://bitbucket.org/snippets/amphioxus/
Category: 
Code