How to Create a Slack Bot to Invoke GitHub Actions via Hubot

choubertsprojects

The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

There are many ways to use a slack bot, for example Hubot could be used as a GitHub action. This is because the GitHub API has an endpoint of /hubot/commands that returns all commands available in Slack. The following is a brief tutorial on how to create this sort of piece of software with NodeJS and Socketio. If you want to create a slack bot and you can’t do it yourself, you can contact a professional software development team for help.

“hubot-slack interactive message” is a way to create a Slack bot to invoke GitHub actions. It’s an easy step by step process that anyone can follow.

How to Create a Slack Bot to Invoke GitHub Actions via Hubot

Did you know that if you use GitHub Actions as your build and release workflow and your team also utilizes Slack, you’ll never have to leave it? Create a Slack bot to automatically launch GitHub Actions processes from Slack!

In this article, you’ll learn how to use Hubot, a bot-building tool, to create a new Slack chatbot that will automatically launch a GitHub Actions process to push code to a server.

Let’s get started!

Prerequisites

This will be an interactive presentation. If you want to follow along, make sure you have these items:

  • Working in Slack
  • A GitHub account as well as a GitHub personal token are required.
  • To deploy code, you’ll need a Linux server – Ubuntu 19.04 will be used in this lesson.
  • A local Linux system – Ubuntu will be used in this lesson, thus all local commands will be in Linux. The instructions may alter somewhat if you’re using a different operating system.
  • To connect to the server where you’ll be delivering code, you’ll need SSH credentials.
  • Visual Studio Code or another code editor that understands YAML.

Using Git Hooks to Automate Client-Side Git Actions

Workflow for Creating a Project and GitHub Actions

You must first establish a GitHub Actions process before you can rapidly launch it from Slack.

Let’s start by creating a project folder to house all of the files you’ll be working with.

Related: How to Setup Visual Studio Code on GitHub!

1. Launch your preferred terminal program.

2. Now execute the following commands to create the Hubot project folder and browse inside it.

mkdir /Hubot # Create a Hubot directory cd /Hubot # Change to Hubot’s directory.

3. Next, run npm init to build a package.json file for Node.JS. When you run npm init, you’ll get a typical Node.JS project with a package.json file that provides information about the project and any NPM packages it depends on.

# Initializes the package.json file using npm init

Create a workflows directory and a deploy.yml workflow file now. The workflow file is a set of steps that GitHub Actions will execute in a certain order.

mkdir .github/workflows && touch deploy.yml

5. After that, specify which GitHub secrets your process will read. These secrets will be referenced in the process you’re going to develop. Let’s make GitHub secrets since you’ll need your server IP, username, password, and port to SSH.

You may add your GitHub secrets at https://github.com/yourusername/yourrepository/settings/secrets/actions. Replace yourusername and yourrepository with your GitHub username and repository, respectively.

Fill in the details about the secret you’re creating by clicking the New repository secret button, as shown below.

Adding Secrets to GitHubAdding Secrets to GitHub

6. Fill in the Name and Value fields for the secret, then click Add secret to preserve it. This will take you to the GitHub secrets page, where you can view all of your secrets. As before, click on the New repository secret button to add additional secrets.

Make sure you preserve secrets for supplied variables with the same name since you’ll be referring the same variables: HOST, USERNAME, PASSWORD, and PORT.

Filling up the Details for a GitHub SecretFilling up the Details for a GitHub Secret

Seeing Every GitHub Secret Seeing Every GitHub Secret

7. Finally, in your code editor, open the /Hubot/.github/workflows/deploy.yml workflow file and copy/paste the following code. The workflow code below will execute whenever the workflow is triggered later through Slack.

When you start the process, it will do the following tasks:

  • With the USERNAME and PASSWORD provided as secrets, GitHub Actions will parse the workflow file below to SSH into the destination host indicated in the HOST secret.
  • The process will then execute git pull origin$branchName to obtain the contents of the GitHub repo for a given branch ($branchName). Make sure the name of the branch includes the code you want to deploy.
  • You’ll be utilizing the ssh-remote-commands Workflow Package from Github Marketplace. To run on production, this package provides a nice wrapper where you simply need to give host, username, password, port, and command.

Make sure your server has git installed, as well as the login credentials needed to fetch code from the GitHub repository.

# Name that will be used to reference it programmatically name: deploy on: # The event respository dispatch indicates that this whole file is performed on every API trigger. [deploy-service] type # There may be several jobs, but for the time being, this lesson will just focus on one: deploy: Deploy (name) # The name of the base image on which all YAML codes are executed: ubuntu-latest steps: – name: utilizing password to execute remote ssh commands # appleboy/[email protected] It’s an open-source software that # connects to a server through ssh and runs the script appleboy/[email protected] # These are the variables that the package need to connect to the server and run the script: # The variables from https://docs.github.com/en/actions/reference/encrypted-secrets are the secrets. # Your server’s host is kept in github secrets under the same name: $ secrets.HOST # To login, use your server’s username, which is saved in github secrets under the term USERNAME username: $ secrets.USERNAME # The password to access to your server, which is kept on github secrets under the name PASSWORD password: $ secrets.PASSWORD # Login port on your server, which is recorded on github secrets under the term PORT port: $ secrets.PORT # deploy-app.sh may be anything, such as pulling code from GitHub and restarting your webserver or queueing anything. # Make sure you have a cloned repo on your server. git pull origin github.event.client payload.branch github.event.client payload.branch

Manually Executing the Workflow

You’ve just developed a Slack-based GitHub Actions process. However, at this moment, your code is only available on your local system. You’ll need to submit code to GitHub to start the procedure.

Running the instructions below instructs git where the code should be pushed and fetched from, in this case, your remote GitHub repository. Replace yourusername and yourrepository with your GitHub username and repository in the git remote add origin command below.

# Go to github.com and create a repository using the git init command. # Git remote add origin https://github.com/yourusername/yourrepository.git git add git commit -m “Produced GitHub workflow file” git push -u origin master #adds freshly created files for git to track

Let’s see whether your code works first. Using the popular curl program, manually run your code.

To inform GitHub to activate a Workflow file deploy.yml that you produced previously, use the command below to send a post request to your GitHub Repository https://github.com/username/repository/dispatches URL. Replace username and repository with your GitHub account and repository, respectively.

Replace $github personal token with your personal token in the code below.

# Makes a post request at https://github.com/username/repository/dispatches url curl-X POST https://github.com/username/repository/dispatches # Adds header for accepting content type -H ‘Accept: application/vnd.github.everest-preview+json’ # Adds header for authorization -H “Authorization: token $github_personal_token” # Adds json content on a body of post request so you can send multiple parameters # from this data section and you can perform various action based on arguments –data ‘{“event_type”: “deploy-service”, “client_payload”: {“environment”: “‘”$1″‘”, “ref”: “‘”$2″‘”}}’ #You can pass the name of environment & ref as a branch name so that you know which branch to deploy on which server

Using Hubot to build a Slack bot

That’s a solid start, because you were able to manually launch GitHub Action Workflow. Now let’s use Slack Bot to automate the identical manual tasks. You’ll build a Slack Bot that listens for your command and sends parameters to the GitHub Action.

To make a Slack Bot, you can either start from scratch or use a pre-built hubot package for slack workspaces. In this lesson, you’ll utilize Hubot, a pre-built Bot package. Hubot is an open-source automation application that works with chat platforms such as Slack, Discord, Gitter, TeamSpeak, and others.

It takes a long time to build a bespoke bot without utilizing an app like Hubot. Why? Because you’ll be in charge of the bot’s setup, webhook listening, and hosting. To streamline all of those steps, you’ll utilize the Hubot Slack app in this tutorial.

Using Npm to install Hubot

Let’s begin by downloading and installing Hubot on your local system, since you’ll be utilizing it to construct a Slack Bot. Hubot will operate as a connection between Slack and GitHub activity.

1. Navigate to your project directory (/Hubot) in your console (cd).

2. Use the npm install command to install the yo and generator-hubot packages globally (-g) on your local system. The yo package assists with project installation by producing projects in any language (Web, Java, Python, C#, etc.). The yo package is used by the generator-hubot package to install all dependencies and basic settings.

Because the yo command was deployed worldwide, you may use it from anywhere.

yo generator-hubot npm install -g

3. Run the following command to construct a simple Hubot boilerplate. A boilerplate is a piece of code that appears in several locations. You must always create code from scratch if you don’t have a boilerplate.

On your project directory, use the command below to construct a simple Hubot boilerplate. Hubot’s boilerplate connects to Slack (—adapter=slack) so that the Bot may listen to and reply to messages in the Slack channel. —adapter=slack yo hubot

Including Hubot in Your Slack Team

You must setup Hubot to interact with Slack now that it has been installed on your local PC.

Let’s get Hubot installed in your Slack workspace.

1. Open your web browser and go to https://workspacename.slack.com/admin/settings to access your Slack admin settings. Replace workspacename with the name of your Slack workspace.

To search for Hubot in the marketplace, go to the left panel and choose Configure applications, as shown below. Slack provides a marketplace where you can buy ready-made apps.

Getting to the Slack Admin Settings Getting to the Slack Admin Settings

2. Go to the search box and key in hubot to search the marketplace for Hubot, then pick Hubot.

To add Hubot to your Slack workspace, click the Add to Slack button, as shown below.

Hubot is found and added to Slack Workspace. Hubot is found and added to Slack Workspace.

3. Fill up some basic information for your Bot, such as its name (deployerhubot) and icon. Take note of the API Token since you’ll need it later in Hubot Deployer to activate the Bot from your previously built Hubot project.

Setting up Bot Data and Keeping Track of the API Token Setting up Bot Data and Keeping Track of the API Token

Integrating the GitHub Actions Workflow with Slack

Now that Hubot is installed in your Slack workspace, let’s put it to the test by listening to the channel and sending messages to it. However, you must first activate the Bot.

1. From your Hubot repo (./bin/hubot), run the command below within the project’s root directory to activate the Bot for Slack (—adapter slack). Make sure to use the API token you noted previously in lieu of $token.

./bin/hubot —adapter slack HUBOT SLACK TOKEN=$token

2. Run the below command to invite (/invite) the Bot (botusername) to your Slack channel. Replace botusername with the name of the Bot you registered in step three of the “Including Hubot in Your Slack Team” section.

To test whether the integration is functioning, mention a Bot with a text in Slack, such as @deployerhubot ping. You’re OK to go if the Bot answers with PONG, as demonstrated below.

Hubot with Slack Integration Testing Hubot with Slack Integration Testing

If the Bot does not answer, go to your GitHub repository and select the Actions tab in your web browser. The process that failed is identified by a circular red check badge. Click the failed process to learn what went wrong and how to correct it.

Working with Failed WorkflowsWorking with Failed Workflows

The failure is on performing remote ssh commands with password, as seen below. Return to step 3 after adjusting the process to check whether the Bot reacts with a PONG.

Visit correct a failed process, go to the GitHub source. Visit correct a failed process, go to the GitHub source.

Using Slack to start a GitHub Actions Workflow

It’s time to start using GitHub Actions from Slack now that you’ve enabled your Slack Bot!

You’ll need flexibility to deploy a given branch to a particular server, as well as to fetch the code from a given branch. When someone says ***@*bot deploy API feature-x to production in a Slack channel, you’ll educate the Bot to reply automatically. You may verify the environment name so that only specified environments and branches can be deployed afterwards.

To make the Bot’s answers more automated:

1. Make a folder called /Hubot/scripts. You’ll store a script that initiates your GitHub process in the /Hubot/scripts directory.

2. Create a file titled bot.js in the /Hubot/scripts directory using your code editor. Now copy and paste the code below into the bot.js file.

The code below enables the Bot to listen to Slack Channel conversation messages and then starts the process to deliver a response to Slack Channel.

const validServices = [‘api’,’app’]; const validEnvironments = [‘production’]; robot.hear (`@${process.env.BOT_ID}`,async (bot) => { // Bot is only interested in listening message // like @deploy api featurex to production // Setting up reusable variable const payload = bot.message.text.split(” “) const service = payload[2]; const branch = payload[3]; const environment = payload[5]; const username = bot.message.user.name; //Inform user that we processing bot.send(`Roger that! Please wait.`); // Validate if the command that has been used is valid or not // because user can use invalid commands too if(!validateCommand(bot,username,service,branch,environment)) { return; } // If command seems valid, then trigger a workflow await triggerWorkflow(bot,username,service,environment,branch) // Inform user that workflow has been triggered successfully bot.send(`Github Action has been triggered successfully`); }) const validateCommand = (bot,username,service,branch,environment) => { // Limit the services as users can use services that are not listed // which will try to trigger workflow and gets error if(!validServices.includes(service)) { bot.send(`${service} is not availble, Only ${validServices.join(‘, ‘)} are available`); return false; } // Limit the environment as users can use invalid list of environment too if(!validEnvironments.includes(environment)) { bot.send(`${environment} is not availble. Only ${validEnvironments.join(‘, ‘)} are available`); return false; } return true; } const triggerWorkflow = (bot,username,service,environment,branch) => { try { // This is the same manual workflow triggering code converted // from curl to actual javascript post request const data = await axios.post(`https://api.github.com/repos/yourusername/yourreponame/dispatches`,{ ‘event_type’: ‘deploy-service’, ‘client_payload’: {‘environment’: environment, ‘ref’: branch} },{headers:{ Authorization: `token ${token}`, }}) } catch(e) { bot.send(`Sorry @${username} could not trigger github action. Please check my logs ${e.message}`); } }

3. Finally, submit the deploy api staging to dev message to @botusername in Slack, and you should get a similar answer, as seen below.

GitHub Events such as pushing code to a certain branch, generating tags, submitting pull requests, accessing URLs, and others may trigger workflow files.

send the deploy api staging to dev message to @botusername in Slack. send the deploy api staging to dev message to @botusername in Slack.

Conclusion

From manually initiating Slack answers with codes to developing a chatbot, you’ve learnt about GitHub Workflow in this lesson. You’ve also discovered that using a Slack chatbot to automate chores by using the GitHub actions process. Slack chatbots are designed to automate tasks and provide predefined responses within the Slack platform, while in-app chat solutions, such as GetStream, enable real-time messaging capabilities directly within an application, promoting seamless communication and collaboration among users. There are also bunch of alternatives to getstream such as Sendbird, Sceyt and others

Will you expand on your acquired knowledge by adding a Reminder Bot or creating interactive messages?

The “github slack only pull requests” is a Slack bot that can be used to invoke GitHub actions. The bot will only trigger the pull request for a user if they are in the #slack-bot channel.

Related Tags

  • slackbot
  • voxmedia/github action-slack-notify-build v1
  • github slack real time alerts
  • github slack unsubscribe
  • github slack notifications mentions

Table of Content