Search code examples
node.jsfirebasegoogle-cloud-functionsbotframework

Deploying microsoft bots nodejs to firebase functions


I have developed a simple bot using microsoft bot framework with nodejs. the code is just two files like below.

I saw on google firebase function docs https://firebase.google.com/docs/functions/http-events#using_existing_express_apps

it seems i can simply deploy my ms bot nodejs to firebase. question is how exactly should i do it .

app.js

'use strict';

var express = require('express');
var app = express();

// Adding a bot to our app
var bot = require('./bot');
bot.setup(app);

// Adding a messaging extension to our app
var messagingExtension = require('./messaging-extension');
messagingExtension.setup();

// Deciding which port to use
var port = process.env.PORT || 3333;

// Start our nodejs app
app.listen(port, function() {
    console.log(`App started listening on port ${port}`);
});

bot.js

'use strict';

module.exports.setup = function(app) {
    var builder = require('botbuilder');
    var teams = require('botbuilder-teams');
    var config = require('config');

    if (!config.has("bot.appId")) {
        process.env.NODE_CONFIG_DIR = "../config";
        delete require.cache[require.resolve('config')];
        config = require('config');
    }

    // Create a connector to handle the conversations
    var connector = new teams.TeamsChatConnector({
       appId: config.get("bot.appId"),
       appPassword: config.get("bot.appPassword")
    });

    var inMemoryBotStorage = new builder.MemoryBotStorage();

    var bot = new builder.UniversalBot(connector, async function(session) {

        session.send("Hello world");  

    }).set('storage', inMemoryBotStorage);

    // Setup an endpoint on the router for the bot to listen.
    // NOTE: This endpoint cannot be changed and must be api/messages
    app.post('/api/messages', connector.listen());

    // Export the connector for any downstream integration - e.g. registering a messaging extension
    module.exports.connector = connector;
};


Solution

  • I got the echo bot sample to work as a Firebase function. The files from the sample should all go in your functions folder with index.js, bot.js, and .env being the important ones. I made some modifications to index.js so that it uses express and not restify, though it's unclear if that's really necessary. My final index.js looks like this (note the use of the firebase-functions package):

    const functions = require('firebase-functions');
    const dotenv = require('dotenv');
    const path = require('path');
    const express = require('express');
    
    // 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 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.
    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();
    
    // Listen for incoming requests.    
    const app = express();
    app.post('/api/messages', (req, res) => {
        adapter.processActivity(req, res, async (context) => {
            // Route to main dialog.
            await bot.run(context);
        });
    });
    
    // Expose Express API as a single Cloud Function:
    exports.bot = functions.https.onRequest(app);
    

    Your bot's Microsoft app ID and password will need to be in the .env file because they're used to authenticate requests to and from Microsoft Teams. In order to do this, the bot must make requests to an external token server which is naturally not a part of Google. You'll need a paid plan in order for your function to call an external API like that, as you can see here: Use firebase cloud function to send POST request to non-google server

    With a free plan, you can still test the function locally with firebase emulators:start. However, it sounds like you already have a paid plan so I believe this shouldn't be a problem for you. Whether running your bot locally or deployed, your endpoint should end with /bot/api/messages (if you use "bot" as your function name like I have). Once you deploy your bot, you can use the deployed endpoint in the settings blade of your bot resource in Azure.