Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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);
}
/**
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);
});
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);
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);
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;
}
}
// 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 {
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
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();
}
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;
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);
}
}