通过覆盖 MessageReceived 在 LuisDialog 中自动翻译消息

Auto-translate messages in LuisDialog by overriding MessageReceived

我正在尝试创建一个 LuisDialog,其中来自用户的所有消息都将自动翻译成我的 LUIS 应用可以理解的语言。

为此,我重写了 LuisDialog.MessageReceived() 方法。

我将消息自动翻译成我的语言,但我遇到的问题是如何更新 IAwaitable<IMessageActivity>.Text 的值,以便对话框内基于意图的方法可以透明地访问它。

[Serializable]
class LuisDialogAutoTranslated<T> : LuisDialog<T>
{
    protected override async Task MessageReceived(IDialogContext context, IAwaitable<IMessageActivity> msg)
    {
        var activity = await msg;

        activity.Text = await new CognitiveTranslator().TranslateToCurrentLanguage(activity.Text);

        //????
        //how to replace the value of IMessageActivity.Text
        //inside the IAwaitable msg?
        //????

        await base.MessageReceived(context, msg);
    }
} 

与其覆盖 MessageReceived,我建议您覆盖 GetLuisQueryTextAsync, which basically receives the message and return the text that will be passed to LUIS (see here)。

如果您仍想覆盖 MessageReceived,那么您将使用 Awaitable.FromItem<IMessageActivity>(activity) 创建一个 Awaitable<T>,如下面的代码所示。

var activity = await msg;

activity.Text = await new CognitiveTranslator().TranslateToCurrentLanguage(activity.Text);

msg = Awaitable.FromItem<IMessageActivity>(activity);

await base.MessageReceived(context, msg);