-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.js
71 lines (61 loc) · 2.06 KB
/
bot.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
require('dotenv').config();
const express = require('express');
const bot = express();
const bodyParser = require('body-parser');
const Drift = require('drift-chat');
const Team = require('./models/team').model;
bot.use(bodyParser.json());
bot.listen(process.env.PORT || 3000, () => console.log('POC Bot for Drift is listening on port 3000!'));
let mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
mongoose.connect(process.env.MONGO_URI);
bot.get('/oauth', (req, res) => {
const drift = new Drift();
const options = {
clientId: process.env.CLIENTID,
clientSecret: process.env.DRIFTKEY,
code: req.query.code,
};
drift.oauth(options, async function(err,driftToken){
if(err){
console.log(err);
} else {
const teamObj = {
orgId: driftToken.orgId,
driftToken: driftToken
};
const team = await Team.update({orgId: driftToken.orgId},teamObj,{upsert:true, setDefaultsOnInsert: true});
console.log(team)
}
});
return res.status(200).send("YOU DID IT!").end();
});
bot.post('/', async (message, res) => {
if (message.body.token === process.env.DRIFTVERIFY &&
message.body.type === 'new_message' &&
message.body.data.body.startsWith('/foobar')) {
let team = await Team.findOne({orgId: message.body.orgId});
const drift = new Drift(team.driftToken.accessToken);
drift.getConvo(message)
.then((body) =>
console.log(body))
//do something awesome with the convo
.catch(async (err) => {
console.log(err);
const options = {
clientId: process.env.CLIENTID,
clientSecret: process.env.DRIFTKEY,
refreshToken: team.driftToken.refreshToken
};
team.driftToken = await drift.refreshToken(options);
team.save();
drift.token = team.driftToken.accessToken;
drift.getConvo(message)
.then((body) =>
console.log(body))
//do something awesome with the convo
.catch((err) => console.log(err));
});
}
return res.status(200).end();
});