>

NodeJ 용 Microsoft Bot Builder (SDK v3)의 공식 빠른 시작을 따르고 있습니다 : Node.js 용 Bot Builder SDK로 봇 만들기

1-새 프로젝트를 만들었습니다

npm init

2-그런 다음

npm install --save botbuilder@3.13.1

3-그런 다음 "app.js"라는 새 파일을 만들었습니다

var builder = require('botbuilder');
var connector = new builder.ConsoleConnector().listen();
var bot = new builder.UniversalBot(connector, function (session) {
session.send("You said: %s", session.message.text);
});

그러나 pyzwyz를 실행할 때  다음과 같은 오류가 발생합니다.

node app.js

var connector=builder.ConsoleConnector().listen();
TypeError: Cannot read property 'listen' of undefined


  • 답변 # 1

    봇에 저장 옵션을 할당하지 않았습니다. 가장 간단한 옵션 (개발 전용)은 메모리 저장소에서 사용하는 것입니다. 코드는 다음과 같아야합니다 :

    var builder = require('botbuilder');
    // Bot Storage: Here we register the state storage for your bot. 
    // Default store: volatile in-memory store - Only for prototyping!
    var inMemoryStorage = new builder.MemoryBotStorage();
    var connector = new builder.ConsoleConnector().listen();
    var bot = new builder.UniversalBot(connector, function(session) {
        session.send("You said: %s", session.message.text);
    }).set('storage', inMemoryStorage); // Register in memory storage
    
    
    

    즉, v3 SDK는 가까운 시일 내에 폐기 될 예정입니다. 대신 v4 Node SDK를 사용하여 개발을 시작하는 것이 좋습니다. 시작하려면 여기에서 문서를 참조하고 여기에서 샘플 코드를 검토하십시오.

    간단히 v4에서는 index.js, bot.js 및 consoleAdapter.js의 세 파일을 사용합니다.

    index.js 파일은 본질적으로 서버, API 등을 빌드합니다.

    const path = require('path');
    const {
        ConsoleAdapter
    } = require('./consoleAdapter');
    // load environment variables from .env file.
    const ENV_FILE = path.join(__dirname, '.env');
    require('dotenv').config({
        path: ENV_FILE
    });
    // Create the bot adapter, which is responsible for sending and receiving messages.
    // We are using the ConsoleAdapter, which enables a bot you can chat with from within your terminal window.
    const adapter = new ConsoleAdapter();
    // Import our bot class.
    const {
        EchoBot
    } = require('./bot');
    const bot = new EchoBot();
    // A call to adapter.listen tells the adapter to start listening for incoming messages and events, known as "activities."
    // Activities are received as TurnContext objects by the handler function.
    adapter.listen(async(context) => {
        bot.onTurn(context);
    });
    // Emit a startup message with some instructions.
    console.log('> Console EchoBot is online. I will repeat any message you send me!');
    console.log('> Say "quit" to end.');
    console.log(''); // Leave a blank line after instructions.
    
    

    bot.js 파일은 일반적으로 봇의 on [ActivityType] 작업 (예 : onMessage ())을 처리합니다. 더 복잡한 봇에서는 대화 상자가 자체 파일로 추정됩니다.

    class EchoBot {
        async onTurn(context) {
            // Check to see if this activity is an incoming message.
            // (It could theoretically be another type of activity.)
            if(context.activity.type === 'message' && context.activity.text) {
                // Check to see if the user sent a simple "quit" message.
                if(context.activity.text.toLowerCase() === 'quit') {
                    // Send a reply.
                    context.sendActivity(`Bye!`);
                    process.exit();
                } else {
                    // Echo the message text back to the user.
                    return context.sendActivity(`I heard you say "${ context.activity.text }"`);
                }
            }
        }
    }
    module.exports.EchoBot = EchoBot;
    
    

    마지막으로 consoleAdapter.js 파일은 콘솔 활동을 캡처하여 봇으로 변환하는 작업입니다.

    'use strict';
    var __importStar = (this && this.__importStar) || function(mod) {
        if(mod && mod.__esModule) return mod;
        var result = {};
        if(mod != null)
            for(var k in mod)
                if(Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
        result['default'] = mod;
        return result;
    };
    Object.defineProperty(exports, '__esModule', {
        value: true
    });
    const botbuilderCore = require('botbuilder-core');
    const readline = __importStar(require('readline'));
    const console = require('console');
    /**
     * Lets a user communicate with a bot from a console window.
     *
     */
    class ConsoleAdapter extends botbuilderCore.BotAdapter {
        /**
         * Creates a new ConsoleAdapter instance.
         * @param reference (Optional) reference used to customize the address information of activities sent from the adapter.
         */
        constructor(reference) {
                super();
                this.nextId = 0;
                this.reference = Object.assign({
                    channelId: 'console',
                    user: {
                        id: 'user',
                        name: 'User1'
                    },
                    bot: {
                        id: 'bot',
                        name: 'Bot'
                    },
                    conversation: {
                        id: 'convo1',
                        name: '',
                        isGroup: false
                    },
                    serviceUrl: ''
                }, reference);
            }
            /**
             * Begins listening to console input. A function will be returned that can be used to stop the
             * bot listening and therefore end the process.
             *
             * @param logic Function which will be called each time a message is input by the user.
             */
        listen(logic) {
                const rl = this.createInterface({
                    input: process.stdin,
                    output: process.stdout,
                    terminal: false
                });
                rl.on('line', (line) => {
                    // Initialize activity
                    const activity = botbuilderCore.TurnContext.applyConversationReference({
                        type: botbuilderCore.ActivityTypes.Message,
                        id: (this.nextId++).toString(),
                        timestamp: new Date(),
                        text: line
                    }, this.reference, true);
                    // Create context and run middleware pipe
                    const context = new botbuilderCore.TurnContext(this, activity);
                    this.runMiddleware(context, logic)
                        .catch((err) => {
                            this.printError(err.toString());
                        });
                });
                return() => {
                    rl.close();
                };
            }
            /**
             * Lets a bot proactively message the user.
             *
             * @param reference A `ConversationReference` saved during a previous message from a user.  This can be calculated for any incoming activity using `TurnContext.getConversationReference(context.activity)`.
             * @param logic A function handler that will be called to perform the bots logic after the the adapters middleware has been run.
             */
        continueConversation(reference, logic) {
                // Create context and run middleware pipe
                const activity = botbuilderCore.TurnContext.applyConversationReference({}, reference, true);
                const context = new botbuilderCore.TurnContext(this, activity);
                return this.runMiddleware(context, logic)
                    .catch((err) => {
                        this.printError(err.toString());
                    });
            }
            /**
             * Logs a set of activities to the console.
             *
             * @param context Context for the current turn of conversation with the user.
             * @param activities List of activities to send.
             */
        sendActivities(context, activities) {
                const that = this;
                // tslint:disable-next-line:promise-must-complete
                return new Promise((resolve, reject) => {
                    const responses = [];
                    function next(i) {
                        if(i < activities.length) {
                            responses.push({});
                            const a = activities[i];
                            switch(a.type) {
                                case 'delay':
                                    setTimeout(() => next(i + 1), a.value);
                                    break;
                                case botbuilderCore.ActivityTypes.Message:
                                    if(a.attachments && a.attachments.length > 0) {
                                        const append = a.attachments.length === 1 ?
                                            `(1 attachment)` : `(${ a.attachments.length } attachments)`;
                                        that.print(`${ a.text } ${ append }`);
                                    } else {
                                        that.print(a.text || '');
                                    }
                                    next(i + 1);
                                    break;
                                default:
                                    that.print(`[${ a.type }]`);
                                    next(i + 1);
                                    break;
                            }
                        } else {
                            resolve(responses);
                        }
                    }
                    next(0);
                });
            }
            /**
             * Not supported for the ConsoleAdapter.  Calling this method or `TurnContext.updateActivity()`
             * will result an error being returned.
             */
        updateActivity(context, activity) {
                return Promise.reject(new Error(`ConsoleAdapter.updateActivity(): not supported.`));
            }
            /**
             * Not supported for the ConsoleAdapter.  Calling this method or `TurnContext.deleteActivity()`
             * will result an error being returned.
             */
        deleteActivity(context, reference) {
                return Promise.reject(new Error(`ConsoleAdapter.deleteActivity(): not supported.`));
            }
            /**
             * Allows for mocking of the console interface in unit tests.
             * @param options Console interface options.
             */
        createInterface(options) {
                return readline.createInterface(options);
            }
            /**
             * Logs text to the console.
             * @param line Text to print.
             */
        print(line) {
                console.log(line);
            }
            /**
             * Logs an error to the console.
             * @param line Error text to print.
             */
        printError(line) {
            console.error(line);
        }
    }
    exports.ConsoleAdapter = ConsoleAdapter;
    
    

    위 코드는 Botbuilder-Samples 저장소의 01.console-echo 샘플에서 가져온 것입니다. 인라인 주석을 제거했습니다. 전체 코드/파일 및 관련 설명은 프로젝트를 참조하십시오.

    도움을 기원합니다!

관련 자료

  • 이전 node.js - Knex 트랜잭션 쿼리 및 Postgres 외래 키 제약 조건
  • 다음 javascript - onclick을 호출 한 요소 삭제