您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

自适应对话框中的事件和触发器-参考指南Events and triggers in adaptive dialogs - reference guide

适用于: SDK v4APPLIES TO: SDK v4

有关本主题的介绍,请参阅 自适应对话框概念中的事件和触发器 一文。For an introduction to this topic, see the Events and triggers in adaptive dialogs concept article.

基本触发器Base trigger

OnCondition 触发器是所有触发器派生自的基本触发器。The OnCondition trigger is the base trigger that all triggers derive from. 在自适应对话中定义触发器时,它们定义为 OnCondition 对象的列表,如以下示例中所示:When defining triggers in an adaptive dialog they are defined as a list of OnCondition objects as demonstrated in the following example:

Triggers = new List<OnCondition>()
{
    ...
}

识别器事件触发器Recognizer event triggers

事件原因Event cause 触发器名称Trigger name 基本事件Base event 说明Description
选择意向Choose Intent OnChooseIntent ChooseIntent 当在 CrossTrainedRecognizerSet 的多个识别器中的意向之间检测到歧义时,将运行此触发器。This trigger is run when ambiguity has been detected between intents from multiple recognizers in a CrossTrainedRecognizerSet.
已识别意向Intent recognized OnIntent RecognizedIntent 已识别指定的意向时要执行的操作。Actions to perform when specified intent is recognized.
QnAMatch 意向QnAMatch intent OnQnAMatch RecognizedIntent QnAMakerRecognizer 返回了 QnAMatch 意向时,将运行此触发器。This trigger is run when the QnAMakerRecognizer has returned a QnAMatch intent. 实体 @answer 将具有 QnAMaker 答案。The entity @answer will have the QnAMaker answer.
已识别未知意向Unknown intent recognized OnUnknownIntent UnknownIntent 无法识别用户输入或在任何 OnIntent 触发器中找不到匹配项时要执行的操作。Actions to perform when user input is unrecognized or no match is found in any of the OnIntent triggers. 还可以将此用作根对话中的第一个触发器来代替 OnBeginDialog,在对话首次启动时执行任何所需的任务。You can also use this as your first trigger in your root dialog in place of the OnBeginDialog to preform any needed tasks when the dialog first starts.

提示

使用 OnUnknownIntent 触发器来捕获并响应 "无" 意向。Use the OnUnknownIntent trigger to catch and respond when a "none" intent occurs. 使用 OnIntent 触发器处理 "无" 意向可能会产生意外的结果。Using the OnIntent trigger to handle a "none" intent can produce unexpected results.

识别器事件示例Recognizer event example

下面的示例提供了 OnIntentOnUnknownIntent 触发器的示例,演示如何使用识别器触发器。Examples of OnIntent and OnUnknownIntent triggers are given in the example below to demonstrate the use of the Recognizer triggers.

备注

  • OnIntent 触发器允许处理 recognizedIntent 事件。The OnIntent trigger lets you handle the recognizedIntent event. recognizedIntent事件由识别器引发。The recognizedIntent event is raised by a recognizer. QnA Maker 识别器例外外,所有机器人 Framework SDK 内置识别器在成功标识用户 输入 时都会发出此事件,以便机器人能够做出适当的响应。With the exception of the QnA Maker recognizer, all of the Bot Framework SDK built-in recognizers emit this event when they successfully identify a user input so that your bot can respond appropriately.
  • recognizedIntent 事件未由任何其他触发器捕获和处理时,请使用 OnUnknownIntent 触发器来捕获和响应。Use the OnUnknownIntent trigger to catch and respond when a recognizedIntent event isn't caught and handled by any of the other triggers. 这意味着,任何未经处理的意向 (包括 "none" ) 会使其触发,但仅当对话框没有任何当前正在执行的操作时。This means that any unhandled intent (including "none") can cause it to trigger, but only if there aren't any currently executing actions for the dialog.
// Create the root dialog as an Adaptive dialog.
var rootDialog = new AdaptiveDialog(nameof(AdaptiveDialog));

// Add a regex recognizer
rootDialog.Recognizer = new RegexRecognizer()
{
    Intents = new List<IntentPattern>()
    {
        new IntentPattern()
        {
            Intent = "HelpIntent",
            Pattern = "(?i)help"
        },
        new IntentPattern()
        {
            Intent = "CancelIntent",
            Pattern = "(?i)cancel|never mind"
        }
    }
};

// Create an OnIntent trigger named "helpTrigger" that handles the intent named "HelpIntent".
var helpTrigger = new OnIntent("HelpIntent");

// Create a list of actions to execute when the trigger named "helpTrigger" fires.
var helpActions = new List<Dialog>();
helpActions.Add(new SendActivity("Hello, I'm the samples bot. At the moment, I respond to only help!"));
helpTrigger.Actions = helpActions;

// Add the OnIntent trigger "helpTrigger" to the root dialog
rootDialog.Triggers.Add(helpTrigger);

// Create a trigger to handle the unhandled intent events. The unknown intent trigger fires when a  
// recognizedIntent event raised by the recognizer is not handled by any OnIntent trigger in the dialog.
// Given the RegEx recognizer added to this dialog, this trigger will fire when the user says 'cancel'.
// The RegexRecognizer returned the 'cancel' intent, however, we have no trigger attached to handled it.
// The OnUnknownIntent trigger will also fire when user says 'yo' (or any other word that does not map
// to any intent in the recognizer). When the recognizer parses the user input and does not detect an
// intent, it will return a 'none' intent and since there is no OnIntent trigger to handle  a 'none'
// intent, the unknown intent trigger fires.
var unhandledIntentTrigger = new OnUnknownIntent();
var unhandledIntentActions = new List<Dialog>();
unhandledIntentActions.Add(new SendActivity("Sorry, I did not recognize that"));
unhandledIntentTrigger.Actions = unhandledIntentActions;

// Add the OnUnknownIntent trigger "unhandledIntentTrigger" to the root dialog
rootDialog.Triggers.Add(unhandledIntentTrigger);

对话事件触发器Dialog event triggers

对话触发器处理与对话框 生命周期 相关的对话框特定事件。Dialog triggers handle dialog specific events that are related to the lifecycle of the dialog. Bot Framework SDK 中目前有 6 个对话触发器,它们都派生自 OnDialogEvent 类。There are currently 6 dialog triggers in the Bot Framework SDK and they all derive from the OnDialogEvent class.

提示

这并不像普通中断事件处理程序,在这种情况下,在处理程序的操作完成后子操作将继续运行。These aren't like normal interruption event handlers where the child's actions will continue running after the handler's actions complete. 对于以下所有事件,bot 将运行一组新的操作,并将在完成这些操作后关闭。For all of the events below, the bot will run a new set of actions and will end the turn once those actions have finished.

触发器名称Trigger name 基本事件Base event 说明Description
OnBeginDialog BeginDialog 此对话开始时要执行的操作。Actions to perform when this dialog begins. 若要仅与子对话一起使用,而不是在根对话中使用,请使用 OnUnknownIntent 执行对话初始化活动。For use with child dialogs only, not to be used in your root dialog, In root dialogs, use OnUnknownIntent to perform dialog initialization activities.
OnCancelDialog CancelDialog 使用此事件可以防止由于执行 CancelAllDialogs 操作的子对话而取消当前对话。This event allows you to prevent the current dialog from being cancelled due to a child dialog executing a CancelAllDialogs action.
OnEndOfActions EndOfActions 处理完所有操作和歧义事件后发生此事件。This event occurs once all actions and ambiguity events have been processed.
OnError Error 对话事件发生时要执行的操作 ErrorActions to perform when an Error dialog event occurs. 此事件类似于, OnCancelDialog 因为您要阻止包含此触发器的自适应对话框终止,在这种情况下,由于子对话出现错误。This event is similar to OnCancelDialog in that you are preventing the adaptive dialog that contains this trigger from ending, in this case due to an error in a child dialog.
OnRepromptDialog RepromptDialog 发生 RepromptDialog 事件时要执行的操作。Actions to perform when RepromptDialog event occurs.
OnDialog DialogEvents.VersionChanged

提示

如果使用的是自适应对话框的 声明性 方法,则对话框将定义为 .dialog 用于在运行时创建对话框的文件。If you are using the declarative approach to adaptive dialogs, your dialogs are defined as .dialog files that are used to create your dialogs at run-time. 还可以在运行时修改这些对话框,方法是 .dialog 直接更新文件,然后处理 resourceExplorer.Changed 事件以重新加载对话框。These dialogs can also be modified at run time by updating the .dialog file directly then handling the resourceExplorer.Changed event to reload the dialog. 你还可以 DialogEvents.VersionChanged触发器 中捕获事件,以执行在与用户进行会话的过程中更改对话框时可能导致的任何所需操作。You can also capture the DialogEvents.VersionChanged event in a trigger to take any needed actions that may result from a dialog changing in the middle of a conversation with a user. 有关详细信息,请参阅在自适应对话框中使用声明性资产一文中的文件更改时自动重新加载对话For more information see Auto reload dialogs when file changes in the the Using declarative assets in adaptive dialogs article.

对话框事件示例Dialog event example

此示例演示如何使用 OnBeginDialog 触发器向用户发送欢迎消息。This example demonstrates sending a welcome message to the user, using the OnBeginDialog trigger.

var welcomeDialog = new AdaptiveDialog(nameof(AdaptiveDialog))
{
    Triggers = new List<OnCondition>()
    {
        new OnBeginDialog()
        {
            Actions = new List<Dialog>()
            {
                new SendActivity("Hello world!")
            }
        }
    }
};

活动事件触发器Activity event triggers

通过活动触发器可以将操作与来自客户端的任何传入活动关联,例如,当新用户加入,并且机器人开始新对话时。Activity triggers let you associate actions to any incoming activity from the client such as when a new user joins and the bot begins a new conversation. 有关活动的其他信息,请参阅 Bot Framework Activity 架构Additional information on activities can be found in Bot Framework Activity schema.

所有活动事件都具有 ActivityReceived 的基本事件,并通过其活动类型进行进一步优化。All activity events have a base event of ActivityReceived and are further refined by their activity type. 所有活动触发器派生自的基类是 OnActivityThe Base class that all activity triggers derive from is OnActivity.

事件原因Event cause 活动类型ActivityType 触发器名称Trigger name 说明Description
GreetingGreeting ConversationUpdate OnConversationUpdateActivity conversationUpdate当 bot 或用户加入或离开会话时,要对其执行的操作。Actions to perform on receipt of a conversationUpdate activity, when the bot or a user joins or leaves a conversation.
已结束对话Conversation ended EndOfConversation OnEndOfConversationActivity 接收活动时要执行的操作 endOfConversationActions to perform on receipt of an endOfConversation activity.
已接收事件Event received Event OnEventActivity 接收活动时要执行的操作 eventActions to perform on receipt of an event activity.
提交给人Handover to human Handoff OnHandoffActivity 接收活动时要执行的操作 handOffActions to perform on receipt of a handOff activity.
已调用对话Conversation invoked Invoke OnInvokeActivity 接收活动时要执行的操作 invokeActions to perform on receipt of an invoke activity.
用户正在键入User is typing Typing OnTypingActivity 接收活动时要执行的操作 typingActions to perform on receipt of a typing activity.

活动事件示例Activity event example

OnConversationUpdateActivityOnConversationUpdateActivity

OnConversationUpdateActivity触发器允许处理 活动接收 事件。The OnConversationUpdateActivity trigger lets you handle an activity received event. OnConversationUpdateActivity触发器仅在收到活动时触发 conversationUpdateThe OnConversationUpdateActivity trigger will only fire when the activity received is a conversationUpdate activity.

以下代码片段演示如何创建 OnConversationUpdateActivity 触发器:The following code snippet demonstrates how you can create an OnConversationUpdateActivity trigger:

var myDialog = new AdaptiveDialog(nameof(AdaptiveDialog))
{
    Generator = new TemplateEngineLanguageGenerator(new TemplateEngine().AddFile(Path.Combine(".", "myDialog.lg"))),
    Triggers = new List<OnCondition>() {
        new OnConversationUpdateActivity() {
            Actions = new List<Dialog>() {
                new SendActivity("${Welcome-user()}")
            }
        }
    }
};

消息事件触发器Message event triggers

消息事件触发器允许您对任何消息事件(例如 (MessageUpdate) 或删除) (的消息进行更新 MessageDeletion ,或者当有人 MessageReaction 向消息提供 () 时,某些常见消息反应包括类似、个大笑、惊讶、悲伤和生气的反应 (。Message event triggers allow you to react to any message event such as when a message is updated (MessageUpdate) or deleted (MessageDeletion) or when someone reacts (MessageReaction) to a message (for example, some of the common message reactions include a Like, Heart, Laugh, Surprised, Sad and Angry reactions).

消息事件是一种活动事件,因此,所有消息事件都具有 ActivityReceived 的基本事件,并通过活动类型进行进一步优化。Message events are a type of activity event and, as such, all message events have a base event of ActivityReceived and are further refined by activity type. 所有消息触发器派生自的基类是 OnActivityThe Base class that all message triggers derive from is OnActivity.

事件原因Event cause 活动类型ActivityType 触发器名称Trigger name 说明Description
收到的消息Message received Message OnMessageActivity 收到类型为 MessageReceived 的活动时要执行的操作。Actions to perform on receipt of an activity with type MessageReceived.
已删除消息Message deleted MessageDeletion OnMessageDeleteActivity 收到类型为 MessageDelete 的活动时要执行的操作。Actions to perform on receipt of an activity with type MessageDelete.
消息回应Message reaction MessageReaction OnMessageReactionActivity 收到类型为 MessageReaction 的活动时要执行的操作。Actions to perform on receipt of an activity with type MessageReaction.
已更新消息Message updated MessageUpdate OnMessageUpdateActivity 收到类型为 MessageUpdate 的活动时要执行的操作。Actions to perform on receipt of an activity with type MessageUpdate.

自定义事件触发器Custom event trigger

可以通过将 EmitEvent 操作添加到任何触发器来发出自己的事件,然后可以通过定义自定义事件触发器,在机器人的任何对话中的任何触发器中处理该自定义事件。You can emit your own events by adding the EmitEvent action to any trigger, then you can handle that custom event in any trigger in any dialog in your bot by defining a custom event trigger. 自定义事件触发器是在将 Event 属性设置为与 EmitEvent 的 EventName 属性相同的值时,实际上会成为自定义触发器的 OnDialogEvent 触发器。A custom event trigger is the OnDialogEvent trigger that in effect becomes a custom trigger when you set the Event property to the same value as the EmitEvent's EventName property.

提示

可以通过将 EmitEvent 的 BubbleEvent 属性设置为 true,允许机器人中的其他对话处理自定义事件。You can allow other dialogs in your bot to handle your custom event by setting the EmitEvent's BubbleEvent property to true.

事件原因Event cause 触发器名称Trigger name 基类Base class 说明Description
自定义事件Custom event OnDialogEvent OnCondition 检测到自定义事件时要执行的操作。Actions to perform when a custom event is detected. 使用 " 发出自定义事件 " 操作可引发自定义事件。Use Emit a custom event action to raise a custom event.

自定义事件示例Custom event example

var rootDialog = new AdaptiveDialog(nameof(AdaptiveDialog))
    {
        Generator = new TemplateEngineLanguageGenerator(),
        Triggers = new List<OnCondition>()
        {
            new OnUnknownIntent()
            {
                Actions = new List<Dialog>()
                {
                    new TextInput()
                    {
                        Prompt = new ActivityTemplate("What's your name?"),
                        Property = "user.name",
                        AlwaysPrompt = true,
                        OutputFormat = "toLower(this.value)"
                    },
                    new EmitEvent()
                    {
                        EventName = "contoso.custom",
                        EventValue = "=user.name",
                        BubbleEvent = true,
                    },
                    new SendActivity("Your name is ${user.name}"),
                    new SendActivity("And you are ${$userType}")
                }
            },
            new OnDialogEvent()
            {
                Event = "contoso.custom",

                // You can use conditions (expression) to examine value of the event as part of the trigger selection process.
                Condition = "turn.dialogEvent.value && (substring(turn.dialogEvent.value, 0, 1) == 'v')",
                Actions = new List<Dialog>()
                {
                    new SendActivity("In custom event: '${turn.dialogEvent.name}' with the following value '${turn.dialogEvent.value}'"),
                    new SetProperty()
                    {
                        Property = "$userType",
                        Value = "VIP"
                    }
                }
            },
            new OnDialogEvent()
            {
                Event = "contoso.custom",

                // You can use conditions (expression) to examine value of the event as part of the trigger selection process.
                Condition = "turn.dialogEvent.value && (substring(turn.dialogEvent.value, 0, 1) == 's')",
                Actions = new List<Dialog>()
                {
                    new SendActivity("In custom event: '${turn.dialogEvent.name}' with the following value '${turn.dialogEvent.value}'"),
                    new SetProperty()
                    {
                        Property = "$userType",
                        Value = "Special"
                    }
                }
            },
            new OnDialogEvent()
            {
                Event = "contoso.custom",
                Actions = new List<Dialog>()
                {
                    new SendActivity("In custom event: '${turn.dialogEvent.name}' with the following value '${turn.dialogEvent.value}'"),
                    new SetProperty()
                    {
                        Property = "$userType",
                        Value = "regular customer"
                    }
                }
            }
        }
    };

其他信息Additional Information