Slack is an excellent messaging platform that allows teams to collaborate effectively. And if that collaboration moreover involves looking after multiple WordPress internet sites proper right here at Kinsta, you’ll switch some not unusual site-management tasks to Slack with the help of the Kinsta API.
Integrating a Slackbot into your workflow can save time and strengthen productivity. This educational combines the ability of Slack and the Kinsta API to build a Slackbot ready to managing tasks like checking internet web site status, clearing a internet web site’s cache, and restarting a internet web site’s PHP engine.
What You’re Building
Proper right here, you’re building a Slackbot on Node.js the usage of the Bolt API (the swiftest method to get began programming with the Slack Platform). Your instrument turns Slack’s slash directions into calls to the Kinsta API and relays responses so that all the shopper interaction happens in Slack.
Should haves
To use along with this endeavor, you’ll have the following:
- Elementary knowledge of JavaScript and Node.js
- Node.js fashion 12 or higher
- npm (Node Bundle Supervisor) installed in your laptop
- Slack workspace
Creating a Slack Application
A Slackbot is in large part a Slack instrument. To create a brand spanking new Slack instrument, practice the ones steps:
- Navigate to the Slack API dashboard.
- Click on on on the Create New App button, which is in a position to open a modal.
- Make a selection the From Scratch approach to get began building your app from the ground up.
- Provide a name on your Slack app. For instance, Kinsta Bot.
- Next, select the workspace where you want to position within the app and click on on Create App button.
Don’t hesitate to edit your app’s elementary knowledge by way of navigating to the Elementary Information risk on the sidebar. Scroll all of the manner all the way down to Display Information with the intention to upload details like an image, determine, description, color, and further.
Configuring oAuth and Permissions
You’ve successfully created a Slackbot. Then again, certain permissions must be granted to permit it to get right to use wisdom and perform actions within your Slack workspace. To get right to use the essential settings:
- Transfer in your Slack app’s dashboard and find the OAuth and Permissions risk inside the left sidebar.
- While you’re there, scroll all of the manner all the way down to the Scopes phase.
- Grant your bot the ability to be informed fast messages from consumers and answer to those messages.
Below is a screenshot showing the scopes you’ll have to provide in your bot:
By the use of configuring the ones scopes, your bot it will be supplied to interact seamlessly with Slack consumers and carry out its meant functions effectively.
Setting up Slack Bot to Your Workspace
To complete the process, you’ll have to arrange your new Slackbot within your Slack workspace. Navigate to the left sidebar and choose Arrange Apps. From there, click on on Set as much as Workspace and specify the channel where you’d like with the intention to upload the bot.
Your Slackbot is now ready. Let’s prepare a Node.js server that it will be used to procure and process your requests.
Atmosphere Up the Development Surroundings
To get started along with your new Node.js endeavor, create a brand spanking new record on your instrument and initialize it with npm:
mkdir my-express-app
cd my-express-app
npm init -y
After running the command above, a brand spanking new package deal deal.json document is created for your decided on record with default values. The package deal deal.json document is essential as it accommodates information about your endeavor and its dependencies. The ones dependencies will permit blank building and strengthen the potential of your endeavor:
@slack/bolt
: This JavaScript framework empowers you to rapidly create feature-rich Slack apps, leveraging the most recent platform options.nodemon
: A precious tool that mechanically restarts your Node.js instrument every time document changes inside the record are detected, ensuring a streamlined building workflow.dotenv
: This zero-dependency module plays a the most important serve as in loading surroundings variables from the .env document into theprocess.env
, making configuration management a breeze.
To place within the specified packages, execute the following directions:
npm i @slack/bolt
npm i --save-dev nodemon dotenv
After successfully putting in place the ones dependencies and dev dependencies, it’s time with the intention to upload a dev script in your package deal deal.json document, the usage of nodemon
to run your JavaScript document. Make sure that your package deal deal.json script object incorporates the following:
"scripts": {
"dev": "nodemon app.js"
}
In the end, it’s crucial to mention that the dev
script is pointing to a non-existent app.js document. Create this document for your endeavor’s record, as that’s the position the commonsense of your endeavor it will be handled.
touch app.js
Configuring Your Surroundings Variables (Tokens and Secrets and techniques and methods)
You’ll need specific tokens and secrets and techniques and methods to interact along with your Slack instrument from your Node.js endeavor. The ones credentials are subtle, and to ensure their protection when the usage of fashion control, we’ll store them inside the .env document.
To obtain the Signing secret, transfer in your Slack dashboard, click on on on Elementary Information, and then scroll all of the manner all the way down to App Credentials, where you’ll find the Signing Secret. For the token, click on on on Arrange App or OAuth & Permissions, and there you’ll find the OAuth Token. Normally, the Token starts with “xoxb”.
Create a document named .env inside the root record of your endeavor, and add the Signing Secret and Bot Token inside the following construction:
SLACK_SIGNING_SECRET="YOUR SIGNING SECRET"
SLACK_BOT_TOKEN="YOUR BOT TOKEN"
To make sure this subtle knowledge isn’t pushed in your Git provider, create a .gitignore record for your endeavor’s root record and add the following strains to disregard concerning the .env document and the node_modules folder:
/node_modules
.env
With this setup whole, you at the present time are ready to proceed with the server configuration.
Setting up the Node.js Server
Setting up the Node.js server is a key step in building your Slackbot. You wish to have to import essential packages and modules, initialize them, and set the port on which your endeavor will listen. Open the app.js document you created earlier and add the following code:
const { App } = require("@slack/bolt");
require("dotenv").config();
// Initializes your app along with your bot token and signing secret
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET,
});
(async () => )();
Inside the code above, you import the App
class from the @slack/bolt
library, a the most important phase for building Slack apps. Additionally, you utilize the dotenv
package deal deal to process surroundings variables.
Then, the app
constant is created the usage of the App
class, representing your Slack bot instrument. It calls for 2 crucial parameters: token
and signingSecret
. The ones values are fetched from the .env document.
Next, all through the async
function, the server setup occurs. The app is started by way of calling app.get began()
. It listens to port 3000
locally and logs a message to the console, confirming that the Kinsta Bot app is working.
Now, whilst you run the dev
script you configured (npm run dev
), you get the message for your terminal: “ Kinsta Bot app is working on port 3000!”
Understanding Slack API Socket Mode
In Slack API integration with Node.js servers, there are two primary methods of connection: the usage of most people HTTP endpoint of your server or the usage of Socket Mode to permit WebSockets. This educational focuses on the usage of Socket Mode, as it permits the implementation of interactive choices like Slack slash directions with higher ease. This system allows Slack to hook up with your Node.js server the usage of WebSockets instead of standard HTTP.
Then again, if you choose to use the HTTP endpoint locally, you’ll leverage ngrok to create a public URL that proxies in your localhost.
Getting Started With Socket Mode
To get started with Socket Mode, practice the ones steps:
- Navigate to Elementary Information on the left sidebar of your Slack dashboard. Scroll all of the manner all the way down to App-Stage Tokens and click on at the Generate Token and Scopes button.
- Give your token a name and add the two available scopes:
connections:write
andauthorizations:be told
. Click on on Generate to create the token. - Replica the generated token and paste it into your .env document, assigning it to a variable referred to as
APP_TOKEN
. Have in mind, app-level token strings get started withxapp-
.
Next, click on on on Socket Mode inside the sidebar, and toggle the Permit Socket Mode risk. Finally, for your app.js document, add socketMode:true
and your appToken
to the code that initializes your app/server:
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET,
socketMode: true, // permit socket mode
appToken: process.env.APP_TOKEN,
});
While you’ve completed the ones steps, all requests in your building server will occur by way of WebSockets reasonably than HTTP. This setup lets you benefit from Socket Mode and strengthen your Slackbot’s capacity.
Slack Slash Directions
Slash instructions are an excellent serve as in Slack that permits custom designed triggers for specific actions. The ones triggers can be detected in chat messages all through channels within Slack. Additionally, slash directions mean you can pass text wisdom without delay in your server. For instance, while you prepare a command like /operation_status [operation ID]
, it’ll pass the equipped operation ID
in your server and motive the corresponding operation_status
command listener.
Along with your server as it should be configured to interact with Slack, the next move is setting up slash directions that can motive actions in your server.
Creating Slash Directions on Slack
To create Slash Directions on Slack, click on at the Slash Directions menu risk on the left sidebar, then click on at the Create New Command button. Fill the following form the usage of the image beneath as a data.
After filling out the form, click on at the Save button. Slack will advisable you to reinstall the app in your workspace for the changes to take affect. Practice the instructions to create some slash directions, as confirmed inside the image beneath:
Configuring Slash Directions With Node.js
While you’ve created the essential slash directions, regulate your Node.js app to reply to them.
Let’s get started by way of checking out the /operation_status
command. Prepare a listener for events that include the /operation_status
command by way of together with the following code in your app.js document:
const { App } = require('@slack/bolt');
require('dotenv').config();
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET,
socketMode: true, // permit the following to use socket mode
appToken: process.env.APP_TOKEN,
});
app.command('/operation_status', async ({ command, ack, say }) => {
look forward to ack();
say('Wooah! Iit works!');
});
(async () => )();
Inside the code above, the point of interest is on the app.command()
function, which functions in a similar fashion to check listeners in JavaScript. You specify the command you need to pay attention for and then create an asynchronous callback function to stipulate the desired movement. This function takes 3 parameters:
command
: Comprises the details of the slash command sent by way of the shopper.ack
: Acknowledges the receipt of the slash command.say
: Sends a message once more to the Slack channel.
With the code above, the /operation_status
command in Slack will generate the message: “Wooah! it in point of fact works!”
Now, let’s add the command listeners for all the slash directions you’ve created:
app.command('/environment_id', async ({ command, ack, say }) => {
look forward to ack();
// Perform the desired movement the usage of the command and then send a response.
});
app.command('/site_id', async ({ command, ack, say }) => {
look forward to ack();
// Perform the desired movement the usage of the command and then send a response.
});
app.command('/operation_status', async ({ command, ack, say }) => {
look forward to ack();
// Perform the desired movement the usage of the command and then send a response.
});
app.command('/clear_site_cache', async ({ command, ack, say }) => {
look forward to ack();
// Perform the desired movement the usage of the command and then send a response.
});
app.command('/restart_php_engine', async ({ command, ack, say }) => {
look forward to ack();
// Perform the desired movement the usage of the command and then send a response.
});
Your app is now ready to pay attention for the Slack slash directions. It’s time with the intention to upload the actions every command will motive.
Implementing Slash Directions With Kinsta API
Your app will respond to every slash command with a option to the Kinsta API and then return the result of that movement to Slack. To use Kinsta’s API, you’ll have to have an account with no less than one WordPress web site, software, or database in MyKinsta. You’ll moreover wish to generate an API key to authenticate and get right to use your account throughout the API.
How To Create a Kinsta API Key
To generate an API key:
- Transfer in your MyKinsta dashboard.
- Navigate to the API Keys internet web page (Your determine > Company settings > API Keys).
- Click on on Create API Key.
- Make a selection an expiration date or set a custom designed get began date and collection of hours for the essential factor to expire.
- Give the essential factor a unique determine.
- Click on on Generate.
While you create an API key, copy it and store it somewhere safe, as that’s the one time you’ll see it. For this endeavor, save it for your .env document as KINSTA_API_KEY
.
Interacting With Kinsta API in Node.js
Interacting with the Kinsta API can be completed the usage of a lot of Node.js libraries, along with Axios. Then again, in this educational, we’ll opt for the JavaScript fetch()
manner, which is now supported and performs effectively inside the newest Node.js variations.
For this Slackbot, many API requests it will be made, along with GET and POST requests. To avoid repetition, store the API URL and headers in variables so that your code is simple to care for and skim:
// kinsta API utilities
const KinstaAPIUrl = 'https://api.kinsta.com/v2';
const getHeaders = {
Authorization: `Bearer ${process.env.KINSTA_API_KEY}`,
};
const postHeaders = {
'Content material material-Type': 'instrument/json',
Authorization: `Bearer ${process.env.KINSTA_API_KEY}`,
};
Forward of you get began coding your app’s response to every slash command, you’ll have to copy your Kinsta company ID and store it inside the .env document as KINSTA_COMPANY_ID
. It’s going to be needed to retrieve your internet web site tick list.
Implementing Surroundings ID Slash Command
While you use the /environment_id
slash command, any value equipped after the command it will be retrieved and used for your Node.js server. For this command, a marginally was once added to indicate that it expects a parameter: the [Site name]
.
Each internet web site on MyKinsta has a unique internet web site determine, alternatively there is no direct endpoint to request a internet web site’s surroundings ID the usage of its determine. Because of this, you first wish to make a request for all the internet sites in your company account, and then use the find()
method to in finding the internet web site whose determine fits the one passed with the slash command.
To reach this, two requests are made. First, to obtain the internet web site’s ID, and then you’re making every other request to the /environments
endpoint to retrieve the environment ID associated with that internet web site.
To care for code clarity and ease of maintenance, every request is made independently. This means having specific particular person functions for the ones requests and then calling those functions inside the command listener.
Let’s get started by way of fetching the tick list of all your internet sites:
async function getAllSites() {
const query = new URLSearchParams({
company: process.env.KINSTA_COMPANY_ID,
}).toString();
const resp = look forward to fetch(`${KinstaAPIUrl}/internet sites?${query}`, {
manner: 'GET',
headers: getHeaders,
});
const wisdom = look forward to resp.json();
return wisdom;
}
The code above will return an array containing all the internet sites. Inside the /environment_id
command listener, you’ll retrieve the response and store it in a variable. Then, the usage of the find()
manner, search for a internet web site whose determine fits the one passed from Slack. The information from Slack is stored in command.text
.
app.command('/environment_id', async ({ command, ack, say }) => {
look forward to ack();
let siteName = command.text;
let response = look forward to getAllSites();
if (response) {
let mySites = response.company.internet sites;
let currentSite = mySites.find((internet web site) => internet web site.determine === siteName);
// get surroundings ID
}
});
Now that you simply’ve the internet web site, use its ID to fetch the environment ID. Similar to after we queried for a list of internet sites, create a faithful function to make an HTTP request to the /environments
endpoint:
async function getEnvironmentId(siteId) {
const resp = look forward to fetch(`${KinstaAPIUrl}/internet sites/${siteId}/environments`, {
manner: 'GET',
headers: getHeaders,
});
const wisdom = look forward to resp.json();
return wisdom;
}
The code above expects the internet web site ID to be passed as a topic when calling this function inside the /environment_id
command listener. Upon receiving the ID, the API request is made, and the response is stored in a variable. Then, you’ll output the environment ID on Slack the usage of the say()
manner:
app.command('/environment_id', async ({ command, ack, say }) => {
look forward to ack();
let siteName = command.text;
let response = look forward to getAllSites();
if (response) {
let mySites = response.company.internet sites;
let currentSite = mySites.find((internet web site) => internet web site.determine === siteName);
let envIdResponse = look forward to getEnvironmentId(currentSite.identity);
let envId = envIdResponse.internet web site.environments[0].identity;
if (envId) {
say(`Just right day 👋,nnThe surroundings ID for "${siteName}" is 👉 ${envId}`);
}
}
});
At this point, whilst you open Slack and sort /environment_id
followed by way of a valid internet web site determine, paying homage to /environment_id fashionstored
, you’ll download a response that looks like this:
Implementing Web site Apparatus (Clear Web site Cache, Restart PHP Engine) Slash Command
Two tasks you’ll implement merely throughout the API and not using a wish to navigate to MyKinsta are the web site device operations Clear Web site Cache and Restart PHP Engine.
To perform any internet web site tools operation, all you need is the environment ID. This ID is used to make a POST request to the /internet sites/tools/clear-cache
and /internet sites/tools/restart-php
respectively. As you most likely did earlier, perform the API request independently and then return the response:
async function clearSiteCache(environmentId) {
const resp = look forward to fetch(`${KinstaAPIUrl}/internet sites/tools/clear-cache`, {
manner: 'POST',
headers: postHeaders,
body: JSON.stringify({
environment_id: environmentId,
}),
});
const wisdom = look forward to resp.json();
return wisdom;
}
async function restartPHPEngine(environmentId) {
const resp = look forward to fetch(`${KinstaAPIUrl}/internet sites/tools/restart-php`, {
manner: 'POST',
headers: postHeaders,
body: JSON.stringify({
environment_id: environmentId,
}),
});
const wisdom = look forward to resp.json();
return wisdom;
}
Next, you’ll create command listeners for every operations in Slack. The ones listeners it will be configured to motive every time the respective command is used:
app.command('/clear_site_cache', async ({ command, ack, say }) => {
look forward to ack();
let environmentId = command.text;
let response = look forward to clearSiteCache(environmentId);
if (response) {
say(
`Just right day 👋, nn${response.message} by way of the usage of the /operation_status slack commmand. nnOperation Identification is ${response.operation_id}`
);
}
});
app.command('/restart_php_engine', async ({ command, ack, say }) => {
look forward to ack();
let environmentId = command.text;
let response = look forward to restartPHPEngine(environmentId);
if (response) {
say(
`Just right day 👋, nn${response.message} by way of the usage of the /operation_status slack command. nnOperation Identification is ${response.operation_id}`
);
}
});
Inside the code above, the ideas retrieved from the API requests are used to construct the response sent once more to Slack. The response incorporates information about the operation, such since the message and the operation ID.
By the use of enforcing the ones slash directions and their corresponding listeners, you’ll empower your Slackbot to seamlessly interact with the Kinsta API, making it easier than ever to keep an eye on your internet web site’s cache and PHP engine without delay from Slack.
Implementing an Operation Status Slash Command
It’s going to also be excellent to get the status of your operations from Slack. You’ll use the /operations
endpoint alongside the operation_id
to do this. Like quicker than, create a function to care for this request and return the request response:
async function CheckOperationStatus(operationId) {
const resp = look forward to fetch(`${KinstaAPIUrl}/operations/${operationId}`, {
manner: 'GET',
headers: getHeaders,
});
const wisdom = look forward to resp.json();
return wisdom;
}
Let’s define the command listener to motive the request and pass the operation ID
sent by way of Slack:
app.command('/operation_status', async ({ command, ack, say }) => {
look forward to ack();
let operationId = command.text;
let response = look forward to CheckOperationStatus(operationId);
let operationMessage = response.message;
if (operationMessage) {
say(`Just right day 👋, nn${operationMessage}`);
}
});
Now whilst you use the /operation_status
slash command with any reliable operation ID
, you’ll get the status of the ID returned by way of Slack.
At the side of the directions you’ve already performed with the Kinsta API, there are further directions that can be integrated, along with additional events that can be handled by way of the Slackbot. For instance, the Slackbot can answer when mentioned or tagged the usage of the @
symbol.
To permit this capacity, you need to subscribe to the essential events in Slack. As an alternative of the usage of the app.command()
manner, you’ll take advantage of the app.message()
manner, which takes every the command
and say
parameters.
Proper right here’s an example of the way you’ll achieve this:
app.message("excellent day", async ({ command, say }) => {
say("Woah! It in point of fact works!");
});
After creating your Slackbot, it’s imaginable you’ll notice that you simply’re no longer ready to send messages to it. While you navigate to the bot underneath the Apps tab in Slack, it’s important to come across a message citing: “Sending messages to this app has been changed into off.” No worries, although, we will merely restore this!
To permit message sending, practice the ones steps:
- Click on on on the App Area menu risk located on the left sidebar.
- This internet web page allows you to prepare all settings on your bot. Scroll down until you to find the “Allow consumers to send Slash directions and messages from the messages tab” checkbox.
- Check the sector to permit this capacity.
While you’ve made the ones changes, it’s crucial to reload your Slack app to replicate the updates. Must you’re the usage of a Mac, you’ll reload Slack by way of pressing CMD + R. For various PC consumers, you’ll do so by way of pressing CTRL + R.
Now, you’re all set to send messages in your bot! Inside the Slack app, you’ll have to see the Kinsta Bot app listed slightly under the Your Apps phase. Click on on on it to start out out sending messages. Be happy to test any of your configured slash directions, and so they are going to must artwork flawlessly. Take pleasure in the seamless interaction along with your Slackbot!
The entire provide code for this endeavor is available on GitHub.
Deploying Your Node.js Application to Kinsta
While you assemble your Node.js server, it is important to deploy it so your Slackbot is always available, although you save you your local building. You’ll have the ability to deploy to Kinsta’s Utility Webhosting platform if your code is hosted on the Git providers Bitbucket, GitHub, or GitLab.
To deploy your repository to Kinsta, practice the ones steps:
- Log in in your Kinsta account on the MyKinsta dashboard.
- Click on on Add supplier.
- Make a selection Application from the dropdown menu.
- Inside the modal that appears, select the repository you want to deploy. When you’ve got multiple branches, you’ll choose the desired division and offers a name in your instrument.
- Make a selection one of the crucial available wisdom heart puts. Kinsta will come across and arrange your app’s dependencies from package deal deal.json, then assemble and deploy.
Finally, it’s not safe to push out API keys to public hosts like your Git provider. When web hosting on Kinsta, you’ll add them as atmosphere variables the usage of the an identical variable determine and worth specified for your building .env document.
While you start the deployment of your instrument, it’ll get started the process and maximum steadily whole within a few minutes. If any issues along with your Node.js configurations affect deployment, you’ll add a Node.js buildpack inside the deployment settings tab.
Summary
In this article, you are going to have learned assemble a Node.js instrument that connects Slack with the Kinsta API and deploy that instrument to Kinsta.
Slackbots and the Kinsta API make it easier so to apply and prepare your Kinsta-hosted services and products. Building on the basics of this educational, consider what you’ll do with a Slackbot and the API. Consider further difficult directions that perform operations like WordPress web site cloning and web site advent correct from Slack.
How are you the usage of Kinsta API? What choices do you need to see added/exposed next?
The put up How To Construct a Slackbot With Node.js and Kinsta API for Website Control gave the impression first on Kinsta®.
Contents
- 1 What You’re Building
- 2 Creating a Slack Application
- 3 Atmosphere Up the Development Surroundings
- 4 Understanding Slack API Socket Mode
- 5 Slack Slash Directions
- 6 Implementing Slash Directions With Kinsta API
- 7 Deploying Your Node.js Application to Kinsta
- 8 Summary
- 9 Step-by-Step Information For Atmosphere Up Divi Sprint
- 10 9 Reasons To Invest In Divi Pro During The Summer Sale (70% Off)
- 11 WordPress vs Webflow (2023) — Which is Better for Your Website?
0 Comments