slack 是现在非常流行的团队协作看板工具,支持多频道,多平台独立的沟通,而且有非常强大的接口,连接其他平台的应用,比如github,trello等。Hubot是一个开源的CoffScript机器人,它可以通过一写聊天工具实现对机器的远程命令操作。正如该项目在Github上骄傲的说:它帮助极大的帮助员工提升效率。而我感兴趣正是如此,边聊天边指挥机器人远程操作服务器这样的场景。今天来尝试部署一下。

Hubot

安装npm

hubot是node开发,需要先配置node.js环境。我使用的系统环境在centos6.5。参考node.js官网

运行下面操作,可以先装上node的集合套件命令npm

如果选择 Node.js v4:

1
curl --silent --location https://rpm.nodesource.com/setup_4.x | bash -

如果选择 Node.js v6(我选择最高版本安装):

1
curl --silent --location https://rpm.nodesource.com/setup_6.x | bash -

如果选择Node.js 0.10:

1
curl --silent --location https://rpm.nodesource.com/setup | bash -

然后运行, as root:

1
yum -y install nodejs

注:以上安装方式适用用centos6.5以上版本,以下版本不支持

安装hubot

1
npm install -g hubot coffee-script yo generator-hubot

创建一个hubot的运行目录,并配置相关组的写权限

1
2
3
4
mkdir /hubot
chmod g+rwx /root
chmod g+rwx /hubot
chmod -R g+rwx /root/.npm

在工作目录部署hubot

1
yo hubot

安装过程中会问你安装什么样的adapter,手工输入slack
缺省安装的hubot,会带上herokuredis,如果用不到的话,比如我就手工输入slack

hubot目录下的external-scripts.json文件中把有关herokuredis的两行删掉就行了,否则老是会报几个警告。并且移除hubot-scripts.json,否则会报错

1
mv hubot-scripts.json hubot-scripts.json.bak

好了,现在总算可以了。用一下看看吧:

1
./bin/hubot

连接slack和hubot

前提是你要注册有slack,这里我们进入“Apps & Integrations”,搜索“hubot”,然后add,并配置相关信息,会得到一个“API TAKEN”

1
HUBOT_SLACK_TOKEN=you taken ./bin/hubot --adapter slack

这个命令会连接你的bot到slack,你可以在slack上和hubot进行对话了、尝试下slack的#general频道(hubot默认的使用,add它进来即可)与hubot使用些基本命令交互下看看,比如help。

1
rob_ding help #(你在slack设置的robot名字) help

在slack指挥hubot操作脚本

我们需要小机器人来执行一些shell脚本,所以我们需要安装:

1
2
npm install hubot-script-shellcmd
cp -R node_modules/hubot-script-shellcmd/bash ./

增加一个hubot-script-shellcmd模块到external-scripts.json:

1
2
3
4
5
6
7
8
9
10
11
12
[
"hubot-catme",
"hubot-diagnostics",
"hubot-help",
"hubot-google-images",
"hubot-google-translate",
"hubot-pugme",
"hubot-maps",
"hubot-rules",
"hubot-script-shellcmd", #增加此模块,注意逗号
"hubot-shipit"
]

这里面的helloworld就是个例子,我稍微改一下:

1
cp helloworld 这里谁最美

好了,现在你重启一下小机器人,在你的slack端对机器人说:

1
rob_ding shellcmd 这里谁最美

看看效果吧!

原理就是如此,需要执行什么脚本,就看自己需求了。

让hubot始终运行

hubot需要独立运行才能和slack保持通信,这里我们使用screen命令,即使退出了ssh终端,它也可以独立运行不中断

1
2
3
4
5
6
7
screen -dmS hubot #创建一个运行的独立窗口,命名为hubot
screen -list #查看创建的独立窗口列表
screen -r hubot #进入hubot的窗口
#运行hubot进程
HUBOT_SLACK_TOKEN=you taken ./bin/hubot --adapter slack
快捷键ctrl+a+d,退出当前的hubot窗口,回到原来窗口