/
webhook.js
124 lines (100 loc) · 2.9 KB
/
webhook.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
'use strict'
var express = require('express');
var storage = require('node-persist');
var dateFormat = require('dateformat');
const smoochBot = require('smooch-bot');
const MemoryLock = smoochBot.MemoryLock;
const SmoochApiStore = smoochBot.SmoochApiStore;
const SmoochApiBot = smoochBot.SmoochApiBot;
const StateMachine = smoochBot.StateMachine;
const SmoochCore = require('smooch-core');
const jwt = require('../jwt');
const lock = new MemoryLock();
const script = require('../script');
const store = new SmoochApiStore({
jwt
});
class BetterSmoochApiBot extends SmoochApiBot {
constructor(options) {
super(options);
}
sendImage(imageFileName) {
const api = this.store.getApi();
let message = Object.assign({
role: 'appMaker'
}, {
name: this.name,
avatarUrl: this.avatarUrl
});
var real = fs.realpathSync(imageFileName);
let source = fs.readFileSync(real);
return api.conversations.uploadImage(this.userId, source, message);
}
}
const name = 'ABC Mall';
const avatarUrl = 'http://smoochwebhook.azurewebsites.net/images/avatar.png';
var router = express.Router();
//Only POST
router.post('/', function (req, res, next) {
var isPostback = req.body.trigger == "postback";
var msg = '';
const appUser = req.body.appUser;
const userId = appUser.userId || appUser._id;
const stateMachine = new StateMachine({
script,
bot: new BetterSmoochApiBot({
name,
avatarUrl,
lock,
store,
userId
})
});
if (!isPostback) {
const messages = req.body.messages.reduce((prev, current) => {
if (current.role === 'appUser') {
prev.push(current);
}
return prev;
}, []);
if (messages.length === 0 && !isTrigger) {
return res.end();
}
msg = messages[0];
} else {
msg = req.body.postbacks[0];
msg.text = msg.action.text;
switch (msg.action.payload) {
case 'check_in':
console.log("Check in");
break;
default:
break;
}
}
stateMachine.receiveMessage(msg)
.then(() => res.end())
.catch((err) => {
console.error('SmoochBot error:', err);
console.error(err.stack);
res.end();
});
});
router.post('/SendMessage', function (req, res, next) {
var id = req.body.id;
var message = req.body.message;
console.log("id " + id);
console.log("message" + message);
var smoochCore = new SmoochCore({
jwt: jwt,
scope: 'app'
});
smoochCore.appUsers.sendMessage(id, {
text: message,
role: 'appMaker'
}).catch(function (error) {
console.log(error);
});
res.end();
});
module.exports = router;