01 - Programming (EN)03 - Open Source (EN)03b - Node.js (EN)

Sending Slack messages with NodeJs from IBM i

Premise

Slack is software that falls into the category of corporate collaboration tools used to send messages instantly to team members (wikipedia). It is possible to organize communications through specific channels, generate interactions with notifications, communicate with innovativ
e methods. This article illustrates how, through a NodeJs application, messages can be sent or interactions between the management system residing in the IbmI and a Slack channel.
The article illustrates the method of interacting with the chat, and specifically an application that communicates the daily order, divided by customer, to the chat channel of the corporate workspace.
The idea is to generate a daily communication to be sent to the sales department.
This method can be used to generate notifications of system errors, execution process management messages, notifications regarding a commercial action, etc. The mes
sage can be enriched. with images, emoticons, buttons, interaction functions and much more.

Prerequisites

  • Operating system 7.2 or higher.
  • Nodejs v10.15.3 or higher.

Registration App Slack

First you need to create a new workspace in slack https://slack.com/intl/en-it/, through the use of email. After
opening the workspace and the channels, proceed with the activation of the incoming webhooks (See the pdf below). The
main difference between Webhook and API is subtle, since both services are used to move data between apps. With APIs, you get data from the provider, while notifications allow the provider to send you the data. Basically there is an answer in the API, the Webhooks simply send the data.

Nodejs application

Let’s create in the home path of our profile / home / user / … a folder that we will call slack and where we will build the application inside.



Ibmi.js module


This function is intended to access the ibmi database.
The connector is the idb-pconnector.
The connection is made through an async function and the return is a json.

The node command for installation is as follows: npm install idb-pconnector.h
ttps: //www.npmjs.com/package/idb-pconnector

const {Connection} = require ('idb-pconnector');
var dateFormat = require ('dateformat');
 
var datetime = new Date ();
today = dateFormat (datetime, "yyyymmdd");   
const sql = 'SELECT ragsoc, decimal (sum (qtaord * price), 7,0) val FROM library.testataOrd a' +
            'inner join library.detailOrd b on a.tpdoc = b.tpdoc' +
            'and a.nrord = b.nrord' +
            'inner join library.anagaCli on codcli = a.codcli' +
            'where a.dtord =' + today +
            'group by ragsoc'  
            ; 
async function db () {
  try {
    let statement = new Connection (). connect (). getStatement ();
 
    let result = await statement.exec (sql);
    c = JSON.stringify (result)
    return c
 
  } catch (error) {
       console.error (`Error was:  n $ {error.stack}`);
    }
}

module.exports = {
      db
 }; 


MsgSlack.js module

here is the https call to the slack provider (xxxxxxxxx ….. it is the code that must be copied from the subscription to the slack webhook
service) .To this function the return json is passed by the ibmi.js function and through a loop, the ordered value of each customer is communicated.

var SlackWebhook = require ('slack-webhook')
var slack = new SlackWebhook ('https: //hooks.slack.com/services/xxxxxxxxx .....', {
  defaults: {
    username: 'Gianpiero',
    channel: '#general',
    icon_emoji: ': robot_face:'
  }
})
function sendMsg (db) {
console.log ('send:', db)
var myArray = eval ("(" + db + ")")
for (var i = 0; i <myArray.length; i ++) {
     slack.send ({
        "blocks": [
                    {
            "type": "section",
            "block_id": "section789",
            "fields": [
              {
                "type": "mrkdwn",
                "text": "* Ordinate of the day *  n" + (myArray.[i]ragsoc + '' + myArra[i]y.VAL)
              }
            ]
          }
        ]
     ,
      attachments: [
        // optional attachment data
      ]
      username: 'new username',
      icon_emoji: ': scream_cat:',
      channel: '#general'
    })  
    
} 
   }
   module.exports = {
        sendMsg
     }; 

AppSlack.js module

This is the module that manages the entire application and brings the two previous modules together.
With require the previously created modules are imported.

const ibmi = require ('./ ibmi')
const msg = require ('./ msgSlack')

async function start () {
const db = await ibmi.db () 

console.log ('Json:', db)
msg.sendMsg (db)
var myArray = eval ("(" + db + ")")
}
start ();
 

Application execution

The application can be launched in several ways:
– Interactive mode (call qp2term)
. – Batch mode (qsh).

To set the parameters for the automatic execution of the application it is necessary to configure a profile file in the etc folder and a .profile file in the user home user folder:

profile
PATH = / QOpenSys / pkgs / bin:
$ PATHexport

PATH.pro
filenode /home/QPGMR01/slack/appSlack.js

Example of interactive launch from an rpgfree program that we called slack:

CTL-Opt OPTION (* SRCSTMT: * NODEBUGIO)  
DFTACTGRP (* No);                      
dcl-pr qp2term ExtPgm ('QP2TERM');    
END-PR;                              
callp qp2term ();                     
* * INLR = On;                           

Run the slack program by logging into the session with the user with whom the nodejs application was created in the system.
Call slack

The console.log commands entered in the node application are displayed in the SSH console

The message is sent to the slack platform from which we can access from the browser or better on the move from any device.

Conclusion

It is important to identify the most appropriate technologies in the analysis of business processes to accelerate innovations. This is one of many that can be implemented to provide quality services, such as by sending market notifications to a commercial department or making communications through chat channels more efficient. Slack also contributes to enriching the offer of products and services useful to companies to be competitive and to generate added value from the team’s work. The company is made up of people and everything is useful to strengthen the responsibility of each of us and the quality of the services offered.

About author

Project manager, business management consultant, application development with Rpgfree, Python, JavaScript. I entered the IT world when the As400 was born, I am a supporter of the Ibm-I platform and its enormous potential and I believe in the resources offered by the community by open source. I am grateful to collaborate with FAQ400 because I fully share the objectives.

Leave a Reply

%d bloggers like this: