Microsoft Bot Framework (v4): как сделать список карт героев в качестве быстрого выбора - PullRequest
0 голосов
/ 01 июля 2019

Я пытаюсь создать диалоговое окно со списком карт героев в качестве варианта.

Я создал функцию, которая будет возвращать список карт героев и использовать его в качестве диалогового окна.

Как мне этого добиться? или есть лучший способ реализовать это. Примечание: мне нужно поместить это в диалоговое окно, потому что мне нужно реализовать последовательный диалог. Я также поместил список карт героев в отдельную функцию, потому что буду использовать его в другом диалоговом окне.

async selectProduct(stepContext){
    return await stepContext.prompt(CHOICE_PROMPT, {
        prompt: 'Select Product:',
        choices: this.productChoices()
    });
}



productChoices(){        
    const productSeriesOptions = [
        CardFactory.heroCard(
        'Title 1',
        CardFactory.images(['image URL 1']),
        CardFactory.actions([
            {
                type: ActionTypes.ImBack,
                title: 'Title 1',
                value: 'Value 1'
            }
        ])
        ),

        CardFactory.heroCard(
        'Title 2',
        CardFactory.images(['image URL 2']),
        CardFactory.actions([
            {
                type: ActionTypes.ImBack,
                title: 'Title 2',
                value: 'Value 2'
            }
        ])
        )
    ];

    return productSeriesOptions;
}   

1 Ответ

1 голос
/ 03 июля 2019

Я включил пример диалога, который демонстрирует пользователю представление карусели карт HeroCard (ниже).В HeroCard есть одна кнопка, которая при нажатии приводит к выполнению следующего шага «Водопад».

Первоначально я извлек это диалоговое окно из примера использования карт.Поэтому, если вы хотите запустить его, вы можете заменить mainDialog.js в этом проекте и запустить его в эмуляторе.

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

const { ActionTypes, AttachmentLayoutTypes, CardFactory } = require('botbuilder');
const { ChoicePrompt, ComponentDialog, DialogSet, DialogTurnStatus, WaterfallDialog, ChoiceFactory } = require('botbuilder-dialogs');

const MAIN_WATERFALL_DIALOG = 'mainWaterfallDialog';

class MainDialog extends ComponentDialog {
    constructor() {
        super('MainDialog');

        // Define the main dialog and its related components.
        this.addDialog(new WaterfallDialog(MAIN_WATERFALL_DIALOG, [
            this.showProductChoicesStep.bind(this),
            this.showCardSelectionStep.bind(this)
        ]));

        // The initial child Dialog to run.
        this.initialDialogId = MAIN_WATERFALL_DIALOG;
    }

    /**
     * The run method handles the incoming activity (in the form of a TurnContext) and passes it through the dialog system.
     * If no dialog is active, it will start the default dialog.
     * @param {*} turnContext
     * @param {*} accessor
     */
    async run(turnContext, accessor) {
        const dialogSet = new DialogSet(accessor);
        dialogSet.add(this);

        const dialogContext = await dialogSet.createContext(turnContext);
        const results = await dialogContext.continueDialog();
        if (results.status === DialogTurnStatus.empty) {
            await dialogContext.beginDialog(this.id);
        }
    }

    /**
     * Send a carousel of HeroCards for the user to pick from.
     * @param {WaterfallStepContext} stepContext
     */
    async showProductChoicesStep(stepContext) {
        console.log('MainDialog.showProductChoicesStep');

        await stepContext.context.sendActivity({
            attachments: this.productChoices(),
            attachmentLayout: AttachmentLayoutTypes.Carousel
        });
        return { status: DialogTurnStatus.waiting };
    }

    async showCardSelectionStep(stepContext) {
        console.log('MainDialog.showCardSelectionStep');

        await stepContext.context.sendActivity('You picked ' + stepContext.context.activity.value);

        // Give the user instructions about what to do next
        await stepContext.context.sendActivity('Type anything to see another card.');

        return await stepContext.endDialog();
    }

    // ======================================
    // Helper functions used to create cards.
    // ======================================
    productChoices(){
        const productSeriesOptions = [
            CardFactory.heroCard(
            'Product 1',
            CardFactory.images(['https://sec.ch9.ms/ch9/7ff5/e07cfef0-aa3b-40bb-9baa-7c9ef8ff7ff5/buildreactionbotframework_960.jpg']),
            CardFactory.actions([
                {
                    type: 'messageBack',
                    title: 'Pick Me',
                    value: 'product1'
                }
            ])
            ),

            CardFactory.heroCard(
            'Product 2',
            CardFactory.images(['https://sec.ch9.ms/ch9/7ff5/e07cfef0-aa3b-40bb-9baa-7c9ef8ff7ff5/buildreactionbotframework_960.jpg']),
            CardFactory.actions([
                {
                    type: 'messageBack',
                    title: 'Pick Me',
                    value: 'product2'
                }
            ])
            ),

            CardFactory.heroCard(
                'Product 3',
                CardFactory.images(['https://sec.ch9.ms/ch9/7ff5/e07cfef0-aa3b-40bb-9baa-7c9ef8ff7ff5/buildreactionbotframework_960.jpg']),
                CardFactory.actions([
                    {
                        type: 'messageBack',
                        title: 'Pick Me',
                        value: 'product3'
                    }
                ])
                ),

            CardFactory.heroCard(
                'Product 4',
                CardFactory.images(['https://sec.ch9.ms/ch9/7ff5/e07cfef0-aa3b-40bb-9baa-7c9ef8ff7ff5/buildreactionbotframework_960.jpg']),
                CardFactory.actions([
                    {
                        type: 'messageBack',
                        title: 'Pick Me',
                        value: 'product4'
                    }
                ])
            )

        ];

        return productSeriesOptions;
    }
}

module.exports.MainDialog = MainDialog;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...