Hubot是Github开发并开源的chatbot,将其部署到运维环境中后,可通过编写自定义的脚本,将之前的web端、shell命令等人工进行的运维工作,通过聊天工具交给机器人来代替。

搭建hubot本地开发环境

安装Node.js:

下载Node.js LTS的Binary版本:https://nodejs.org/en/download/current/。将binary压缩包解压缩到安装目录NODE_INSTALL_PATH中。 设置环境变量NODE_HOME指向到解压缩后的目录,并设置PATH环境变量包含NODE_HOME

NODE_INSTALL_PATH中创建一个npm_cache目录,使用下面的命令将npm_cache的路径变更到这个目录中:

1npm config set cache NODE_INSTALL_PATH/npm_cache --global
1node -v
2v10.14.1
3
4npm -v
56.4.1

使用npm安装hubot generator生成我们自己本地的hubot:

1npm install -g yo generator-hubot
1mkdir myhubot
2cd myhubot
3yo hubot

接下来会是交互的初始化hubot,这里略过。

Hubot需要使用redis来持久化数据,这里是本地开发环境,编辑external-scripts.json删除hubot-redis-brain,在本地不使用redis。

删除external-scripts.json中的hubot-heroku-keepalive

执行bin/hubot进入:

1bin/hubot
2wing> help
3usage:
4history
5exit, \q - close shell and exit
6help, \? - print this usage
7clear, \c - clear the terminal screenhu

编写第一个hubot脚本

hubot使用CoffeScript开发自定义机器人脚本,先查看一下本地myhubot的目录结构:

1bin/                    #hubot运行脚本
2node_modules/           #引用的包文件
3scripts/                #自定义机器人脚本
4external-scripts.json   #引用的外部脚本
5package.json            #项目全局配置信息
1module.exports = (robot) ->
2
3  robot.hear /hello/i, (res) ->
4    res.send "hello everyone."
5
6  robot.respond /hi/i, (res) ->
7    res.reply "hi everyone."

hear和respond的区别,hear监听任何消息,respond只监听群组中发送给机器人的消息,即需要指定机器人名称,参见下面的触发脚本的方式。 send和reply的区别,send会将消息发送到群组中,而reply会将消息回复给具体的人,如@

1wing> hello
2wing> hello everyone.
3
4wing> wing hi
5wing> hi everyone.

参考