如何在对话更新活动中获取语言环境? [英] How do I get the locale in conversationUpdate activity?

查看:40
本文介绍了如何在对话更新活动中获取语言环境?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对根据其区域设置添加的每个成员实施欢迎消息.代码如下:

I would like to implement a welcome message for every members added based on their locale. The code is as following:

if (message.Type == ActivityTypes.ConversationUpdate)
{
    // some code...

    if (message.Locale == "en-us")
    {
        var reply = message.CreateReply("Hello world");
    }
    else
    {
        // some code...
    }


    // some code...
}

奇怪的是,即使我在使用bot模拟器和

Strangely, the locale is null even though I've set the locale both when I test it using bot emulator and BotFramework-WebChat. The locale property is working fine when messages is received.

在对话更新活动期间,有什么方法可以获取语言环境?

Is there any way I could get the locale during conversationUpdate activity?

提前谢谢!

推荐答案

一种在第一次输入之前获取用户语言的解决方案是使用Webchat的backchannel功能.这样,我们就可以以隐藏方式将信息推送到我们的机器人,例如提供区域设置或自定义ID.

One solution to get the language of the user before his 1st input is to use the backchannel feature of the Webchat. This allows us to push information to our bot in a hidden way, to provide locale or a custom id for example.

您将在GitHub帐户此处找到该演示.

You will found this demo on GitHub account here.

特别是,这是您的Webchat集成示例,该集成最后通过postActivity将事件发送到bot,这是从Microsoft的Webchat GitHub描述中的示例创建的:

In particular, here is the sample of integration of your webchat sending the event to the bot at the end with a postActivity, created from the samples on Microsoft's Webchat GitHub description:

<!DOCTYPE html>
<html>
<head>
    <link href="https://cdn.botframework.com/botframework-webchat/latest/botchat.css" rel="stylesheet" />
</head>
<body>
    <div id="bot" />
    <script src="https://cdn.botframework.com/botframework-webchat/latest/botchat.js"></script>
    <script>
        // Get parameters from query
        const params = BotChat.queryParams(location.search);

        // Language definition
        var chatLocale = params['locale'] || window.navigator.language;

        // Connection settings
        const botConnectionSettings = new BotChat.DirectLine({
            domain: params['domain'],
            secret: 'YOUR_SECRET',
            webSocket: params['webSocket'] && params['webSocket'] === 'true' // defaults to true
        });

        // Webchat init
        BotChat.App({
            botConnection: botConnectionSettings,
            user: { id: 'userid' },
            bot: { id: 'botid' },
            locale: chatLocale,
            resize: 'detect'
        }, document.getElementById('bot'));

        // Send message to provide language of user
        botConnectionSettings.postActivity({
            type: 'event',
            from: { id: 'userid' },
            locale: chatLocale,
            name: 'localeSelectionEvent',
            value: chatLocale
        }).subscribe(function (id) { console.log('event language "' + chatLocale + '" selection sent'); });
    </script>
</body>
</html>

我添加了一个控制台事件来显示发布的活动.

I added a console event to show the activity posted.

该事件随后被机器人的MessageController接收并处理:

This event is then received by the bot's MessageController and treated:

[BotAuthentication]
public class MessagesController : ApiController
{
    /// <summary>
    /// POST: api/Messages
    /// Receive a message from a user and reply to it
    /// </summary>
    public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
    {
        // DEMO PURPOSE: echo all incoming activities
        Activity reply = activity.CreateReply(Newtonsoft.Json.JsonConvert.SerializeObject(activity, Newtonsoft.Json.Formatting.None));
        var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
        connector.Conversations.SendToConversation(reply);

        // Process each activity
        if (activity.Type == ActivityTypes.Message)
        {
            await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
        }
        // Webchat: getting an "event" activity for our js code
        else if (activity.Type == ActivityTypes.Event && activity.ChannelId == "webchat")
        {
            var receivedEvent = activity.AsEventActivity();

            if ("localeSelectionEvent".Equals(receivedEvent.Name, StringComparison.InvariantCultureIgnoreCase))
            {
                await EchoLocaleAsync(activity, activity.Locale);
            }
        }
        // Sample for emulator, to debug locales
        else if (activity.Type == ActivityTypes.ConversationUpdate && activity.ChannelId == "emulator")
        {
            foreach (var userAdded in activity.MembersAdded)
            {
                if (userAdded.Id == activity.From.Id)
                {
                    await EchoLocaleAsync(activity, "fr-FR");
                }
            }
        }

        var response = Request.CreateResponse(HttpStatusCode.OK);
        return response;
    }

    private async Task EchoLocaleAsync(Activity activity, string inputLocale)
    {
        Activity reply = activity.CreateReply($"User locale is {inputLocale}, you should use this language for further treatment");
        var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
        await connector.Conversations.SendToConversationAsync(reply);
    }
}

插图alrivéedes消息":

Illustration de l'arrivée des messages :

对于说法语的用户,

For French speaking users, here is a more detailed answer on my company's blog

这篇关于如何在对话更新活动中获取语言环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆