Last active
August 29, 2015 14:12
-
-
Save kakajika/8bd294248b24b0009426 to your computer and use it in GitHub Desktop.
JSON responce pattern loader for Hubot.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# responder.coffee | |
# | |
# Description: | |
# Load responce pattern from json file. | |
# | |
# Commands: | |
# hubot responder reload - JSONファイルからResponceパターンを再読み込みします. | |
# hubot responder list - Responceパターンの一覧を表示します. | |
fs = require 'fs' | |
class Responder | |
constructor: (@responces, @index) -> | |
class Responders | |
constructor: (@robot, @path) -> | |
@robot.brain.data.responders = {} | |
@reload() | |
reload: -> | |
@removeAll() | |
json = fs.readFileSync @path | |
list = JSON.parse json | |
for data in list | |
@add data.pattern, data.responces | |
list: -> | |
@robot.brain.data.responders | |
count: -> | |
@list().length | |
find: (pattern) -> | |
@list()[pattern] | |
add: (pattern, responces) -> | |
@robot.hear pattern, (msg) -> | |
msg.reply msg.random responces | |
index = @robot.listeners.length - 1 | |
@list()[pattern] = new Responder(responces, index) | |
remove: (pattern) -> | |
responder = @find(pattern) | |
if responder | |
@robot.listeners.splice(responder.index, 1, (->)) | |
delete @list()[pattern] | |
removeAll: -> | |
for pattern, responder of @list() | |
@remove pattern | |
@robot.brain.data.responders = {} | |
module.exports = (robot) -> | |
responders = new Responders(robot, "json/responces.json") | |
robot.respond /responder reload/i, (msg) -> | |
responders.reload() | |
msg.send "Loaded responder patterns from json." | |
robot.respond /responder list/i, (msg) -> | |
msg.send "#{JSON.stringify(responders.list())}" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
"pattern" : "pattern1|pattern2", | |
"responces" : [ | |
"responce1", | |
"responce2" | |
] | |
}, | |
{ | |
"pattern" : "pattern3", | |
"responces" : [ | |
"responce3" | |
] | |
} | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment