-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (70 loc) · 2.08 KB
/
index.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
import { Wit, log, interactive } from 'node-wit'
import moment from 'moment'
import 'moment-round'
import { WIT_TOKEN } from '../config'
import { dbConnect } from '../config/db'
import * as send from './send'
import User from '../models/User'
import QuickReply from '../templates/QuickReply'
const TESTING_MODE = require.main === module
//
// Bot Actions
// ---
//
const actions = {
async send(req, res) {
const user = await User.findOne(
{ 'session.id': req.sessionId }
)
if (user && user.messenger_id) {
if (req.context.quick_replies) {
await send.textMessage(user.messenger_id, res.text, req.context.quick_replies)
}
else if (res.quickreplies) {
let quick_replies = createTextQuickReplies(res.quickreplies)
await send.textMessage(user.messenger_id, res.text, quick_replies)
}
else {
await send.textMessage(user.messenger_id, res.text)
}
await User.update(
{ messenger_id: user.messenger_id },
{ 'session.context': req.context }
)
} else if (!TESTING_MODE) {
console.error(`Oops! Couldn\'t find user for session: ${req.sessionId}`)
}
},
async getContact({ context, text, entities}) {
if (entities.contact && Array.isArray(entities.contact)) {
// Choose first entity
entities.contact.map(entity => context.contact = entity.value)
}
return context
}
}
// Helpers
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
const isAnOption = (options, text) => options.some(option => option === text)
export const createTextQuickReplies = (options) => options.map(option => new QuickReply({
title: option,
content_type: 'text',
payload: 'empty'
}))
//
// Initialize Wit.ai
// ---
// API Reference: https://wit.ai/docs
//
export const wit = new Wit({
accessToken: WIT_TOKEN,
actions: actions,
logger: new log.Logger(log.INFO)
})
// BOT TESTING MODE
if (TESTING_MODE) {
console.log('Bot testing mode!')
dbConnect()
interactive(wit)
}