Thursday, 8 June 2017

Bot Framework Node.js translation with Bing Translate API according to prefered language

I am trying to implement translation feature within bot developed with Node.js Bot Builder SDK. I found sample where this translation is done like this:

bot.use({
    receive: function (event, next) {
            var token = tokenHandler.token();
            if (token && token !== ""){ //not null or empty string
                var urlencodedtext = urlencode(event.text); // convert foreign characters to utf8
                var options = {
                    method: 'GET',
                    url: 'http://api.microsofttranslator.com/v2/Http.svc/Translate'+'?text=' + urlencodedtext + '&from=' + FROMLOCALE +'&to=' + TOLOCALE,
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                };
                request(options, function (error, response, body){
                    //Check for error
                    if(error){
                        return console.log('Error:', error);
                    } else if(response.statusCode !== 200){
                        return console.log('Invalid Status Code Returned:', response.statusCode);
                    } else {
                        // Returns in xml format, no json option :(
                        parseString(body, function (err, result) {
                            console.log(result.string._);
                            event.text = result.string._;
                            next();
                        });

                    }
                });
                } else {
                    console.log("No token");
                    next();
                }

    });

I need to do this, because I need to utilize LUIS and it does not support language with which my users can communicate with the bot (Slovak). However, bot is multilingual, that means I am supporting also English. In case my user uses English language (he or she set it up and this preference is stored within session.preferredLocale) I am doing translation that is not needed.

How can I access session in receive middleware, so I can check whether there is need to do the translation or not? And also, how can I sendTyping before doing the translation? It can sometime take longer time, and so bot becomes unresponsive.

Please note, that I cannot use event.textLocale, as I am planning to publish bot to messenger, and it does not post this information. I also do not want to use Locale recognizer API as another cognitive service.

Thank you!



via marek_lani

No comments:

Post a Comment