DEV Community

Jeff Shomali
Jeff Shomali

Posted on

Using Slack Webhook

What do you learn in this post?

  • You will learn how to create a Shell script.
  • You will learn how to backup up your database by a script.
  • You will learn how to automate your script by specif time of day.
  • Also, you will learn how to send a message to your Slack channel programmatically.

Overview

Just imagine that you have a Slack channel, and you wanted to get notified when something happened in your Linux/Unix machine. For instance, getting back up of something, or checking disk usage, monitor the network/process, or whatever you want to do in that machine manually. In this case, I assume you want to get a database backup and send a process success or failure message to your one of your Slack channels. Before to start this, you need to have a Slack account. The goal of this post is to take a backup every day and send a message to your Slack channel. Before to start this you need to have Slack

Create Script

  • Create your script.sh file in your machine.
  • Make your script executable by chmod u+x script.sh
  • Add your logic to it. For this case to get backup of MySQL database with mysqldump.

#!/bin/sh

date=`date +%Y%m%d`

mysqldump -h localhost -u root -p pass --single-transaction --quick databasename > jeff/backup/databse${date}.sql

if [ "$?" -eq 0 ]
then
    echo " Script is running - ${date}" >> jeff/dbbackup.log
     curl -X POST -H 'Content-type: application/json' --data '{"channel":"#<your channel name>","text":"<your message here>"}' https://<your-slack-chanel>.slack.com/services/hooks/<your hooks key>
else
    echo "Script failed to run on ${date}" >> jeff/dbbackup.log
    curl -X POST -H 'Content-type: application/json' --data '{"channel":"#<your channel name>","text":"<your message here> "}' https://<your-slack-chanel>.slack.com/services/hooks/<your hookks key>
fi

Enter fullscreen mode Exit fullscreen mode

You need to modify the <your message here>, <your channel name>, <your hooks key with your custom message and Slack webhooks' key. Where to get the key? follow next step

Create Slack Webhook

Add script to Cron jobs.

If you want to schedules a command or script on your server to run automatically at a specified time and date, please read the end of my last post.

Good luck 😉

Top comments (0)