首页 > 解决方案 > 如果输入的字符少于 6 个,则提示用户输入超过 6 个字符

问题描述

我有一个使用 MS Bot 框架版本 3 创建的机器人。如果用户输入的字符少于 6 个(“hi”、“hello”或“help”除外),我想提示用户输入超过 6 个字符字符的响应。你能告诉我处理这个的事件吗?

标签: botframework

解决方案


您可以在两个地方检查活动文本 - 在 OnTurn 处理程序中或在对话框堆栈中作为提示验证。

OnTurn 处理程序选项设置起来相当简单。这将一直通知用户,直到满足条件并适用于输入的每条消息:

async onTurn(turnContext) {
    if (turnContext.activity.type === ActivityTypes.Message) {
        // Create a dialog context object.
        const dc = await this.dialogs.createContext(turnContext);

        if (turnContext.activity.text.length <= 6) {
            await dc.context.sendActivity(`Your message must be longer than 6 characters`);
            [...Other Logic Here...]
        }
    }
    [...]
}

或者,如果您需要在对话框中的特定点进行验证,您将需要以下内容:

首先,扩展 TextPrompt 的类

const { TextPrompt } = require('botbuilder-dialogs');

// This is a custom TextPrompt that requires the input to be between 1 and 50 characters in length.
module.exports.LengthPrompt = class LengthPrompt extends TextPrompt {
    constructor(dialogId) {
        super(dialogId, async (prompt) => {
            console.log(`val: `, prompt.recognized);

            let length = prompt.recognized.value.length;

            if (length < 6) {
                await prompt.context.sendActivity('Validation failed');
                await prompt.context.sendActivity('Please enter a message that has at least 6 characters');
                return false;
            } else if (length >= 6) {
                await prompt.context.sendActivity('Validation succeeded');
                return true;
            }
        });
    }
};

接下来,将以下内容添加到您的 bot.js 文件中:

const { ActivityTypes } = require('botbuilder');
const { DialogSet, WaterfallDialog } = require('botbuilder-dialogs');
const { LengthPrompt } = require('./prompts/lengthPrompt');

const DIALOG_STATE_PROPERTY = 'dialogState';
const START_DIALOG = 'start_dialog';

const LENGTH_PROMPT = 'length_prompt';

class ExampleBot {
    /**
     *
     * @param {conversationState} conversationState A ConversationState object used to store the dialog state.
     * @param {userState} userState A UserState object used to store values specific to the user.
     */
    constructor(conversationState, userState) {
        this.conversationState = conversationState;
        this.userState = userState;

        this.dialogState = this.conversationState.createProperty(DIALOG_STATE_PROPERTY);

        this.dialogs = new DialogSet(this.dialogState);

        // Add prompts that will be used by the main dialogs.
        this.dialogs
            .add(new LengthPrompt(LENGTH_PROMPT));

        this.dialogs.add(new WaterfallDialog(START_DIALOG, [
            this.colorStep.bind(this)
        ]));
    }

    // This step in the dialog prompts the user for their name.
    async colorStep(step) {
        await step.prompt(LENGTH_PROMPT, `What is a color you like?`,
            {
                retryPrompt: 'What is a color you like?'
            }
        );
    }

    /**
     *
     * @param {TurnContext} turnContext A TurnContext object that will be interpreted and acted upon by the bot.
     */
    async onTurn(turnContext) {
        if (turnContext.activity.type === ActivityTypes.Message) {
            // Create a dialog context object.
            const dc = await this.dialogs.createContext(turnContext);

            const utterance = (turnContext.activity.text || '').trim().toLowerCase();
            if (utterance === 'cancel') {
                if (dc.activeDialog) {
                    await dc.cancelAllDialogs();
                    await dc.context.sendActivity(`Ok... canceled.`);
                } else {
                    await dc.context.sendActivity(`Nothing to cancel.`);
                }
            }

            // If the bot has not yet responded, continue processing the current dialog.
            await dc.continueDialog();

            // Start the sample dialog in response to any other input.
            if (!turnContext.responded) {
                await dc.beginDialog(START_DIALOG);
            }
        }
        // Save changes to the user state.
        await this.userState.saveChanges(turnContext);

        // End this turn by saving changes to the conversation state.
        await this.conversationState.saveChanges(turnContext);
    }
}

module.exports.ExampleBot = ExampleBot;

希望有帮助!


推荐阅读