-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWitMessengerBot.js
executable file
·77 lines (63 loc) · 2.2 KB
/
WitMessengerBot.js
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
72
73
74
75
76
77
'use strict'
const {Wit, log} = require('node-wit')
const Bot = require('messenger-bot')
const {formatQuickReplies} = require('./format/fb-formatter')
//extends Bot from https://github.com/remixz/messenger-bot
//has wit.ai NLP functionality + messenger's SEND api.
class WitMessengerBot extends Bot{
constructor(fbOptions, witOptions, botSessionsDelegate){
super(fbOptions)
//if user doesn't define his own send
if(!("send" in witOptions['actions'])){
//add the default send function as a function that calls the method: this.send
witOptions.actions["send"] = (request, response) =>{
return this.send(request, response)
}
}
//getting wit app instance with the actions defined
this.witInstance = new Wit({
accessToken: witOptions.accessToken,
actions: witOptions.actions,
logger: new log.Logger(log.DEBUG)
})
//to handle sessions
this.botSessionsDelegate = botSessionsDelegate
}
//run actions of the wit.ai instance
runActions(sessionId, text, context, completionHandler){
var witMessengerBot = this
return this.witInstance.runActions(sessionId,text,context).then(completionHandler)
}
//implementation of the wit.ai required send function with messenger platform sendMessage
send(request,response){
const{sessionId,context,entities} = request
const recipientId = this.botSessionsDelegate.fbIdForSession(sessionId)
const{text,quickreplies,confidence} = response
let quick_replies = formatQuickReplies(quickreplies)
var witMessengerBot = this
return new Promise(function(resolve, reject){
witMessengerBot.sendMessage(recipientId,{text,quick_replies},(err,info)=> {
if(err) console.log(err)
})
return resolve()
})
}
findOrCreateSession(fbid){
return this.botSessionsDelegate.findOrCreateSession(fbid)
}
fbIdForSession(sessionId){
return this.botSessionsDelegate.fbIdForSession(sessionId)
}
//modify existing session
writeSession(sessionId, sessionData){
this.botSessionsDelegate.write(sessionId, sessionData)
}
//delete session
deleteSession(sessionId){
this.botSessionsDelegate.delete(sessionId)
}
}
module.exports = {
WitMessengerBot: WitMessengerBot,
BotSessionsDelegate: require('./user-sessions/sessions.js')
}