Automate Your Development Activities with Hubot

Hubot is an automation tool that can sync with other chat services. It was first developed as an internal project at Github and is developed in CoffeeScript on Node.js which lets you take advantage of a large number of packages available for the Node.js.

Functionality extension and Deployment are a breeze in Hubot. Deployment on Heroku is as easy as setting a few environment variables and functionality extension can be done by just placing the code in the right folder.

Why Hubot?

Why would you choose Hubot over all the other automation tools out there?

  • In active development and updated regularly by Github.
  • Incredibly simple to add functionality.
  • Written over Node.js which means you get to take advantage of all the Node libraries out there.
  • Uses CoffeeScript.
  • Has inbuilt support for HTTP listner and HTTP requests which makes interacting with third party APIs really easy.
  • Large number of useful scripts already available.
  • Incredibly easy to deploy on Heroku.
  • Extending Hubot to support other chat servers is trivial.
  • Support for popular chat servers including Hall, IRC, HipChat.
  • Large number of pre built scripts available at the Hubot scripts catalogl

What you can do?

  • Get constant updates from Github/Gitlab about your code.
  • Monitor status of your applications without leaving the chat room.
  • Use the bot to record daily activities and extract meaningful statistics from chatroom interactions.
  • Use it as an announcement tool to relay a message to all the rooms.
  • Use it as a live scratchpad/dashboard for assigning tasks and deadlines on the go.

Interesting Plugins

A few of the interesting plugins that can be found in the hubot script catalog.

  • ambush – Send a message to someone as soon as they enter the room.
  • aws – Queries for the status of AWS services
  • bang-bang – Repeat the last command directed at hubot
  • basecamp – Interactions with basecamp
  • gemwhois – Get information on a gem if it exists.
  • github-commits – An HTTP Listener for notifications on github pushes
  • gitlab – GitLab integration.
  • heroku-status – Show current Heroku status and issues
  • newrelic – Display current app performance stats from New Relic
  • redmine – Display current app performance stats from New Relic
  • rubygems – Find a rubygem from rubygems.org
  • travis – Find the build status of an open-source project on Travis
  • update – Allows hubot to update itself using git pull and npm update.

Who is using Hubot?

Other chat service integrations

Installation

Hubot is written in coffeescript on Node.js and requires the installation of Node and CoffeeScript on a linux machine.

The best way to install Node and npm would be to install them from source from the official website after which CoffeeScript and Hubot can be installed using the following command.

$ npm install -g hubot coffee-script

The -g flag is optional and signifies that Hubot will be installed globally. You can skip it to install it locally.

After the installation, the hubot command is now available which is used to create a bot.

creates a new bot called as newbot in a directory with the same name. Now would probably be a good time to start using Git for version control. By using Git, you will be able to deploy the bot to Heroku with minimum configuration.

Usage

The Hubot executable is located in the “bin” folder and the bot can be started with bin/hubot command. This starts the Hubot with the “shell adapter”. This is mainly used for development. The default user name is “Shell”.

The default name “hubot” for the bot can be changed by supplying the --name option to the bin/hubot command.

$ bin/hubot --name namedbot

The bot will now respond to namedbot rather than hubot.

Hubot comes with a few scripts installed by default of which help is the most useful. It lists all the commands available and a short description of the command.

Development

Extending the functionality for Hubot is as simple as placing the code in the “scripts” folder. Every script will have to have the following code

module.exports = (robot) ->

Hubot uses regular expression to match any commands directed at it. This is done by the robot.hear and robot.respond functions both of which take a regular expression and a callback function as arguments.

robot.hear matches any text that is entered in the chat room while robot.respond only matches text that is addressed directly to the bot.

You can make Hubot respond to commands by using the msg parameter. The msg.send, msg.reply and msg.emote functions are used for this.
msg.reply addresses the robot’s message to a particular user whereas msg.send sends it to the room directly without addressing anyone.

While the above methods are fine for responding to static messages, the real power of the bot comes from the regular expressions.

You can use regular expressions by defining capture groups in your robot.hear and robot.respond sections. These are enclosed in brackets and the matched text can be accessed through the msg.match array.

In addition to the above features, Hubot provides simple HTTP functionality through the robot.http method which can be used to make HTTP calls. This opens up huge possibilities for interacting and integrating third party services.

Hubot also has a HTTP listener which can listen and respond to requests. This makes it really easy to trigger hubot actions from external sources.

Action How to
Create a script module.exports = (robot) ->
listen to all chats robot.hear /<regular expression here>/
listen to chats addressed to the bot robot.respond /<regular expression here>/
Matches from regular expression msg.match[<match number>]
Send message in room msg.send "<message here>"
Send message to specific person msg.respond "<message here>"
Make HTTP call robot.http('<url here>').get() (err, res, body) ->
Send random message from a list msg.send msg.random ['hello', 'hi', 'how do you do']
Detect when user enters or leaves room robot.enter (msg) ->, robo.leave (msg) ->
Access environment variables process.env.ENVIRONMENT_VARIABLE
HTTP Listener robot.router.post '/hubot/chatsecrets/:room', (req, res) ->
Emit and listen to events robot.emit '<event>', robot.on '<event>'
Persistence interface robot.brain

Persistence

Hubot uses the Redis NoSQL database to provide persistence. robot.brain variable is used as the interface for the persistence. You can store arbitrary values in the robot.brain variable and they will be available even after restarting the bot.

robot.brain.answer_to_life_the_universe_and_everything = 42

You can make sure that the brain has initialized and the database connection has been established by adding

robot.brain.on 'loaded', ->

before the execution of your code. This makes sure that all the data stored in the brain is loaded before Hubot starts executing code.

Configuration

Configuration for custom scripts is easy since Hubot makes use of environment variables. This way, you don’t have to hardcode any of your configuration values into the system.

The environment variables are accessible through the process.env.<var_name> variable. For example to define a custom environment variable in the local development environment, you would do

To set the same environment variable on a bot that has been deployed to Heroku, you would do

$ heroku config:add NEW_ENV_VAR=42

The variable is now accesed by the bot by using

within the script.

Sample script for displaying search results from Railscasts

Here is a sample script with explanation that will get you the details of the first 5 episodes for a search term on RailsCasts.

Install Cheerio using npm install cheerio and add it to your package.json file.

# Include required libraries
# Cheerio is used to parse the html and extract data
cheerio = require('cheerio')

RAILSCASTS_BASE_URL = "http://railscasts.com/"

# Indicate that you are defining a script
module.exports = (robot) ->
  # Define your regular expressions to match
  robot.respond /link me (.*)/i, (msg) ->
    # Get the query and form the search url
    query = msg.match[1]
    URL = "http://railscasts.com/episodes?search=#{query}"

    # Make a http call to railscasts
    robot.http(URL).get() (err, res, body) ->
      # Parse and reply with episodes found
      $ = cheerio.load(body)
      # Only first 5 episodes to be returned
      $('.episode').slice(0, 5).each ->
        msg.send "Title: " + $(this).find('h2 a').first().text().replace /^s+|s+$/g, ""
        msg.send $(this).find('.info .number').text()
        msg.send "Link: " + RAILSCASTS_BASE_URL + $(this).find('h2 a').first().attr('href')
        # Delimiter for episodes
        msg.send Array(4).join '~'

With the above script, you can now enter hubot link me bootstrap in the chat and it will reply with the details of the first 5 episodes that are found on railscasts.

Screenshot

!Hubot and Railscast

Deployment on Heroku

You can deploy your bot on Heroku so that you can use the bot outside of your local machine. You will need to install the “heroku toolbelt” program so that you can interact with Heroku from the command line. You can use the following command on ubuntu to install it.

$ wget -qO- https://toolbelt.heroku.com/install-ubuntu.sh | sh

Authenticate with your login credentials using heroku login command(You will need an account on Heroku for this.)

You should also have a Git repository initialized to be able to deploy to Heroku. After making sure that you have a Git repository intialized, you need to create a Heroku app.

This will create an app on Heroku with specific url where you can deploy your bot.

If you are planning to integrate the app with a chat service like Hall/Campfire/IRC, you will have to set service specific config variables before deploying. An example of this can be found in the next section.

After setting the config variables, you can deploy the app by pushing your code to the Heroku remote.

Integration with Chat Services

Hubot facilitates integration with chat services through “adapters”. Adapters are interfaces to services that you want the bot to run on. All adapters are extended from the “adapter.coffee” file which provides the basic interface on the robot object.

Integration with the Hall chat service is done as follows.

Add hubot-hall dependency to package.json file.

"dependencies": {
  "hubot-hall": "latest",
  ...
}

You need to set the configuration options before deploying. Hubot on Hall needs the following config variables set

$ heroku config:add HEROKU_URL=<url_of_your_app_here>
$ heroku config:add HUBOT_HALL_EMAIL=<email_of_the_bot_registered_on_hall.com>
$ heroku config:add HUBOT_HALL_PASSWORD=<password_for_the_above_account>

You need to register on hall.com with a new account and use the credentials for the bot.

Actual deployment

$ git push heroku master
$ heroku ps:scale web=1

At this point, you should be able to see the bot join all the rooms to which it has been invited and start responding to commands.

References

Share the Love

Published in automation | Tagged with hubot, coffeescript, heroku, nodejs, redis, javascript


Friday Hug is a weekly round up of best articles, tutorials, analysis across the Web, hand curated by our Tech Team.

-->




Source link

مدونة تقنية تركز على نصائح التدوين ، وتحسين محركات البحث ، ووسائل التواصل الاجتماعي ، وأدوات الهاتف المحمول ، ونصائح الكمبيوتر ، وأدلة إرشادية ونصائح عامة ونصائح