背景介绍
在自动化测试中的Slack机器人-基础篇一文中,我们介绍了如何在Slack上注册一个聊天机器人,并且让它负责Jenkins的运维工作。接下来,我们来详细介绍如何打造自己的自动化机器人。
开发准备
API简介
Slack提供了多种语言的API客户端,方便用户使用API来与Slack进行交互。具体请参考Slack Bot API页面介绍。
这里,我们使用第三方的Slack API的封装库Botkit, Botkit实现了对API级别更高级的封装,屏蔽了底层的交互细节,使大家更专注于业务逻辑实现。非常方便,简单易使用。
安装botkit库
由于botkit是nodejs开发的,所以我们首先需要准备nodejs环境。
npm install --save botkit
原型开发
使我们的Bot处于在线状态
将token中填入自己创建的Bot的API Token序列串。
var Botkit = require('botkit');
var controller = Botkit.slackbot();
var bot = controller.spawn({
token: your_slack_bot_token
})
bot.startRTM(function(err,bot,payload) {
if (err) {
throw new Error('Could not connect to Slack');
}
});
开始处于处于离线状态的autobot.
将上面的代码保存为bot.js, 然后执行
node bot.js
就可以在Slack中看到我们开发的autobot机器人处于在线状态了,如下图所示;不过由于代码中,我们没做业务逻辑处理,所以我们的机器人还不会做任何事情。
使用一些基本的Bot命令
这里,我们使用botkit提供的bot.hears()命令,来监听聊天中的关键字信息,并进行回复。
基于如下模板编写代码
controller.hears(["keyword","^pattern$"],["direct_message","direct_mention","mention","ambient"],function(bot,message) {
// do something to respond to message
// all of the fields available in a normal Slack message object are available
// https://api.slack.com/events/message
bot.reply(message,'You used a keyword!');
});
我们监听消息open the (.*) doors
, 然后回复该消息,如果是pod bay
则回复Sorry
信息,否则回复Okay
.
controller.hears('open the (.*) doors', ['message_received'],function(bot,message)
{
var doorType = message.match[1]; //match[1] is the (.*) group. match[0] is the entire group (open the (.*) doors).
if (doorType === 'pod bay')
{
return bot.reply(message, 'I\'m sorry, Dave. I\'m afraid I can\'t do that.');
}
return bot.reply(message, 'Okay');
});
Botkit的其他API介绍和使用样例,点击这里查看,我们在本章中就不过多介绍了。下面我们重点介绍如何使Bot机器人与我们的jenkins系统进行交互。
当前,我们的jenkins地址为 http://localhost:8080
添加自定义jenkins build 相关命令
controller.hears(['jenkins build job (.*)'], 'direct_message,direct_mention,mention', function(bot, message) {
var matches = message.text.match(/build job (.*)/i);
var job_name = matches[1];
console.log(job_name)
var job_url = encodeURI('http://localhost:8080/job/'+job_name+'/build')
request.post({url: job_url}, function (error, response, body) {
if (!error && response.statusCode == 201) {
console.log(body)
var str = 'I have notify jenkins server to run this command. ^_^'
bot.reply(message, str)
} else {
bot.reply(message, 'error, maybe the job *'+job_name+'* not found. I am sorry for that. >_<!!')
}
})
})
我们主要是用到了nodejs的request库来调用Jenkins 提供的RESTful API实现与Jenkins交互的。如果提示错误信息,请确保jenkins的访问策略配置,我们的用例是没有带Jenkins API Token访问的。
添加自定义jenkins robot 相关命令
例如,获取robot framework项目的执行结果情况。
功能代码实现如下:
controller.hears(['jenkins get job-robot-result (.*)'], 'direct_message,direct_mention,mention', function(bot, message) {
var matches = message.text.match(/get job-robot-result (.*)/i);
var job_name = matches[1];
console.log(job_name)
var job_url = encodeURI('http://localhost:8080/job/'+job_name+'/lastBuild/robot/api/json?pretty=true')
request({url: job_url}, function (error, response, body) {
// console.log(response)
if (!error && response.statusCode == 200) {
var json = JSON.parse(body)
var critical_failed = json['criticalFailed']
var critical_total = json['criticalTotal']
var pass_percentage = json['passPercentage']
var reply_with_attachments = {
"attachments": [
{
"fallback": "Required plain-text summary of the attachment.",
"color": "#36a64f",
"pretext": "result from jenkins server.",
"title": "The last build robot result of " + job_name,
"title_link": job_url,
},
{
"fields": [
{
"title": "Failed Cases",
"value": critical_failed,
"short": true
},
{
"title": "Total Cases",
"value": critical_total,
"short": true
},
{
"title": "Pass Percentage",
"value": pass_percentage + '%',
"short": true
}
]
}
]
}
console.log(JSON.stringify(reply_with_attachments))
bot.reply(message, reply_with_attachments)
}
else {
bot.reply(message, 'something error, maybe the job name is not correct. please make sure.')
}
})
})
还可以添加其他一些命令,这里就不再介绍了。
总结
好了,至此,我们也介绍完了如何打造自己的Slack聊天运维机器人了,至于如何使自己的机器人更智能,还需要自己慢慢完善,我这里仅仅是给出一个样例,方便大家入门。