· 9 years ago · Nov 01, 2016, 02:42 PM
1var config = require('./util/config')
2var request = require('request')
3var express = require('express')
4var crypto = require('crypto')
5var webapp = express()
6var bodyParser = require('body-parser')
7var LanguageTranslatorV2 = require('watson-developer-cloud/language-translator/v2');
8
9webapp.use(bodyParser.json()) // support json encoded bodies
10webapp.use(bodyParser.urlencoded({ extended: false }))
11
12const watsonWork = 'https://api.watsonwork.ibm.com'
13
14// connect to the watson translator api
15var language_translator = new LanguageTranslatorV2({
16 username: config.watson_user,
17 password: config.watson_password,
18 url: 'https://gateway.watsonplatform.net/language-translator/api'
19})
20
21// obtain a new token from watson workspace
22function getToken(callback){
23
24 // Authentication API
25 const authenticationAPI = 'oauth/token'
26
27 const authenticationOptions = {
28 "method": "POST",
29 "url": watsonWork + '/' + authenticationAPI,
30 "auth": {
31 "user": config.client_id,
32 "pass": config.client_secret
33 },
34 "form": {
35 "grant_type": "client_credentials"
36 }
37 }
38
39 request(authenticationOptions, function(err, response, body){
40 // If can't authenticate just return
41 if (response.statusCode != 200) {
42 console.log("Error authentication application. Exiting.");
43 process.exit(1);
44 }
45 callback(JSON.parse(body).access_token);
46 })
47}
48
49function sendMessage(spaceId, message){
50 getToken(function (token){
51
52 var messageData = {
53 type: "appMessage",
54 version: 1.0,
55 annotations: [{
56 type: "generic",
57 version: 1.0,
58 color: "#D5212B",
59 title: "Translation",
60 text: message
61 }]
62 }
63
64 var sendMessageOptions = {
65 "method": "POST",
66 "url": watsonWork + "/v1/spaces/" + spaceId + "/messages",
67 "headers": {
68 "Authorization": `Bearer ` + token
69 },
70 "json": messageData
71 }
72
73 request(sendMessageOptions, (err, response, body) => {
74 if(response.statusCode != 201) {
75 console.log("Error posting translation.");
76 console.log(response.statusCode);
77 }
78 })
79 })
80}
81
82// Needed to make Bluemix happy :)
83webapp.get('/', function(req, res) {
84 res.send('IBM Watson Workspace translate bot is alive and happy!')
85})
86
87// watson workspace only uses post. you have to look at the the
88// type of the body in order to find the event type.
89webapp.post('/webhook', function(req, res) {
90 console.log('post')
91 // Handle Watson Work Webhook verification challenge
92 if(req.body.type === 'verification') {
93 console.log('Got Webhook verification challenge ' + req.body)
94
95 var bodyToSend = {
96 response: req.body.challenge
97 }
98
99 var hashToSend = crypto.createHmac('sha256', config.webhookSecret).update(JSON.stringify(bodyToSend)).digest('hex')
100
101 res.set('X-OUTBOUND-TOKEN', hashToSend)
102 res.send(bodyToSend)
103 return
104 }
105
106 //Got a message
107 console.log('Content: ' + req.body.content)
108
109 // Only handle messages events, by filtering the type and Ignore our own messages
110 if (req.body.type !== 'message-created') {
111 console.log('Ende')
112 res.end()
113 return
114 }
115
116 //// check for echo keyword and send the echo back
117 if (req.body.content.substring(0,10) === '@translate') {
118 console.log("Translate requiered")
119
120 var messageWithoutKeyWord = req.body.content.substring(11).trim()
121 var splittedMessage = messageWithoutKeyWord.split(' ')
122 var toscanaMessage = ''
123 var index = req.body.spaceId.lastIndexOf(":")
124 var spaceId = req.body.spaceId.substring(index+1)
125
126 if(splittedMessage.length <= 2){
127 sendMessage(spaceId, 'Wrong usage')
128 return
129 }
130
131 var originLanguage = splittedMessage[0]
132 var destinationLanguage = splittedMessage[1]
133 var textToTranslate = messageWithoutKeyWord.substring(6).trim()
134
135 console.log('From: ' + originLanguage + ' |to: ' + destinationLanguage + ' |text: ' + textToTranslate)
136
137 language_translator.translate({
138 text: textToTranslate, source : originLanguage, target: destinationLanguage },
139 function (err, translation) {
140 if (err) {toscanaMessage = 'Sorry, i was not able to translate this!'}
141 else {toscanaMessage = translation.translations[0].translation}
142
143 // get spaceId
144 var index = req.body.spaceId.lastIndexOf(":")
145 var spaceId = req.body.spaceId.substring(index+1)
146
147 sendMessage(spaceId, toscanaMessage)
148 })
149 res.end()
150 }
151})
152
153// Start the main process listening on Port 3000
154webapp.listen(process.env.PORT || 3000)
155console.log("Watson Translate Bot listening on Port 3000")