Create your own Hubot (3) - Create scripts for your Hubot

Jun 15, 2017 Hubot 中文版

In the previous post, I’ve demonstrated how to install and create a new Hubot. To make it more powerful, we have to create scripts (.coffee or .js file) for our Hubots. I will show you how to do it and integrate it with Slack in this article.



Prerequisite

Makre sure you have Node.js and npm installed on your machine:

# Check Node.js version
nodejs -v

# Check npm version
npm -v


Create scripts

Why we need scripts for Hubot? You can consider scripts as plugins. Without customized plugins, your Hubot only provides very basic features (commands). Thus, we need to create more plugins to power it. Then, how to install customized plugins? All you need to do is to put scripts into a folder name scripts. And don’t worry, Yo already created it for us. Now, let’s create a simple script:

# This example is written in Coffescript

module.exports = (robot) ->

  # Usage: show_info
  robot.respond /show_info/i, (msg) ->

    # Do anything you want in here ...

    # For example: send a multi-line message back
    msg.reply """Put your information here
    and here ....
    and here ....
    """

In this example, I used robot.respond to define a command (trigger). So, when you type and execute show_info on Slack, Hubot will react to it by sending messages back. Besides respond, you can use hear. But there is a little difference between them (check documentation). Here comes a more interesting example:

# Call a HTTP API

  ...

  # Usage: call-http [param1] [param2]
  robot.respond /call-http (.*) (.*)/i, (msg) ->

    # Get parameters
    data = JSON.stringify({
      param1: msg.match[1]
      param2: msg.match[2]
    })

    # Send POST Request, and return response
    msg.http('/url/to/your/service')
      .header('Content-Type', 'application/json')
      .post(data) (err, res, body) ->
        if res
          if res.statusCode isnt 200
            msg.reply "Something goes wrong ..."
            return
          msg.reply "Return your data or messages"
        else
          msg.reply "Something goes wrong ..."


Integrate Slack with your Hubot

To integrate Hubot with Slack, it needs one more step. Now, Slack has not known the existence of our Hubots. Therefore, we have to register our Hubots and get API tokens. Run Slack and click Apps & Integrations, and then chose Bot. After registration, you will get an API token.

Run Hubot

Let’s run Hubot up with the API token:

# Don't forget to add the token
HUBOT_SLACK_TOKEN=your-api-token ./bin/hubot --adapter slack

A better way is to set the token as an environment variable. Now, you can type and test your commands in a Slack channel with your bot.


You might also like:




If you have any suggestions, questions or even find some typos, feel free to contact me. Thank you! :)

zeckli.devforgalaxy@gmail.com   © 2015-2019 zeckli, thanks to Jekyll and GitHub.