loading...
Cover image for A simple Slack bot with Crontab and JavaScript

A simple Slack bot with Crontab and JavaScript

killianfrappartdev profile image Killian Frappart ・3 min read

Hello everyone 👋

I am still engaged in my coding bootcamp, and we are using Slack to stay in touch and share courses resources.

One of my classmate and me built a really simple bot that notify everybody when it is time for daily stand up or lunch break.

Powered by our instructor, we achieved this using NodeJS, Cron job and AWS.

I thought it could be interesting to share the building process with you 😇.

Slack API

Let's start by diving into Slack API Documentation which is in my opinion extremely well written.

They literally did half the job for us! If we look for "sending message" we will probably be redirected to the webhook section.

Head over to "Your apps" and create a new one, give it a name and select the workspace. We can now add features to our app by enabling webhooks for example.

Alt Text

However, we need a URL to reach our app. At the very bottom we are allowed to add our app to a channel in our workspace and it will automatically generate the corresponding URL.

Before we move on to the next step, make sure our app has permission to send messages and our app is correctly installed in our workspace.

Node Script

Alright, we have our app able to write messages, but alone it won't do much...

We are about to write a very simple node script that send HTTP requests directly to Slack API through the URL we received when we installed our app.

//Environement variable
require('dotenv').config({ path: __dirname + '/.env' });


//Import Axios & MomentJS
const axios = require('axios');
const moment = require('moment-timezone');

//Get Time
const currentTime = moment.tz("Europe/Brussels");

//Messages array
const MESSAGES = [
  'Daily Stand Up in 10 minutes 🔥',
  "Lunch Break 🍔",
  'Good job everybody! 🏠',
];

//Pick message depending on current time
let currentMessage;
if (currentTime.hours() === 8 && currentTime.minute() === 50) {
  currentMessage = MESSAGES[0];
} else if (currentTime.hours() === 12 && currentTime.minute() === 30) {
  currentMessage = MESSAGES[1];
} else {
  currentMessage = MESSAGES[2];
}

//HTTP Request
const sendMessage = async () => {
  try {
    axios.post(
      process.env.SLACK,
      { text: currentMessage },
      { headers: { 'Content-type': 'application/json' } }
    );
  } catch (error) {
    console.log(error);
  }
};

sendMessage();

node script.js

It would be an awful idea to push the URL to our GitHub right? Work with .env and .gitignore files to avoid this mistake.

When this script is executed, an HTTP request is sent to our app and carries the message that will be displayed in our Slack's channel.

AWS Cloud server

Our code is working locally on our machines, but we are not going to manually execute that code ourselves right ?

Here is the solution we came up with, we are going to create an instance of a Linux machine that runs in the cloud.

AWS comes to the rescue! Create an account and head over to EC2's section.

It is very straightforward, in a couple clicks we can set up a Linux instance and connect via ssh. Store your ssh key preciously 🔑

Alt Text

Now we want to access our instance and to do so, look in the console for the "connect" button and choose ssh client.

By following instructions, we should be able to access our cloud instance from the terminal and it is time to set everything up.

At first, we notice that node and npm are not installed.

sudo apt install nodejs

Thereafter, we clone our script from our remote repository (GitHub for example) and install dependencies.

Cron

We are almost done! Cloud server is live and our script works just fine. The very last thing we are going to work on is some way to schedule our script execution.

You may already have heard of Cron job before, it is well known of Unix users and allow us to schedule any task we want.

It is really easy to get started with, look at this.

crontab -e

Alt Text

Conclusion

✅ App is installed in our Slack's channel and able to write messages.

✅ There is a working Node script that reaches out to our app.

✅ A Linux instance is running on AWS.

✅ Our script is automatically executed thanks to Cron job.

That was a quick summary of the building process.

Thank you for reading! 😇

Discussion

pic
Editor guide