【问题标题】:Greeting user upon opening bot打开机器人时问候用户
【发布时间】:2019-07-26 00:39:52
【问题描述】:

我是 Node.JS 和 Microsoft Bot Framework 的初学者。我正在制作一个聊天机器人,我已经弄清楚如何与 LUIS 服务进行通信,但我仍然遇到一个小问题。我尝试了很多不同的东西,我应该注意我正在使用 Azure 中的在线应用服务编辑器。

我不知道如何与用户打招呼,我觉得这应该很容易。通过问候,我的意思是在用户单击链接以打开与我的机器人对话时向用户发送消息。我知道我应该使用 onMembersAdded 命令,但是当我尝试添加它时,我总是搞砸了别的东西。这是我当前的代码:

bot.js

const { ActivityHandler } = require('botbuilder');
const { BotFrameworkAdapter } = require('botbuilder');
const { LuisRecognizer } = require('botbuilder-ai');

class LuisBot {
    constructor(application, luisPredictionOptions) {
        this.luisRecognizer = new LuisRecognizer(application, luisPredictionOptions, true);
        }   
    async onTurn(turnContext) {
        // Make API call to LUIS with turnContext (containing user message)
        try {
            const results = await this.luisRecognizer.recognize(turnContext);

            //console.log(results);
            // Extract top intent from results
            const topIntent = results.luisResult.topScoringIntent;
            switch (topIntent.intent) {
                    case 'Greeting':
                    await turnContext.sendActivity('Hello!');
break;          
                    default:
                    await turnContext.sendActivity('Oops, looks like something went wrong');
            }
        } catch (error) {
        }
    }
}
module.exports.LuisBot = LuisBot;

index.js

const dotenv = require('dotenv');
const path = require('path');
const restify = require('restify');

// Import required bot services.
// See https://aka.ms/bot-services to learn more about the different parts of a bot.
const { BotFrameworkAdapter } = require('botbuilder');

// This bot's main dialog.
// const { EchoBot } = require('./bot');
const { LuisBot } = require('./bot');

// Import required bot configuration.
const ENV_FILE = path.join(__dirname, '.env');
dotenv.config({ path: ENV_FILE });

// Create HTTP server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, () => {
    console.log(`\n${ server.name } listening to ${ server.url }`);
    console.log(`\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator`);
    console.log(`\nTo talk to your bot, open the emulator select "Open Bot"`);
});

// Create adapter.
const adapter = new BotFrameworkAdapter({
    appId: process.env.MicrosoftAppId,
    appPassword: process.env.MicrosoftAppPassword,
    channelService: process.env.ChannelService,
    openIdMetadata: process.env.BotOpenIdMetadata
});

const luisApplication = {
    applicationId: process.env.LuisAppId,
    endpointKey: process.env.LuisAuthoringKey,
    azureRegion: process.env.LuisAzureRegion
};
const luisPredictionOptions = {
    includeAllIntents: true,
    log: true,
    staging: false
};

// Catch-all for errors.
adapter.onTurnError = async (context, error) => {
    // This check writes out errors to console log .vs. app insights.
    console.error(`\n [onTurnError]: ${ error }`);
    // Send a message to the user
    await context.sendActivity(`Oops. Something went wrong!`);
};

// Create the main dialog.
// const bot = new EchoBot();
// Create the main dialog.
const bot = new LuisBot(luisApplication, luisPredictionOptions);

// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
    // console.log(process.env.LuisAppId);
    adapter.processActivity(req, res, async (context) => {
        // Route to main dialog.
        // console.log(process.env.LuisAppId);
        await bot.onTurn(context);
    });
});

我显然是新手,如果这是一个不好的问题,我深表歉意,但我已经尝试了一切。

【问题讨论】:

    标签: node.js azure botframework


    【解决方案1】:

    实现只需要一点代码。请注意,我只显示相关代码。

    首先,将您的问候放在单独的“bot”文件中。在此示例中,我在名为 welcomeCard.json 的文件中定义了一个简单的自适应卡。这是在问候文件welcomeBot.js 中引用的,它扩展了主“bot”文件mainBot.js

    welcomeBot.js

    const { CardFactory } = require('botbuilder');
    const { MainBot } = require('./mainBot');
    const WelcomeCard = require('../resources/json/welcomeCard');
    
    class WelcomeBot extends MainBot {
      constructor(conversationState, userState, dialog, conversationReferences) {
        super(conversationState, userState, dialog, conversationReferences);
    
        this.onMembersAdded(async (context, next) => {
          const membersAdded = context.activity.membersAdded;
          for (let cnt = 0; cnt < membersAdded.length; cnt++) {
            if (membersAdded[cnt].id !== context.activity.recipient.id) {
              const welcomeCard = CardFactory.adaptiveCard(WelcomeCard);
              await context.sendActivity({ attachments: [welcomeCard] });
            }
          }
    
          await next();
        });
      }
    }
    
    module.exports.WelcomeBot = WelcomeBot;
    

    接下来,在index.js 文件中,我引用welcomeBot 文件和我的mainDialog 来实例化机器人。

    index.js

    const { WelcomeBot } = require( './bots/welcomeBot' );
    const { MainDialog } = require( './dialogs/mainDialog' );
    
    [...other code...]
    
    const dialog = new MainDialog( 'MainDialog', userState, conversationState );
    const bot = new WelcomeBot( conversationState, userState, dialog );
    

    应该让您在用户首次连接到机器人时启动并运行问候语渲染。

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 2020-04-21
      • 2021-11-17
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 2020-07-06
      • 1970-01-01
      • 2016-01-17
      • 1970-01-01
      相关资源
      最近更新 更多