Развертывание фреймворка Botkit до azure и тестирование в веб-чате возвращает 502 - PullRequest
1 голос
/ 17 марта 2020

Для моей стажировки я создаю чат-бота. Я создал бота, используя botkit framework (yo botkit), и дошел до того, что использовал его в клиенте ms Teams. Но только используя мою настройку localhost + ngrok. когда я хочу использовать https: // {myproject} .azurewebsites.net / api / messages после развертывания, я получаю сообщение об ошибке 502.

Чтобы попытаться, действительно ли мое развертывание прошло нормально, я создал другой проект, используя "ботобилер" без фреймворка для боткитов. Следуя тем же шагам, я развернул его в группе fre sh. На этот раз с помощью https: // {myproject} .azurewebsites.net / api / messages URL работал. (стандартный эхо-бот)

После этого я скопировал мои файлы ботов из моего первого проекта в новый и заменил мой индекс. js из моего стандартного проекта бодибилдера на мой файл бота. js из моего Botkit Framework Project.

Я просто использовал стандартный пакет botbuilder -> index. js file и botkit -> bot. js file + в моем пакете. json Я изменил основной файл и сценарии на укажите на бот. js вместо индекса. js. После развертывания он снова дал мне 502.

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');

// 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.
// See https://aka.ms/about-bot-adapter to learn more about how bots work.
const adapter = new BotFrameworkAdapter({
    appId: process.env.MicrosoftAppId,
    appPassword: process.env.MicrosoftAppPassword
});

// Catch-all for errors.
const onTurnErrorHandler = async (context, error) => {
    // This check writes out errors to console log .vs. app insights.
    // NOTE: In production environment, you should consider logging this to Azure
    //       application insights.
    console.error(`\n [onTurnError] unhandled error: ${ error }`);

    // Send a trace activity, which will be displayed in Bot Framework Emulator
    await context.sendTraceActivity(
        'OnTurnError Trace',
        `${ error }`,
        'https://www.botframework.com/schemas/error',
        'TurnError'
    );

    // Send a message to the user
    await context.sendActivity('The bot encountered an error or bug.');
    await context.sendActivity('To continue to run this bot, please fix the bot source code.');
};

// Set the onTurnError for the singleton BotFrameworkAdapter.
adapter.onTurnError = onTurnErrorHandler;

// Create the main dialog.
const myBot = new EchoBot();

// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
    adapter.processActivity(req, res, async (context) => {
        // Route to main dialog.
        await myBot.run(context);
    });
});

// Listen for Upgrade requests for Streaming.
server.on('upgrade', (req, socket, head) => {
    // Create an adapter scoped to this WebSocket connection to allow storing session data.
    const streamingAdapter = new BotFrameworkAdapter({
        appId: process.env.MicrosoftAppId,
        appPassword: process.env.MicrosoftAppPassword
    });
    // Set onTurnError for the BotFrameworkAdapter created for each connection.
    streamingAdapter.onTurnError = onTurnErrorHandler;

    streamingAdapter.useWebSocket(req, socket, head, async (context) => {
        // After connecting via WebSocket, run this logic for every request sent over
        // the WebSocket connection.
        await myBot.run(context);
    });
});

бот. js

const { Botkit } = require('botkit');
const { BotkitCMSHelper } = require('botkit-plugin-cms');

// Import a platform-specific adapter for botframework.

const { MongoDbStorage } = require('botbuilder-storage-mongodb');

// Load process.env values from .env file
require('dotenv').config();

let storage = null;
if (process.env.MONGO_URI) {
    storage = mongoStorage = new MongoDbStorage({
        url : process.env.MONGO_URI,
    });
}


const controller = new Botkit({
    webhook_uri: '/api/messages',

    adapterConfig: {
        appId: process.env.APP_ID,
        appPassword: process.env.APP_PASSWORD,
    },

    storage
});

if (process.env.CMS_URI) {
    controller.usePlugin(new BotkitCMSHelper({
        uri: process.env.CMS_URI,
        token: process.env.CMS_TOKEN,
    }));
}

// Once the bot has booted up its internal services, you can use them to do stuff.
controller.ready(() => {

    // load traditional developer-created local custom feature modules
    controller.loadModules(__dirname + '/features');

    /* catch-all that uses the CMS to trigger dialogs */
    if (controller.plugins.cms) {
        controller.on('message,direct_message', async (bot, message) => {
            let results = false;
            results = await controller.plugins.cms.testTrigger(bot, message);

            if (results !== false) {
                // do not continue middleware!
                return false;
            }
        });
    }

});



controller.webserver.get('/', (req, res) => {

    res.send(`This app is running Botkit ${ controller.version }.`);

});

упаковка. json

{
    "name": "my-chat-bot",
    "version": "1.0.0",
    "description": "Demonstrate the core capabilities of the Microsoft Bot Framework",
    "author": "Generated using Microsoft Bot Builder Yeoman generator v4.7.0",
    "license": "MIT",
    "main": "bot.js",
    "scripts": {
        "start": "node ./bot.js",
        "watch": "nodemon ./bot.js",
        "lint": "eslint .",
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "repository": {
        "type": "git",
        "url": "https://github.com"
    },
    "dependencies": {
        "botbuilder": "~4.7.0",
        "dotenv": "^8.2.0",
        "restify": "~8.4.0",
        "botbuilder-storage-mongodb": "^0.9.5",
        "botkit": "^4.6.2",
        "botkit-plugin-cms": "^1.0.3",
        "firebase-admin": "^8.9.2",
        "jira-client": "^6.15.0",
        "request": "^2.88.2"
    },
    "devDependencies": {
        "eslint": "^6.6.0",
        "eslint-config-standard": "^14.1.0",
        "eslint-plugin-import": "^2.18.2",
        "eslint-plugin-node": "^10.0.0",
        "eslint-plugin-promise": "^4.2.1",
        "eslint-plugin-standard": "^4.0.1",
        "nodemon": "~1.19.4"
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...