forked from DT42/BerryNet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathline.js
84 lines (73 loc) · 2.73 KB
/
line.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
// Copyright 2017 DT42
//
// This file is part of BerryNet.
//
// BerryNet is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// BerryNet is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with BerryNet. If not, see <http://www.gnu.org/licenses/>.
'use strict';
const mqtt = require('mqtt');
const line = require('@line/bot-sdk');
const imgur = require('imgur');
const config = require('./config');
const broker = config.brokerHost;
const client = mqtt.connect(broker);
const topicActionLog = config.topicActionLog;
const topicNotifyLINE = config.topicNotifyLINE;
const topicDashboardInferenceResult = config.topicDashboardInferenceResult;
const targetUserID = config.LINETargetUserID;
// create LINE SDK config
const LINEConfig = {
channelAccessToken: config.LINEChannelAccessToken,
channelSecret: config.LINEChannelSecret,
};
// create LINE SDK client
const LINEClient = new line.Client(LINEConfig);
function log(m) {
client.publish(topicActionLog, m);
console.log(m);
}
client.on('connect', () => {
client.subscribe(topicNotifyLINE);
client.subscribe(topicDashboardInferenceResult);
log(`client connected to ${broker} successfully.`);
});
client.on('message', (t, m) => {
const size = m.length;
log(`client on topic ${t}, received ${size} bytes.`)
if (t === topicDashboardInferenceResult) {
const result = m.toString();
LINEClient.pushMessage(targetUserID, { type: 'text', text: result });
return;
}
// save image to file and upload it to imgur for display in LINE message
const snapshot_path = m.toString();
imgur.uploadFile(snapshot_path)
.then((json) => {
var imgurLink = json.data.link;
imgurLink = imgurLink.replace('http:\/\/', 'https:\/\/');
log(`An image has been uploaded to imgur. link: ${imgurLink}`);
// Image can only be delivered via 'https://' URL, 'http://' doesn't work
LINEClient.pushMessage(targetUserID, { type: 'image',
originalContentUrl: imgurLink,
previewImageUrl: imgurLink })
.then((v) => {
log(`A message sent to ${targetUserID} successfully.`);
})
.catch((err) => {
log(`An error occurred, ${err}.`);
});
})
.catch((err) => {
log(`An error occurred. ${err}`);
});
});