Conversation Services Bot
// --------------- Configuration --------------- //
const TENANT_ALIAS = 'wqltest';
const CLIENT_ID = 'M2UyNTdiZjgtZTRhOC00MjZmLTk0NTEtYmFjNWYyN2EzMDlh';
const CLIENT_SECRET = 'tjabbivnoien2eewnwyba9uul3puqq0c078gepokoe71zltuw7mz6bhoqjmllmouxiutkk1wfwidz683hi3e4p65xk482ejlj5r';
// --------------------------------------------- //
const got = require('got');
const express = require("@runkit/runkit/express-endpoint/1.0.0");
// const express = require("express"); // use this line if you are not using runkit.com
const bodyParser = require('body-parser');
const app = express(exports);
app.use(bodyParser.json());
// Workday Cloud Platform base URL
const WORKDAY_API = 'api.workday.com';
// Simple cache so that a new token isn't needed for every message
var tokenCache;
// Set up the endpoint through Express.js
app.post('/', async function(req, res) {
console.info(`Got message from Workday: ${req.body.chatMessage.text.stripped}`);
try {
const name = req.body.chatMessage.createdByDisplayName;
const wid = /USER:(.*)/.exec(req.body.chatMessage.createdByID)[1];
const message = `Hi, **${name}**!\n(Workday ID: *${wid}*)\nYou said: ${req.body.chatMessage.text.text}`;
const token = await getToken();
await sendMessage(token, req.body.conversationID, message);
} catch (e) {
console.error(`Error sending chat message: ${e}`);
}
});
// Uses the Client Credentials Grant Type to authenticate with Workday Cloud Platform.
// Reuses tokens from prior requests, if they're still valid.
async function getToken() {
// get and cache a new token if no cached token or cached token is expired
if(!tokenCache || (tokenCache.expireDate < new Date())) {
const url = `https://auth.${WORKDAY_API}/v1/token`;
const encodedAuth = Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64');
const options = {
headers: {
Authorization: `Basic ${encodedAuth}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `tenant_alias=${TENANT_ALIAS}&grant_type=client_credentials`
};
const response = await got.post(url, options);
const jsonResponse = JSON.parse(response.body);
const accessToken = jsonResponse.access_token;
const expireDate = new Date();
expireDate.setSeconds(expireDate.getSeconds() + jsonResponse.expires_in);
tokenCache = {"accessToken":accessToken, "expireDate": expireDate};
}
return tokenCache.accessToken;
}
// Sends a message to a conversation ID using the provided token.
async function sendMessage(token, conversationId, message) {
const url = `https://${WORKDAY_API}/tlkw/rest/conversations/no-tenant-needed/${conversationId}/chatMessages`;
const options = {
json: true,
headers: {
Authorization: `Bearer ${token}`
},
body: {
text: message
}
};
await got.post(url, options);
console.info(`Message sent to ${url}: ${message}`);
}
no comments