How to use botbuilder - 10 common examples

To help you get started, we’ve selected a few botbuilder examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sebsylvester / reminder-bot / test / newReminder.js View on Github external
it('should call Reminder.create to save a reminder to MongoDB (1)', function (done) {
        const connector = new builder.ConsoleConnector();
        const bot = new builder.UniversalBot(connector);
        const args = {
            reminder: { type: 'reminder', entity: 'make coffee' },
            datetime: { rawEntity: { type: 'value', value: '2016-11-28T15:00:00.000Z'}},
            message: 'Remind me to make coffee at 3pm'
        };
        const normalizedDatetime = '2016-11-28T14:00:00.000Z';

        // Create a stub on the Reminder model
        sinon.stub(Reminder, 'create').callsFake(reminder => {
            expect(reminder.user_address).to.be.an('object');
            expect(reminder.value).to.equal(args.reminder.entity);
            expect(reminder.expiration).to.deep.equal(new Date(normalizedDatetime));
            Reminder.create.restore();
            done();
        });
github microsoftly / BotTester / test / ava / BotTesterFailure.ava.spec.ts View on Github external
setupMultiUserAddressTest(bot);

    const askForUser1Name = new Message()
    .text('What is my name?')
    .address(defaultAddress)
    .toMessage();

    const address = {
        user: {
            id: user2Address.user.id
        }
    } as IAddress;

    // partial addresses work as well (i.e. if you only want to check one field such as userId)
    const expectedPartialAddress = new Message()
        .address(address)
        .toMessage();

    return t.throws(new BotTester(bot, getTestOptions(t))
        .sendMessageToBot(askForUser1Name, expectedPartialAddress)
        .runTest()
    );
});
github microsoft / BotBuilder-Samples / generators / generator-botbuilder / generators / app / templates / echo / index.ts View on Github external
try {
    botConfig = BotConfiguration.loadSync(BOT_FILE, process.env.botFileSecret);
} catch (err) {
    console.error(`\nError reading bot file. Please ensure you have valid botFilePath and botFileSecret set for your environment.`);
    console.error(`\n - The botFileSecret is available under appsettings for your Azure Bot Service bot.`);
    console.error(`\n - If you are running this bot locally, consider adding a .env file with botFilePath and botFileSecret.`);
    console.error(`\n - See https://aka.ms/about-bot-file to learn more about .bot file its use and bot configuration.\n\n`);
    process.exit();
}

// Get bot endpoint configuration by service name
const endpointConfig = botConfig.findServiceByNameOrId(BOT_CONFIGURATION) as IEndpointService;

// Create adapter.
// See https://aka.ms/about-bot-adapter to learn more about .bot file its use and bot configuration.
const adapter = new BotFrameworkAdapter({
    appId: endpointConfig.appId || process.env.microsoftAppID,
    appPassword: endpointConfig.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 myBot = new MyBot();

// Listen for incoming requests.
github microsoft / botframework-solutions / templates / Enterprise-Template / src / typescript / src / index.ts View on Github external
const STORAGE_CONFIGURATION = process.env.STORAGE_NAME || ""; // this is the name of the cosmos DB configuration in your .bot file
const cosmosConfig: ICosmosDBService = botConfig.findServiceByNameOrId(STORAGE_CONFIGURATION) as ICosmosDBService;
if (!cosmosConfig) {
    console.log("Please configure your CosmosDB connection in your .bot file.");
    process.exit(BOT_CONFIGURATION_ERROR);
}
const storage = new CosmosDbStorage({
    authKey: cosmosConfig.key,
    collectionId: cosmosConfig.collection,
    databaseId: cosmosConfig.database,
    serviceEndpoint: cosmosConfig.endpoint,
});

// create conversation and user state with in-memory storage provider.
const conversationState = new ConversationState(storage);
const userState = new UserState(storage);

// Use the AutoSaveStateMiddleware middleware to automatically read and write conversation and user state.
// CONSIDER:  if only using userState, then switch to adapter.use(userState);
adapter.use(new AutoSaveStateMiddleware(conversationState, userState));

// Transcript Middleware (saves conversation history in a standard format)
const AzureBlobTranscriptStore = require("botbuilder-azure").AzureBlobTranscriptStore;
const BLOB_CONFIGURATION = process.env.BLOB_NAME || ""; // this is the name of the BlobStorage configuration in your .bot file
const blobStorageConfig: IBlobStorageService = botConfig.findServiceByNameOrId(BLOB_CONFIGURATION) as IBlobStorageService;
if (!blobStorageConfig) {
    console.log("Please configure your Blob storage connection in your .bot file.");
    process.exit(BOT_CONFIGURATION_ERROR);
}
const blobStorage = new BlobStorageService(blobStorageConfig);
const transcriptStore = new AzureBlobTranscriptStore({
    containerName: blobStorage.container,
github microsoft / BotBuilder-Samples / samples / javascript_nodejs / 02.echobot / index.js View on Github external
// 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.
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.
github microsoft / botbuilder-js / samples / 08. sendChart / src / index.ts View on Github external
import * as restify from 'restify';
import { BotFrameworkAdapter, MemoryStorage } from 'botbuilder';
import { AdaptiveDialog, DefaultRule, SetProperty, SendChart, ChartType } from 'botbuilder-dialogs-adaptive';
import { DialogManager } from 'botbuilder-dialogs';

// 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 echobot.bot file in the Emulator.`);
});

// Create adapter.
// See https://aka.ms/about-bot-adapter to learn more about .bot file its use and bot configuration.
const adapter = new BotFrameworkAdapter({
    appId: process.env.microsoftAppID,
    appPassword: process.env.microsoftAppPassword,
});

// Create bots DialogManager and bind to state storage
const bot = new DialogManager();
bot.storage = new MemoryStorage();

// Listen for incoming activities.
server.post('/api/messages', (req, res) => {
    adapter.processActivity(req, res, async (context) => {
        // Route activity to bot.
        await bot.onTurn(context);
    });
});
github microsoft / botbuilder-js / samples / dialogs / alarmbot-ts / lib / app.js View on Github external
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const botbuilder_1 = require("botbuilder");
const restify = require("restify");
const bot_1 = require("./bot");
// Create server
let server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
    console.log(`${server.name} listening to ${server.url}`);
});
// Create adapter
const adapter = new botbuilder_1.BotFrameworkAdapter({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
});
// Add state middleware
const storage = new botbuilder_1.MemoryStorage();
const convoState = new botbuilder_1.ConversationState(storage);
const userState = new botbuilder_1.UserState(storage);
adapter.use(new botbuilder_1.BotStateSet(convoState, userState));
// Create bot object containing logic
const bot = new bot_1.Bot(convoState, userState);
// Listen for incoming requests 
server.post('/api/messages', (req, res) => {
    // Route received request to adapter for processing
    adapter.processActivity(req, res, (context) => __awaiter(this, void 0, void 0, function* () {
        // Dispatch to bot
        yield bot.onActivity(context);
github microsoft / botbuilder-js / samples / luis-translator-ts / lib / app.js View on Github external
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const botbuilder_1 = require("botbuilder");
const botbuilder_ai_1 = require("botbuilder-ai");
const restify = require("restify");
// Create server
let server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
    console.log(`${server.name} listening to ${server.url}`);
});
// Create adapter
const adapter = new botbuilder_1.BotFrameworkAdapter({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
});
// Add conversation state middleware
const conversationState = new botbuilder_1.ConversationState(new botbuilder_1.MemoryStorage());
adapter.use(conversationState);
// Delegates for getting and setting user language
function getUserLanguage(context) {
    const state = conversationState.get(context);
    if (state.language == undefined) {
        return 'en';
    }
    else {
        return state.language;
    }
}
github microsoft / BotBuilder-Samples / experimental / adaptive-dialog / javascript_nodejs / 20.echo-bot-declarative / index.js View on Github external
// Set up resource explorer
const resourceExplorer = new ResourceExplorer().addFolder(__dirname, true, true);
resourceExplorer.addComponent(new AdaptiveDialogComponentRegistration(resourceExplorer));

// 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',
github microsoft / botbuilder-js / samples / dialogs / sequences-ts / src / app.ts View on Github external
import { BotFrameworkAdapter, BotStateSet, MemoryStorage } from 'botbuilder';
import * as restify from 'restify';
import { AlarmBot } from './alarmBot';

// Create server
let server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
    console.log(`${server.name} listening to ${server.url}`);
});

// Create adapter
const adapter = new BotFrameworkAdapter( { 
    appId: process.env.MICROSOFT_APP_ID, 
    appPassword: process.env.MICROSOFT_APP_PASSWORD 
});

// Create bots dispatcher
const storage = new MemoryStorage();
const bot = new AlarmBot(storage);

// Add state middleware
adapter.use(new BotStateSet(bot.convoState, bot.userState));

// Listen for incoming requests 
server.post('/api/messages', (req, res) => {
    // Route received request to adapter for processing
    adapter.processActivity(req, res, async (context) => {
        // Dispatch activity to bot