-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrivescript.coffee
71 lines (62 loc) · 2.36 KB
/
rivescript.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# Description:
# Provides a RiveScript chatbot for Hubot. This bot will respond to all
# messages directed at it by using a RiveScript brain.
#
# Dependencies:
# "rivescript": "^1.13.0"
#
# Configuration:
# HUBOT_RIVESCRIPT_BRAIN - The path to a folder containing RiveScript files
# (with the *.rive file extensions).
# HUBOT_RIVESCRIPT_PREFIX - If you don't want your Hubot to answer all
# messages using RiveScript, set this string to be a prefix, e.g. with
# the value "rs" a user must say "hubot rs hello" for the bot to answer
# their "hello" message.
# HUBOT_RIVESCRIPT_UTF8 - Boolean to enable UTF-8 mode, 1 or 0, default 1
#
# Commands:
# hubot [rs] <message> - Retrieve a response from RiveScript.
#
# Author:
# Noah Petherbridge, https://github.com/kirsle
RiveScript = require "rivescript"
module.exports = (robot) ->
# Configuration parameters.
debug = "#{process.env.HUBOT_RIVESCRIPT_DEBUG}" is "1" or false
brain = process.env.HUBOT_RIVESCRIPT_BRAIN or "./brain"
prefix = if process.env.HUBOT_RIVESCRIPT_PREFIX then "#{process.env.HUBOT_RIVESCRIPT_PREFIX}\\s+" else "\\s*"
utf8 = "#{process.env.HUBOT_RIVESCRIPT_UTF8}" is "1" or false
sync = "#{process.env.HUBOT_RIVESCRIPT_SYNC}" is "1" or false
# The matcher regexp.
regexp = new RegExp("#{prefix}(.*)", "i")
# Initialize the RiveScript brain.
@bot = new RiveScript({
debug: debug,
utf8: utf8
})
# Save user variables after each interaction.
@saveUservars = (user) ->
userData = robot.brain.get("rivescript") or {}
userData[user.name] = @bot.getUservars(user.name)
robot.brain.set("rivescript", userData)
@bot.loadDirectory(brain, ->
@bot.sortReplies()
# Load user variables from hubot brain into rivebot, when ready
robot.brain.on 'loaded', =>
userData = robot.brain.get("rivescript") or {}
for user, data of userData
@bot.setUservars user, data
robot.respond regexp, (res) =>
if sync
reply = @bot.reply(res.message.user.name, res.match[1], @)
if reply
res.send reply
@saveUservars(res.message.user)
else
reply = @bot.replyAsync(res.message.user.name, res.match[1], @).then (reply) ->
if reply
res.send reply
@saveUservars(res.message.user)
, (err) ->
console.error "Couldn't load RiveScript replies: #{err}"
)