Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PubNub BLOCK for Microsoft's Translate V3 API
// Demo URL https://codepen.io/team/PubNub/pen/rdQMaN
// ALERT!
// YOU NEED TO ADD YOUR MICROSFOT API KEY 'Ocp-Apim-Subscription-Key'
//
// 1.) Click "My Secrets" button.
// 2.) Add a new Secret 'Ocp-Apim-Subscription-Key'
// 3.) Paste in your Microsoft Translator V3 API Key
// 4.) Save
// 5.) Restart/Start your Module
//
const xhr = require('xhr');
const vault = require('vault');
export default request => {
// Capture Text and Language to Translate
let text = request.message.text;
let lang = request.message.language;
let data = request.message.data || {};
// ChatEngine Compatibility Data Object
lang = lang || (data && data.language) || 'zh-HH';
text = text || (data && data.text) || 'hello';
// Translate using Microsoft V3 Translator API
return translate( text, lang ).then( result => {
request.message.data = request.message.data || {};
request.message.data.translation = result;
request.message.data.text = result.translations[0]['text'];
return request.ok();
} ).catch( error => {
console.error(error);
return request.ok();
} );
};
// ------------------------------------
// Microsoft Translator API V3
// ------------------------------------
// Microsoft Response Format
// { detectedLanguage : { language : "en", score : 1.0 },
// translations : [{ text : text, to : language }] }
function translate( text='hello', language='zh-HH' ) {
return new Promise( ( resolve, reject ) => {
return vault.get('Ocp-Apim-Subscription-Key').then( oask => {
if (!oask) return reject("Missing 'Ocp-Apim-Subscription-Key'");
let headers = {};
let opts = {
host : 'https://dev.microsofttranslator.com'
, method : 'POST'
, headers : headers
, path : '/translate?api-version=3.0'
, to : '&to=' + language
, body : JSON.stringify([{ Text : text }])
};
headers['Content-Type'] = 'application/json';
headers['Ocp-Apim-Subscription-Key'] = oask;
let uri = opts.host + opts.path + opts.to;
return xhr.fetch( uri, opts )
.then( res => resolve(JSON.parse(res.body)[0]) )
.catch( error => reject(error) );
} ).catch( error => {
return reject(error);
} );
} );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.