How to use botframework-schema - 10 common examples

To help you get started, we’ve selected a few botframework-schema 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 microsoft / botbuilder-js / libraries / botbuilder-core / lib / testAdapter.js View on Github external
receiveActivity(activity) {
        // Initialize request
        const request = Object.assign({}, this.template, typeof activity === 'string' ? { type: botframework_schema_1.ActivityTypes.Message, text: activity } : activity);
        if (!request.type) {
            request.type = botframework_schema_1.ActivityTypes.Message;
        }
        if (!request.id) {
            request.id = (this.nextId++).toString();
        }
        // Create context object and run middleware
        const context = new turnContext_1.TurnContext(this, request);
        return this.runMiddleware(context, this.logic);
    }
    /**
github microsoft / botbuilder-js / libraries / botbuilder / lib / testAdapter.js View on Github external
let myInterval = setInterval(() => {
                    let current = new Date().getTime();
                    if ((current - start) > timeout) {
                        let expectedActivity = (typeof expected === 'string' ? { type: botframework_schema_1.ActivityTypes.Message, text: expected } : expected);
                        throw new Error(`${timeout}ms Timed out waiting for:${description || expectedActivity.text}`);
                    }
                    // if we have replies
                    if (this.adapter.botReplies.length > 0) {
                        clearInterval(myInterval);
                        let botReply = this.adapter.botReplies[0];
                        this.adapter.botReplies.splice(0, 1);
                        if (typeof expected === 'function') {
                            expected(botReply, description);
                        }
                        else if (typeof expected === 'string') {
                            assert.equal(botReply.type, botframework_schema_1.ActivityTypes.Message, (description || '') + ` type === '${botReply.type}'. `);
                            assert.equal(botReply.text, expected, (description || '') + ` text === "${botReply.text}"`);
                        }
                        else {
                            this.validateActivity(botReply, expected);
                        }
                        resolve();
                        return;
                    }
                }, interval);
            });
github microsoft / botbuilder-js / samples / echobot-connector-es6 / app.js View on Github external
JwtTokenValidation.assertValidActivity(activity, req.headers.authorization, authenticator).then(() => {

        // On message activity, reply with the same text
        if (activity.type ===  ActivityTypes.Message) {
            var reply = createReply(activity, `You said: ${activity.text}`);
            const client = new ConnectorClient(credentials, activity.serviceUrl);
            client.conversations.replyToActivity(activity.conversation.id, activity.id, reply)
                .then((reply) => {
                    console.log('reply send with id: ' + reply.id);
                });
        }

        res.send(202);
    }).catch(err => {
        console.log('Could not authenticate request:', err);
github microsoft / botbuilder-tools / packages / Chatdown / src / lib / index.ts View on Github external
continue;
    }

    // Indicates a new activity -
    // As more activity types are supported, this should
    // become a util or helper class.
    if (type) {
      let text = aggregate.substr(0, result.index).trim();
      if (text.length > 0) {
        currentActivity.text = text;
        currentActivity.timestamp = getIncrementedDate(delay);
        newActivities.push(currentActivity);
        // reset
        delay = messageTimeGap;
        currentActivity = createActivity({
          type: ActivityTypes.Message,
          from: parserModel.from,
          recipient: parserModel.recipient,
          conversationId: parserModel.conversation.id
        });
        currentActivity.text = '';
      }
      aggregate = aggregate.substr(result.index);
      if (type === ActivityTypes.Typing) {
        let newActivity = createActivity({
          type,
          recipient: parserModel.recipient,
          from: parserModel.from,
          conversationId: parserModel.conversation.id
        });
        newActivity.timestamp = getIncrementedDate(100);
        newActivities.push(newActivity);
github microsoft / botframework-solutions / templates / Enterprise-Template / src / typescript / enterprise-bot / src / dialogs / templateManager / templateManager.ts View on Github external
public async renderTemplate(turnContext: TurnContext, templateId: string, language?: string, data?: any): Promise {
        const fallbackLocales = this._languageFallback;

        if (language) {
            fallbackLocales.push(language);
        }

        fallbackLocales.push('default');

        // try each locale until successful
        for (const locale of fallbackLocales) {
            for (const renderer of this._templateRenderers) {
                const templateOutput = await renderer.renderTemplate(turnContext, locale, templateId, data);
                if (templateOutput) {
                    if (typeof templateOutput === 'string' || templateOutput instanceof String) {
                        return { type: ActivityTypes.Message, text: templateOutput as string } as Activity;
                    } else {
                        return templateOutput as Activity;
                    }
                }
            }
        }

        return undefined;
    }
}
github microsoft / botbuilder-js / libraries / botbuilder-core / src / showTypingMiddleware.ts View on Github external
// Pass in period as the delay to repeat at an interval.
                        startInterval(context, period, period);
                    } else {
                        // Do nothing! This turn is done and we don't want to continue sending typing indicators.
                    }
                },
                delay
            );
        }

        function stopInterval(): void {
            finished = true;
            if (hTimeout) { clearTimeout(hTimeout); }
        }

        if (context.activity.type === ActivityTypes.Message) {
            // Set a property to track whether or not the turn is finished.
            // When it flips to true, we won't send anymore typing indicators.
            finished = false;
            startInterval(context, this.delay, this.period);
        }

        // Let the rest of the process run.
        // After everything has run, stop the indicator!
        return await next().then(stopInterval, stopInterval);

    }
    private async sendTypingActivity(context: TurnContext): Promise {
github microsoft / botbuilder-js / libraries / botbuilder-core / lib / transcriptLogger.js View on Github external
context.onDeleteActivity((ctx, reference, next) => {
            // run full pipeline
            next();
            // add MessageDelete activity
            // log as MessageDelete activity
            let deleteActivity = turnContext_1.TurnContext.applyConversationReference({
                type: botframework_schema_1.ActivityTypes.MessageDelete,
                id: reference.activityId
            }, reference, false);
            this.logActivity(deleteActivity);
        });
        // process bot logic
github microsoft / botbuilder-js / samples / 10. sidecarDebugging / lib / bot.js View on Github external
async onTurn(turnContext) {
        // See https://aka.ms/about-bot-activity-message to learn more about the message and other activity types.
        if (turnContext.activity.type === botframework_schema_1.ActivityTypes.Message) {
            // Create dialog context.
            const dc = await this.dialogs.createContext(turnContext);
            const utterance = (turnContext.activity.text || '').trim().toLowerCase();
            if (utterance === 'cancel') {
                if (dc.activeDialog) {
                    await dc.cancelAllDialogs();
                    await dc.context.sendActivity(`Ok... canceled.`);
                }
                else {
                    await dc.context.sendActivity(`Nothing to cancel.`);
                }
            }
            if (!dc.context.responded) {
                // Continue the current dialog if one is pending.
                await dc.continueDialog();
            }
github microsoft / botbuilder-js / libraries / botbuilder / lib / bot.js View on Github external
post(context, ...activities) {
        // Ensure activities are well formed.
        for (let i = 0; i < activities.length; i++) {
            let activity = activities[i];
            if (!activity.type) {
                activity.type = botframework_schema_1.ActivityTypes.Message;
            }
            botContext_1.applyConversationReference(activity, context.conversationReference);
        }
        // Run post activity pipeline
        const adapter = this.adapter;
        return this.postActivity(context, activities, function postActivities() {
            // Post the set of output activities
            return adapter.post(activities)
                .then((responses) => {
                // Ensure responses array populated
                if (!Array.isArray(responses)) {
                    let mockResponses = [];
                    for (let i = 0; i < activities.length; i++) {
                        mockResponses.push({});
                    }
                    return mockResponses;
github microsoft / botbuilder-js / samples / 10. sidecarDebugging / lib / bot.js View on Github external
await dc.context.sendActivity(`Ok... canceled.`);
                }
                else {
                    await dc.context.sendActivity(`Nothing to cancel.`);
                }
            }
            if (!dc.context.responded) {
                // Continue the current dialog if one is pending.
                await dc.continueDialog();
            }
            if (!dc.context.responded) {
                // If no response has been sent, start the onboarding dialog.
                await dc.beginDialog('root');
            }
        }
        else if (turnContext.activity.type === botframework_schema_1.ActivityTypes.ConversationUpdate &&
            turnContext.activity.membersAdded[0].name !== 'Bot') {
            // Send a "this is what the bot does" message.
            const description = [
                'This is a bot that demonstrates an alternate dialog system',
                'which uses a slot filling technique to collect multiple responses from a user.',
                'Say anything to continue.'
            ];
            await turnContext.sendActivity(description.join(' '));
        }
        await this.conversationState.saveChanges(turnContext);
    }
}