1

For my internship I am making a chatbot. I created a bot using botkit framework (yo botkit) and got as far as using it in the ms Teams client. But only using my localhost + ngrok setup. when I want to use https://{myproject}.azurewebsites.net/api/messages after deployment I get a 502 error message.

To try if I actually did my deployment okay, I made another project using "yo botbuilder" without botkit framework. Following the same steps I deployed it to a fresh Group. This time using the https://{myproject}.azurewebsites.net/api/messages url worked. (standard echo bot)

After that, I copied my bot files from my first project into my new one and replaced my index.js from my standard botbuilder project with my bot.js file from my botkit framework project.

I just used the standard botbuilder -> index.js file and botkit -> bot.js file + in my package.json I changed the main and the scripts to point to bot.js instead of index.js. After deploying, it just gave me my 502 again.

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

bot.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 }.`);

});

package.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"
    }
}
danronmoon
  • 3,814
  • 5
  • 34
  • 56
gijs
  • 11
  • 3
  • First, are you actually running an instance of [Botkit CMS](https://github.com/howdyai/botkit-cms#botkit-cms)? Your code kinda suggests you are, but you didn't mention it in your post. Also, once deployed, can the bot reach the CMS. Is it also deployed somewhere? Second, the Botkit class specifies [here](https://github.com/howdyai/botkit/blob/0d73c284a44e8ef6ade0ca8be6aaa2ac00c1eaec/packages/botkit/src/core.ts#L597) that you need to call `addDep()` and `completeDep()` first otherwise the `controller.ready()` function will not fire. – Steven Kanberg Mar 18 '20 at 04:59
  • I am not using a botkit cms instance, the helper is automatically added when you generate a botkit project with 'yo botkit'. And with the dependencies, why would it run in the bot framework emulator and not once it is deployed? shouldn't the dependencies be loaded even when using the emulator? – gijs Mar 18 '20 at 08:09
  • @gijs, were you ever able to get this combination working? If so, please share your experience (I'm also trying to answer myself questions about a similar integration scenario, with my bot running instead on the AWS cloud though). – pgoldweic Dec 09 '21 at 19:08
  • @pgoldweic, I wasn’t.. since I couldn’t figure it out, I switched to the bot framework from Microsoft and ran it on a dedicated server at my internship. Time was of essence and thus I hadn’t too much time to look into the problem. Sorry for not being able to help more, and god luck – gijs Dec 10 '21 at 20:12
  • Thanks @gijs for your reply – pgoldweic Dec 13 '21 at 15:57

0 Answers0