简体   繁体   English

在bot.use中设置event.textLocale(Node.js Microsoft Bot Framework)

[英]Setting event.textLocale in bot.use (Node.js Microsoft Bot Framework)

I'm using an Azure Web App Bot (Node v 6.9.1) and when the Test in Web Chat interface is initialized, text and textLocale are null. 我正在使用Azure Web App Bot(节点v 6.9.1),并且在“ Web聊天中的测试”界面初始化时,text和textLocale为空。 But when the first input is received from the user, event.textLocale is assigned a default 'en' value so I'm not able to reset this just once from bot.use(receive) after doing a language detect (as it is not null at this stage). 但是,当从用户接收到第一个输入时,event.textLocale被分配了默认的“ en”值,因此在执行语言检测后,我无法仅从bot.use(receive)重置一次(因为它不是在此阶段为null)。

Is there an alternative way to reset event.textLocale just once as I'm not able to propagate the locale value through any global node.js variable from bot.use(receive) to bot.use(send) event either? 有没有一种方法可以重置一次event.textLocale,因为我也无法通过任何全局的node.js变量从bot.use(receive)到bot.use(send)事件传播语言环境值? Please help, thanks 请帮忙,谢谢

app.js Snippet app.js片段

bot.use({
    receive: function (event, next) {       
        var text = ''; 
        async.waterfall([
            function(callback) {
                text= event.text;
                textLocale = event.textLocale;
                request.get(
                    'http://<<<hostname>>>/translateIntent?intent='+text.toString()+'&textLocale='+(textLocale).toString(), 
                    function (error, response, body) {
                        if (!error && response.statusCode == 200) {
                            var jsonStr = JSON.parse(body);
                            event.text=jsonStr.outputText;
                            // Storing the user's text locale if not already set 
                            // - does not execute as event.textLocale is set by default and global variables are not propagating from receive to send 
                            if(!event.textLocale && (jsonStr.inputLanguageContext != "(Unknown)")) {
                                event.textLocale = jsonStr.inputLanguageContext;
                                console.log("Rewriting event text locale to :" + jsonStr.inputLanguageContext); 
                            }

                            callback(null, event);
                        }
                    }
                );  
            },
            function(event, callback) {
                console.log("Rec after modification:");
                console.log("event.textLocale: " + event.textLocale);
                next();
                callback(null, 'done');
            }
        ]);
    },
    send: function (event, next) {
        // translate response using event.textLocale as languageTo  {event.text, languageFrom='en', event.textLocale}
    } 
});

translate api: 翻译api:

app.get("/translateIntent", function(request, response) {
    var inputText = request.param('intent');
    if(inputText) {
        var textLocale = '';    var outputText = '';
        // If locale is already set, languageDetectHelper does not need to be called  
        if(request.param('textLocale')) {
            textLocale = request.param('textLocale');
            if(textLocale == 'en') {
                // No translation required, just send back the inputText
                response.end({outputText:inputText, inputLanguageContext:languageCodeDetected}); 
            } else {
                // Call translate, with languageFrom as textLocale, and languageTo = 'en'
                translateHelper.GetTranslation(inputText, textLocale, languageTo).then(jsonStr =>  {
                    response.end(jsonStr);
                }).catch(error => { 
                    console.log("Error: " + error); 
                }) 
            }
        } else {
            // Locale not yet set, call detectLanguage 
            languageDetectHelper.GetTextLanguage(inputText).then(languageCodeDetected => {
                var languageTo = 'en';  
                if(languageCodeDetected == 'en' || languageCodeDetected == '(Unknown)') {
                    // Send back without translation 
                    response.end({outputText:inputText, inputLanguageContext:languageCodeDetected}); 
                } else {
                    // Translate to English 
                    translateHelper.GetTranslation(inputText, languageCodeDetected, languageTo).then(jsonStr =>  {
                        console.log("JSON stringify output in server: " + JSON.stringify(jsonStr));
                        response.end(jsonStr);
                    }).catch(error => { 
                        console.log("Error: " + error); 
                    }) 
                }               
            }).catch(error=> {
                console.log("Error: " + error);
            });     
        }
    } else {
        console.log("No translation required, waiting for the next event"); 
    }
});

In my understanding, you're trying to detect user's input language and then if it's not English, translate it to English so your backend like LUIS service can handle it, and after handling your bot will send English response by default to your user, but you want to translate the response again back to user's input language. 以我的理解,您正在尝试检测用户的输入语言,然后将其翻译为英语,以便您的后端(例如LUIS服务)可以将其翻译为英语,并且在处理完您的漫游器后,默认情况下会将英语响应发送给您的用户,但是您想要将响应再次转换回用户的输入语言。

Since I can't use your code to build a complex demo, I'm here use azure cognitive service to create this demo: 由于我无法使用您的代码来构建复杂的演示,因此我在这里使用azure认知服务来创建此演示:

var tokenHandler = require('./tokenHandler');
tokenHandler.init();

var TOLOCALE = 'en';
var FROMLOCALE;

bot.use({
    receive: function (event, next) {
        var token = tokenHandler.token();

        //text ayalytics 
        if(event.text != ""){
            var options = {
                method: 'POST',
                url: 'https://westcentralus.api.cognitive.microsoft.com/text/analytics/v2.0/languages',
                body: { documents: [{ id: 'message', text: event.text }]},
                json: true,
                headers: {
                    'Ocp-Apim-Subscription-Key': 'YOUR-KEY'
                }
            };
            request(options, function (error, response, body) {
                if (!error && body) {
                    if (body.documents && body.documents.length > 0) {
                        var languages = body.documents[0].detectedLanguages;
                        if (languages && languages.length > 0) {
                            event.textLocale = languages[0].iso6391Name;
                            FROMLOCALE = event.textLocale;
                        }
                    }
                }
            //text translations
            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 {
                        parseString(body, function (err, result) {
                            console.log(result.string._);
                            event.text = result.string._;
                            next();
                        });

                    }
                });
            } 
            else{
                    console.log("No token");
                    next();
                }
            });
        }
        else{
            next();
        }
    },
    send: function (event, next) {
        // translate response using event.textLocale as languageTo  {event.text, languageFrom='en', event.textLocale}
        var token = tokenHandler.token();
        if (token && token !== ""){
            var options = {
                method: 'GET',
                url: 'http://api.microsofttranslator.com/v2/Http.svc/Translate'+'?text=' + event.text + '&from=' + TOLOCALE +'&to=' + FROMLOCALE,
                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 {
                    parseString(body, function (err, result) {
                        console.log(result.string._);
                        event.text = result.string._;
                        next();
                    });

                }
            });
        }
    }
});

//=========================================================
// Bots Dialogs
//=========================================================
var luisAppUrl = 'YOUR-LUIS-ENDPOINT';
var recognizer = new builder.LuisRecognizer(luisAppUrl);
var intents = new builder.IntentDialog({ recognizers: [recognizer] });
bot.dialog('/', intents);

//Route the luis intents to the various dialogs
intents.matches('greeting', (session)=>{
    session.send('You reached Greeting intent, you said \'%s\'.', session.message.text);
}).onDefault((session)=>{
    session.send('Sorry, I did not understand \'%s\'.', session.message.text);
});

The code for tokenhandler is like this: tokenhandler的代码如下:

var request = require('request');

var token = "";
var tokeninterval;
var TRANSLATIONKEY = 'YOUR-KEY';

function getToken() {

    var options = {
        method: 'POST',
        url: 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken?Subscription-Key=' + TRANSLATIONKEY
    };

    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 {
            //Token gets returned as string in the body
            token = body;
        }
    });

    interval = setTimeout(getToken, 540000); // runs once every 9 minutes, token lasts for 10
}

// Stop the token generation
function stopInterval() {
    clearTimeout(tokeninterval);
}

module.exports = {
  init: function() {
      getToken();
  }, 
  stop: function() {
      stopInterval();
  },
  token: function () {
      return token;
  }
};

This demo works by my side, but for your demo, if you want to use the locale that is set in receive , you can directly define a variable like the FROMLOCALE in my code, set the value to it in receive and use this variable in send . 该演示的作品在我身边,但您的演示,如果你想使用设置在现场receive ,您可以直接定义类的变量FROMLOCALE在我的代码,将该值设置为它在receive和使用这个变量send

If I've misunderstand your requirement, please feel free to let me know. 如果我误解了您的要求,请随时告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Microsoft Bot Framework 3.15 中用于 Node.js 的“reloadAction”未传递“dialogArgs” - 'reloadAction' in Microsoft Bot Framework 3.15 for Node.js is not passing on 'dialogArgs' 如何在Microsoft Bot Framework的node.js版本中“退出”? - How to 'exit' in the node.js version of Microsoft Bot Framework? 使用Node.js Microsoft Bot Framework显示图像 - Display images using the Node.js Microsoft Bot Framework 在Microsoft Bot Framework(Node.js)中的对话框之间切换 - Switches between Dialog in Microsoft Bot Framework (Node.js) 在Microsoft Bot Framework for Skype(node.js)中提示输入文件 - Prompt for file in Microsoft Bot Framework for Skype (node.js) 带有node.js的Microsoft bot框架以及数据库和流 - microsoft bot framework with node.js plus database and flow 无法使用TriggerAction匹配Microsoft Bot框架(node.js)中的LUIS意图 - Unable to use TriggerAction to match with LUIS intent in Microsoft Bot framework (node.js) 如何为 bot 响应添加延迟,使其在 Microsoft Bot Framework Node.js 中感觉更真实? - How to add a delay to bot responses, so it feels more real in Microsoft Bot Framework Node.js? 什么决定了“bot.dialog”何时传递到 Microsoft Bot Framework 中瀑布的下一个 function? (Node.js) - What determines when 'bot.dialog' passes to the next function of the waterfall in Microsoft Bot Framework? (Node.js) Microsoft QnA bot Node.js - Microsoft QnA bot Node.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM