Open Source ChatOps Bots:
1. Hubot : Written in CoffeeScipt
2. Lita : Written in Ruby
3. Errbot : Written in Python
So, What is ChatOps? And How do I Get Started?
12+ Frameworks to Build ChatOps Bots
Hubot is open source developed by Github Chatbot, written in CoffeeScript based on Node.js.
Hubot https://hubot.github.com/
Hubot Scripts https://github.com/hubot-scripts
Hubot Control https://github.com/spajus/hubot-control
You can use Hubot to develop Chatbot to automate what you want All automated tasks, such as:
-Operation and maintenance automation (compiling and deploying code, restarting machines, monitoring server operation, automatically fixing bugs, etc.)
-External service interaction (managing Redmine, integrating Jenkins, monitoring Zabbix, etc.) -Getting
weather forecasts regularly
-random ordering
-chatbots, etc. .
There are detailed usage instructions in the official documentation, https://hubot.github.com/docs/ , here is just a summary.
Hubot Scripts has a large number of ready-made scripts that can be used, and it is also the best sample for writing scripts by yourself.
(1) The following software support is required to install
and run Hubot:
- Node.js
- Redis stores data by default
- CoffeeScript
- Yeoman
- generator-hubot Generate Hubot skeleton project
quote
C:\Users\rensanning>node -v
v0.12.8
C:\Users\rensanning>npm -v
2.14.9
C:\Users\rensanning>npm install -g yo generator-hubot
C:\Users\rensanning>npm list -g generator-hubot yo
v0.12.8
C:\Users\rensanning>npm -v
2.14.9
C:\Users\rensanning>npm install -g yo generator-hubot
C:\Users\rensanning>npm list -g generator-hubot yo
(2) Create your own bot
quote
C:\Users\rensanning>cd d:/
D:\>mkdir hubotsample
D:\>cd hubotsample
D:\hubotsample>yo hubot
? Owner RenSanNing <[email protected]>
? Bot name okbot
? Description A sample hubot
? Bot adapter campfire
D:\>mkdir hubotsample
D:\>cd hubotsample
D:\hubotsample>yo hubot
? Owner RenSanNing <[email protected]>
? Bot name okbot
? Description A sample hubot
? Bot adapter campfire
The adapters for campfire and shell are provided by default. Others need to download hubot-<AdapterName> through npm.
It can also be generated directly through parameters:
quote
yo hubot [email protected] --name=foobot --description="Foo Bot" --adapter=shell
Project structure:
- bin/ runs the script
- The package file for the node_modules application
- scripts store custom scripts
- external-scripts.json App's external scripts
- hubot-scripts.json *** This file is useless and can be deleted
- package.json project global configuration information
(3) Running the bot
quote
D:\hubotsample>bin\hubot -v
2.19.0
D:\hubotsample>bin\hubot -h
Usage hubot [options]
Available options:
-a, --adapter ADAPTER The Adapter to use
-c, --create PATH Create a deployable hubot
-d, --disable-httpd Disable the HTTP server
-h, --help Display the help information
-l, --alias ALIAS Enable replacing the robot's name with alias
-n, --name NAME The name of the robot in chat
-r, --require PATH Alternative scripts path
-t, --config-check Test hubot's config to make sure it won't fail at startup
-v, --version Displays the version of hubot installed
2.19.0
D:\hubotsample>bin\hubot -h
Usage hubot [options]
Available options:
-a, --adapter ADAPTER The Adapter to use
-c, --create PATH Create a deployable hubot
-d, --disable-httpd Disable the HTTP server
-h, --help Display the help information
-l, --alias ALIAS Enable replacing the robot's name with alias
-n, --name NAME The name of the robot in chat
-r, --require PATH Alternative scripts path
-t, --config-check Test hubot's config to make sure it won't fail at startup
-v, --version Displays the version of hubot installed
-a specifies Adapter (default is shell)
-d disables HTTP service (default is enabled)
-c deprecated uses yeoman
to use default shell adapter
quote
D: \ hubotsample> bin \ hubot
Designated adapter
quote
D: \ hubotsample> bin \ hubot -a shell
quote
okbot> help
usage:
history
exit, \q - close shell and exit
help, \? - print this usage
clear, \c - clear the terminal screen
usage:
history
exit, \q - close shell and exit
help, \? - print this usage
clear, \c - clear the terminal screen
quote
okbot> okbot help
okbot> Shell: okbot adapter - Reply with the adapter
okbot animate me <query> - The same thing as `image me`, except adds a few parameters to try to return an animated GIF instead.
okbot echo <text> - Reply back with <text>
okbot help - Displays all of the help commands that Hubot knows about.
okbot help <query> - Displays all help commands that match <query>.
okbot image me <query> - The Original. Queries Google Images for <query> and returns a random top result.
okbot map me <query> - Returns a map view of the area returned by `query`.
okbot mustache me <url|query> - Adds a mustache to the specified URL or query result.
okbot ping - Reply with pong
okbot pug bomb N - get N pugs
okbot pug me - Receive a pug
okbot the rules - Make sure hubot still knows the rules.
okbot time - Reply with current time
okbot translate me <phrase> - Searches for a translation for the <phrase> and then prints that bad boy out.
okbot translate me from <source> into <target> <phrase> - Translates <phrase> from <source> into <target>. Both <source> and <target> are optional
ship it - Display a motivation squirrel
okbot ping
okbot> PONG
okbot echo 你好!
okbot> 你好!
okbot time
okbot> Server time is: Fri Sep 30 2016 11:05:24 GMT+0800 (中国 (标准时间))
okbot> Shell: okbot adapter - Reply with the adapter
okbot animate me <query> - The same thing as `image me`, except adds a few parameters to try to return an animated GIF instead.
okbot echo <text> - Reply back with <text>
okbot help - Displays all of the help commands that Hubot knows about.
okbot help <query> - Displays all help commands that match <query>.
okbot image me <query> - The Original. Queries Google Images for <query> and returns a random top result.
okbot map me <query> - Returns a map view of the area returned by `query`.
okbot mustache me <url|query> - Adds a mustache to the specified URL or query result.
okbot ping - Reply with pong
okbot pug bomb N - get N pugs
okbot pug me - Receive a pug
okbot the rules - Make sure hubot still knows the rules.
okbot time - Reply with current time
okbot translate me <phrase> - Searches for a translation for the <phrase> and then prints that bad boy out.
okbot translate me from <source> into <target> <phrase> - Translates <phrase> from <source> into <target>. Both <source> and <target> are optional
ship it - Display a motivation squirrel
okbot ping
okbot> PONG
okbot echo 你好!
okbot> 你好!
okbot time
okbot> Server time is: Fri Sep 30 2016 11:05:24 GMT+0800 (中国 (标准时间))
***All input will be recorded in .hubot_history file.
(4) Writing
custom scripts written in scripts should be placed in scripts, which can be .coffee or .js files.
scripts/hello.coffee
# Description: # This is a test. # # Commands: # okbot helo - Reply with world! module.exports = (robot) -> robot.respond /hello/i, (msg) -> msg.send "world!"
quote
okbot hello
okbot> world!
okbot> world!
Because Hubot needs to parse the script file and provide help, the comments at the beginning of the script file are standardized, and the
first line must be the comment "# Description:" (others can be omitted), otherwise there will be a warning:
quote
hello.coffee is using deprecated documentation syntax
Hubot also supports js, such as:
scripts/hello2.js
// Description: // This is a test2. // Commands: // okbot helo - Reply with world! module.exports = function(robot) { robot.respond(/hi/i, function(msg){ msg.send("world2!"); }); }
quote
okbot hi
okbot> world2!
okbot> world2!
Respond vs Hear
- respond only listens for messages sent directly to the robot, you need to specify the robot name
- hear can listen to any message
quote
MYHUBOT xxx
myhubot xxx
@myhubot xxx
myhubot: xxx
myhubot xxx
@myhubot xxx
myhubot: xxx
Send vs Reply
- send will send the message to everyone
- reply will reply the message to the specified person
The Random
msg object has a random method that randomly extracts an element from the array object that follows
quote
msg.send msg.random arrayObject
hubot Scripts Explained
http://theprogrammingbutler.com/blog/archives/2011/10/28/hubot-scripts-explained/
(5) Installation scripts
Hubot has a lot of ready-made scripts that can integrate various services.
quote
D: \ hubotsample> npm search hubot-scripts github
D: \ hubotsample> npm install --save hubot-plusplus
[email protected] node_modules \ hubot-
plusplus [email protected]
├── [email protected] .6
└── [email protected]
D: \ hubotsample> npm install --save hubot-plusplus
[email protected] node_modules \ hubot-
plusplus [email protected]
├── [email protected] .6
└── [email protected]
Add package-name to external-scripts.json
quote
"hubot-plusplus"
quote
okbot> ruby++
okbot> ruby has 1 point
okbot> java--
okbot> java has -1 points
okbot> ruby has 1 point
okbot> java--
okbot> java has -1 points
(6) Hubot-script instance
timing script
scripts/cron.coffee
cronJob = require('cron').CronJob module.exports = (robot) -> send = (room, msg) -> response = new robot.Response(robot, {user : {id : -1, name : room}, text : "none", done : false}, []) response.send msg new cronJob('0 * * * * *', () -> currentTime = new Date send '#your-channel-name', "current time is #{currentTime.getHours()}:#{currentTime.getMinutes()}." ).start()
quote
D:\hubotsample>npm install cron --save
D:\hubotsample>bin\hubot -a shell
D:\hubotsample>bin\hubot -a shell
http request
scripts/googleGEO.coffee
module.exports = (robot) -> robot.hear /location (.*)/, (msg) -> request = robot.http("https://maps.googleapis.com/maps/api/geocode/json") .query(address: msg.match[1]) .get() request (err, res, body) -> json = JSON.parse body location = json['results'][0]['geometry']['location'] msg.send "#{location['lat']}, #{location['lng']}"
quote
okbot> location Beijing
okbot> 39.904211, 116.407395
okbot> 39.904211, 116.407395
Crawl data (request, cheerio)
scripts/title.coffee
request = require 'request' cheerio = require 'cheerio' module.exports = (robot) -> robot.respond /title (.*)/i, (msg) -> url = msg.match[1] options = url: url timeout: 2000 headers: {'user-agent': 'node title fetcher'} request options, (error, response, body) -> $ = cheerio.load body title = $('title').text().replace(/\n/g, '') msg.send(title)
quote
D:\hubotsample>npm install --save request
D:\hubotsample>npm install --save cheerio
D:\hubotsample>bin\hubot -a shell
okbot> okbot title http://github.com
okbot> How people build software · GitHub
okbot> okbot title http://www.google.com
okbot> Google
D:\hubotsample>npm install --save cheerio
D:\hubotsample>bin\hubot -a shell
okbot> okbot title http://github.com
okbot> How people build software · GitHub
okbot> okbot title http://www.google.com
okbot> Google
http answer (httpd)
scripts/version.coffee
module.exports = (robot) -> robot.router.get "/version", (req, res) -> res.end robot.version
Visit http://localhost:8080/version.
The default port is 8080, and the environment variable can be modified: export PORT=8080
Hubot relies heavily on environment variables to configure scripts, so it generally makes a startup script:
quote
#!/bin/sh
export HUBOT_ENV_TEST_VAR=""
bin/hubot -a twitter -n testbot
export HUBOT_ENV_TEST_VAR=""
bin/hubot -a twitter -n testbot
quote
@echo off
SET HUBOT_ENV_TEST_VAR=""
bin\hubot.cmd -a twitter -n testbot
SET HUBOT_ENV_TEST_VAR=""
bin\hubot.cmd -a twitter -n testbot
Use in script:
quote
TEST_VAR = process.env.HUBOT_ENV_TEST_VAR
Catch all pending messages
scripts/catchAll.coffee
module.exports = (robot) -> robot.catchAll (res) -> res.send "Nothing Found:#{res.message.text}"
hubotスクリプトの書き方とサンプル Collection
http://blog.fumiz.me/2012/08/05/hubot-irc-bot-script/
Writing Hubot Scripts
http://scarletsky.github.io/2016/05/02/ write-your-own-hubot-scripts/
(7) Custom Adapter
Hubot provides two adapters by default: shell and campfile
shell for development and debugging, and Chat Services other than campfile also have open source implementations.
Adapter basically consists of a
new file\node_modules\hubot\src\adapters\SampleAdapter.coffee
class SampleAdapter extends Adapter send: (envelope, strings...) -> @robot.logger.info "Send" run: -> @robot.logger.info "Run" exports.use = (robot) -> new SampleAdapter robot
Modify the file\node_modules\hubot\src\robot.coffee
quote
HUBOT_DEFAULT_ADAPTERS = [
'campfire'
'SampleAdapter'
'shell'
]
'campfire'
'SampleAdapter'
'shell'
]
start the bot
quote
D:\hubotsample>bin\hubot -a SampleAdapter
* All Adapters must inherit from Adapter
* The two most important methods in Adapter are send and run, other methods such as emote, reply, topic, play, etc. are only required in specific scenarios.
* The run method is executed when the bot starts.
* The send method is executed when the message is replied.
* There are detailed method descriptions in the parent class adapter.coffee https://github.com/github/hubot/blob/master/src/adapter.coffee
* The Adapter name must be: the file name in src\adapters & the name defined in HUBOT_DEFAULT_ADAPTERS of robot.coffee or
the Adapter of the Chat service consistent with hubot-#{adapter}
{Adapter, TextMessage} = require 'hubot' {EventEmitter} = require 'events' class MyChatAdapter extends Adapter send: (envelope, strings...) -> @bot.send str for str in strings run: -> options = token: process.env.HUBOT_CHAT_TOKEN rooms: process.env.HUBOT_CHAT_ROOMS account: process.env.HUBOT_CHAT_ACCOUNT bot = new MyChatStreaming options, @robot bot.on 'message', (userId, userData, message) -> user = @robot.brain.userForId userId, userData @receive new TextMessage user, message bot.listen() exports.use = (robot) -> new MyChatAdapter robot class MyChatStreaming extends EventEmitter constructor: (options, @robot) -> @token = options.token @rooms = options.rooms.split(",") @account = options.account send: (message) -> # Send data to your chat service listen: -> # Get messge data from chat service # @emit 'message', user, message
For details, please refer to: https://github.com/github/hubot/blob/master/src/adapters/campfire.coffee How to
extend the robot:
\node_modules\hubot\src\adapters\incircle.coffee
class TestXXX extends Adapter constructor: (robot) -> super robot robot.hearXXX = (options, callback) -> robot.listeners.push new TextListener(robot, "@XXXmessage", options, callback)
\scripts\testbot.coffee
module.exports = (robot) -> robot.hearXXX (msg) -> msg.send "#{JSON.stringify msg}"
(8) WeChat adapter
https://github.com/KasperDeng/Hubot-WeChat
The main mechanism is to hack the web version of WeChat protocol, first log in to the WeChat account with a mobile phone, and then simulate the web version of WeChat login, so that WeChat messages can be accepted.
- npm install hubot-weixin --save
- Login to WeChat on the mobile phone
- Open the webpage WeChat: web.weixin.qq.com
- Mobile phone scan login
- View the following information on the console /node_modules/hubot-weixin/config.yaml cookie: Uin: Sid: Skey: DeviceID:
- bin \ hubot.cmd -n bot -l / -a weixin
Reference:
Bot that is eating the world: where did it come from and where does it go?
Hubot: Chatbot from GitHub
GitHub Society! bot Kaikai・実行フレームワーク「Hubot」
TDD Hubot scripts with gulp+mocha
Using Hubot in Skype
http://qiita.com/bouzuya/items/c7d0ad80c357aab6b696