用 slack 和 hubot 搭建运维机器人【ubuntu】

1、安装nodejs包管理工具npm

apt-get  install npm     ------ubuntu 中刚安装的npm版本比较低,需要进行升级  
npm -g install npm@3.10.7 //升级到指定版本

npm -g install npm //升级到最新版本

2、安装nodejs

npm install -g n
n stable  //安装nodejs的最新稳定版本,也可以安装指定版本: n v6.6.0

3、安装hubot

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

4、创建配置hubot目录

mkdir /root/hubot
cd /root/hubot
yo hubot
如果使用root用户安装,则需要对以下目录进行授权
chmod g+rwx /root /root/.config /root/.config/configstore
chown -R chown ubuntu /root/.config/configstore
chmod g+rwx /root/hubot chmod -R g+rwx /root/.npm

yo hubot // 如果是root用户安装,这步之前需要调整文件和目录权限.这步安装时若报错,可以尝试多次安装的操作。

安装hubot,默认会带上heroku和redis,如果用不到可以卸载掉:
npm uninstall hubot-heroku-keepalive --save
hubot目录下的external-scripts.json文件中把有关herokuredis的两行删掉就行了,否则老是会报几个警告。
然后,再把hubot-scripts.json删掉,目前我们暂时还用不到它:rm -f hubot-scripts.json

 5、启动hubot服务

现在可以正式启动hubot了: ./bin/hubot
试着执行几个测试命令:
hmbot> help
usage:
history 
exit, q - close shell and exit
help, ? - print this usage
clear, c - clear the terminal screen
hmbot> ping

6、连接hubot和slack

1、首先需要在slack 上安装好hubot的插件,它会自动生成一个token,把这个token记录下来,输入:
env HUBOT_SLACK_TOKEN=xoxb-你的token ./bin/hubot --adapter slack

注释:这时候hubot就启动起来,等待接收命令了。但是由于hubot缺省加入的是slack#general频道,如果你改掉了频道名字,或者删掉了这个频道的话,你需要重新邀请小机器人进入一个新的频道,否则没法对话。

2、现在可以在slack客户端,通过下面的命令和hubot进行对话:
hubot help

 7、让hubot保持在线

但是如果这时候我们关掉ssh的话,小机器人就掉线了,怎么办呢?可以用nohup的方法让它留在后台,也可以用tmux:
yum install tmux
tmux new -s hubot
在tmux里执行上面的命令,然后按ctrl+b,然后再按d退出。如果再想进去,可以执行:
tmux a
-t hubot

8、让hubot执行shell脚本

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

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

修改一下external-scripts.json,添加上以下模块:hubot-script-shellcmd。如果到此为止,你操作的步骤和我基本一样的话,你的external-scripts.json应该长的像这个样子:

[
  "hubot-diagnostics",
  "hubot-help",
  "hubot-google-images",
  "hubot-google-translate",
  "hubot-pugme",
  "hubot-maps",
  "hubot-rules",
  "hubot-shipit",
  "hubot-script-shellcmd"
]

测试shell脚本:

配置完毕上面的东东,这里需要重启下hubot服务:
nohup ./bin/hubot --adapter slack & #执行启动脚本时,千万不要进入bin目录,要在bin目录的外面执行启动脚本,否则启动失败。
然后在slack客户端通过如下命令,对hubot说话: @hmbot run ping #//hmbot 为hubot的申请名称,run 可以通过HUBOT_SHELLCMD_KEYWORD配置。

 附录hubot脚本:

#!/bin/sh

set -e

npm install
export PATH="node_modules/.bin:node_modules/hubot/node_modules/.bin:$PATH"
export HUBOT_SLACK_TOKEN="token"        #slack上面申请的token
export HUBOT_SHELLCMD_KEYWORD="run"     #修改命令虎符

exec node_modules/.bin/hubot --name "hmbot" "$@"

  

原文地址:https://www.cnblogs.com/husbandmen/p/7795317.html