Building a Slackbot for Logging Node.js Application Activities

Building a Slackbot for Logging Node.js Application Activities

Building a Slackbot is a great way to automate notifications about app activities. We use Node.js to build a simple app and test the bot. Our bot will log all activities that happen in our Node.js application including errors into a channel that we will be creating soon.

Building a Slackbot is a great way to automate notifications about app activities. We use Node.js to build a simple app and test the bot.

Slack is a cloud-based instant messaging platform designed for companies to supplement email as a method of communication and sharing data. It also has cool features like sending messages to a channel using its webhooks_._

Webhooks are automated payloads sent from applications when something happens. It’s basically a way that applications can send automated messages or information to other application.

In this article, we will build a Slackbot to log all activities that happen in our application using Node.js. Our bot will log all activities that happen in our Node.js application including errors into a channel that we will be creating soon.


  • Basic familiarity with JavaScript
  • Node.js installed on your development machine
  • MongoDB installed on your development machine
  • Basic understanding of REST APIs

Project setup

Before we start building our bot, we have to create a simple Node.js application where users can create an account and log in. Our bot will log when a user has created an account; when an error occurred during account creation; when a user logs in with the correct credentials; and when a user has attempted login with the incorrect credentials.

We’ll be using the Express generator to create a new Express application, and then we’ll install all the necessary dependencies the we will need for our application. To do this, open up your terminal and type the following:

npx express-generator --no-view

After scaffolding the application, run npm install to install the project dependencies.

npm i axios bcrypt cors jsonwebtoken mongoose dotenv

With these installed, you will modify your app.js file like so:

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
    extended: false
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
module.exports = app;

Now we need to set up Mongoose for our application. Create a config/mongoose.js file and add the following code:

const mongoose = require("mongoose");
module.exports = app => {
    mongoose.connect("mongodb://localhost:27017/slackbot", {
        useUnifiedTopology: true,
        useNewUrlParser: true,
        useFindAndModify: false
    }).then(() => console.log("conneceted to db")).catch(err => console.log(err))
    mongoose.Promise = global.Promise;
    process.on("SIGINT", cleanup);
    process.on("SIGTERM", cleanup);
    process.on("SIGHUP", cleanup);
    if (app) {
        app.set("mongoose", mongoose);
function cleanup() {
    mongoose.connection.close(function () {

Running npm start will display connected to db on the console, which means exactly what you’d think it does.

Now let’s set up our models and controllers for the application. Create a models/users.js file and add the following:

const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const Schema = mongoose.Schema;
const userSchema = new Schema({
    name: {
        type: String,
        required: true,
    password: {
        type: String,
        required: true
    email: {
        type: String,
        required: true,
}, {
    timestamps: true,

userSchema.methods.hashPassword = async password => {
    return await bcrypt.hashSync(password, 10);
userSchema.methods.compareUserPassword = async (inputtedPassword, hashedPassword) => {
    return await, hashedPassword)
userSchema.methods.generateJwtToken = async (payload, secret, expires) => {
    return jwt.sign(payload, secret, expires)
module.exports = mongoose.model("User", userSchema);

Here we create a simple Mongoose schema for our user model and define functions that will hash the user’s password, compare the user’s password, and also generate a JWT token when the user login credentials are correct.

We’ll also create a controllers/users.js file and add the following code to it:

const User = require("../models/user");
exports.createNewUser = async (req, res) => {
    try {
        const user = new User({
            phone_number: req.body.phone_number,
            role: req.body.role
        user.password = await user.hashPassword(req.body.password);
        let addedUser = await
            msg: "Your Account Has been Created",
            data: addedUser
    } catch (err) {
            error: err
exports.logUserIn = async (req, res) => {
    const {
    } = req.body
    try {
        let user = await User.findOne({
            email: email
        //check if user exit
        if (!user) {
            return res.status(400).json({
                type: "Not Found",
                msg: "Wrong Login Details"
        let match = await user.compareUserPassword(password, user.password);
        if (match) {
            let token = await user.generateJwtToken({
            }, "secret", {
                expiresIn: 604800
            if (token) {
                    success: true,
                    token: token,
                    userCredentials: user
        } else {
            return res.status(400).json({
                type: "Not Found",
                msg: "Wrong Login Details"
    } catch (err) {
            type: "Something Went Wrong",
            msg: err

These are basic functions to create a user account and log a user in.

We have to modify our routes/user.js file to listen to our controllers that we created:

var express = require('express');
const controller = require('../controllers/user')
var router = express.Router();
/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});'/register', controller.createNewUser)'/login', controller.logUserIn)

module.exports = router;

You can use POSTMAN to test your login and register routes.

node javascript programming developer chatbot

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Top Node.js Development Companies and Expert NodeJS Developers

A thoroughly researched list of top NodeJS development companies with ratings & reviews to help hire the best Node.JS developers who provide development services and solutions across the world. List of Leading Node.js development Service Providers...

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

JavaScript Full Course - Beginner's Guide to JavaScript on Node.js

This complete 51-part JavaScript tutorial for beginners will teach you everything you need to know to get started with the JavaScript on Node.js. JavaScript Full Course - Beginner's Guide to JavaScript on Node.js

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Learning JavaScript: Development Environments for JavaScript Programming

One of the nice things about learning JavaScript these days is that there is a plethora of choices for writing and running JavaScript code. In this article, I’m going to describe a few of these environments and show you the environment I’ll be using in this series of articles.