Last active
June 8, 2018 19:26
-
-
Save nxsyed/f86cecdef46b6b66cd9cc99df5eed6e2 to your computer and use it in GitHub Desktop.
Assistant function made for pubnub functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default (request, response) => { | |
const base64Codec = require('codec/base64'); | |
const query = require('codec/query_string'); | |
const console = require('console'); | |
const xhr = require('xhr'); | |
const pubnub = require('pubnub'); | |
const vault = require('vault'); | |
const senderName = 'PubNub Bot'; | |
const version = '2018-02-16'; | |
let apiUrl = 'https://gateway.watsonplatform.net/assistant/api/v1/workspaces/'; | |
const getWatsonInfo = new Promise((resolve, reject) => { | |
vault.get('username').then((watsonUN) => { | |
vault.get('password').then((watsonPW) => { | |
vault.get('workspaceID').then((workspaceID)=>{ | |
resolve([watsonUN, watsonPW, workspaceID]); | |
}); | |
}); | |
}); | |
}); | |
return getWatsonInfo.then((watsonInfo)=>{ | |
const [watsonUsername, watsonPassword, workspaceId] = watsonInfo; | |
apiUrl += `${workspaceId}/message`; | |
const base64Encoded = base64Codec.btoa(watsonUsername + ':' + watsonPassword); | |
// bot auth | |
const apiAuth = 'Basic ' + base64Encoded; | |
const payload = JSON.stringify({ | |
input: { | |
text: request.params.question | |
} | |
}); | |
const queryParams = { | |
version | |
}; | |
const httpOptions = { | |
as: 'json', | |
headers: { | |
'Content-Type': 'application/json', | |
Accept: 'application/json', | |
Authorization: apiAuth | |
}, | |
body: payload, | |
method: 'post' | |
}; | |
const url = apiUrl + '?' + query.stringify(queryParams); | |
return xhr.fetch(url, httpOptions) | |
.then(res => { | |
return res.json() | |
.then((parsedResponse) => { | |
response.status = 200; | |
return response.send(parsedResponse.output.text[0]); | |
}); | |
}) | |
.catch(err => { | |
console.error('error during XHR', err); | |
return response.send(400); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
on line 66 do