Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add actionBasedMessagingExtension from samples repo, update .gitignore #1225

Merged
merged 2 commits into from
Sep 27, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore

# Blanket ignore zip files
# Related to Teams Scenarios work
*.zip
*.vscode

# User-specific files
*.suo
*.user
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
MicrosoftAppId=
MicrosoftAppPassword=
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "messaging-extension-action",
"version": "1.0.0",
"description": "",
"main": "./lib/index.js",
"scripts": {
"start": "tsc --build && node ./lib/index.js",
"build": "tsc --build",
"watch": "nodemon --watch ./src -e ts --exec \"npm run start\""
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"botbuilder": "file:../../../",
"dotenv": "^8.1.0",
"node-fetch": "^2.6.0",
"restify": "^8.4.0",
"uuid": "^3.3.3"
},
"devDependencies": {
"@types/node": "^12.7.1",
"@types/node-fetch": "^2.5.0",
"@types/request": "^2.48.1",
"@types/restify": "^7.2.7",
"nodemon": "^1.19.1",
"ts-node": "^7.0.1",
"typescript": "^3.2.4"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import {
Activity,
Attachment,
CardFactory,
MessagingExtensionActionResponse,
MessagingExtensionAction,
TaskModuleContinueResponse,
TaskModuleMessageResponse,
TaskModuleResponseBase,
TeamsActivityHandler,
} from 'botbuilder';

export class ActionBasedMessagingExtensionBot extends TeamsActivityHandler {
constructor() {
super();

// See https://aka.ms/about-bot-activity-message to learn more about the message and other activity types.
this.onMessage(async (context, next) => {
await context.sendActivity(`You said '${context.activity.text}'`);
// By calling next() you ensure that the next BotHandler is run.
await next();
});

this.onMembersAdded(async (context, next) => {
const membersAdded = context.activity.membersAdded;
for (const member of membersAdded) {
if (member.id !== context.activity.recipient.id) {
await context.sendActivity('Hello and welcome!');
}
}

// By calling next() you ensure that the next BotHandler is run.
await next();
});

// This method fires when an user uses an Action-based Messaging Extension from the Teams Client.
// It should send back the tab or task module for the user to interact with.
this.onMessagingExtensionFetchTask(async (context, value, next) => {
return {
status: 200,
body: {
task: this.taskModuleResponse(value, false)
}
};
});

this.onBotMessagePreviewEdit(async (context, value: MessagingExtensionAction, next) => {
const card = this.getCardFromPreviewMessage(value);
let body: MessagingExtensionActionResponse;
if (!card) {
body = {
task: <TaskModuleMessageResponse>{
type: 'message',
value: 'Missing user edit card. Something wrong on Teams client.'
}
}
} else {
body = {
task: <TaskModuleContinueResponse>{
type: 'continue',
value: { card }
}
}
}

return { status: 200, body };
});

this.onBotMessagePreviewSend(async (context, value: MessagingExtensionAction, next) => {
let body: MessagingExtensionActionResponse;
const card = this.getCardFromPreviewMessage(value);
if (!card) {
body = {
task: <TaskModuleMessageResponse>{
type: 'message',
value: 'Missing user edit card. Something wrong on Teams client.'
}
}
} else {
body = undefined;
await context.sendActivity({ attachments: [card] });
}

return { status: 200, body };
});

this.onMessagingExtensionSubmit(async (context, value: MessagingExtensionAction, next) => {
const data = value.data;
let body: MessagingExtensionActionResponse;
if (data && data.done) {
// The commandContext check doesn't need to be used in this scenario as the manifest specifies the shareMessage command only works in the "message" context.
let sharedMessage = (value.commandId === 'shareMessage' && value.commandContext === 'message')
? `Shared message: <div style="background:#F0F0F0">${JSON.stringify(value.messagePayload)}</div><br/>`
: '';
let preview = CardFactory.thumbnailCard('Created Card', `Your input: ${data.userText}`);
let heroCard = CardFactory.heroCard('Created Card', `${sharedMessage}Your input: <pre>${data.userText}</pre>`);
body = {
composeExtension: {
type: 'result',
attachmentLayout: 'list',
attachments: [
{ ...heroCard, preview }
]
}
}
} else if (value.commandId === 'createWithPreview') {
const activityPreview = {
attachments: [
this.taskModuleResponseCard(value)
]
} as Activity;

body = {
composeExtension: {
type: 'botMessagePreview',
activityPreview
}
};
} else {
body = {
task: this.taskModuleResponse(value, false)
}
}

return { status: 200, body };
});
}

private getCardFromPreviewMessage(query: MessagingExtensionAction): Attachment {
const userEditActivities = query.botActivityPreview;
return userEditActivities
&& userEditActivities[0]
&& userEditActivities[0].attachments
&& userEditActivities[0].attachments[0];
}

private taskModuleResponse(query: any, done: boolean): TaskModuleResponseBase {
if (done) {
return <TaskModuleMessageResponse>{
type: 'message',
value: 'Thanks for your inputs!'
}
} else {
return <TaskModuleContinueResponse>{
type: 'continue',
value: {
title: 'More Page',
card: this.taskModuleResponseCard(query, (query.data && query.data.userText) || undefined)
}
};
}
}

private taskModuleResponseCard(data: any, textValue?: string) {
return CardFactory.adaptiveCard({
version: '1.0.0',
type: 'AdaptiveCard',
body: [
{
type: 'TextBlock',
text: `Your request:`,
size: 'large',
weight: 'bolder'
},
{
type: 'Container',
style: 'emphasis',
items: [
{
type: 'TextBlock',
text: JSON.stringify(data),
wrap: true
}
]
},
{
type: 'Input.Text',
id: 'userText',
placeholder: 'Type text here...',
value: textValue
}
],
actions: [
{
type: 'Action.Submit',
title: 'Next',
data: {
done: false
}
},
{
type: 'Action.Submit',
title: 'Submit',
data: {
done: true
}
}
]
})
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import { config } from 'dotenv';
import * as path from 'path';
import * as restify from 'restify';

// Import required bot services.
// See https://aka.ms/bot-services to learn more about the different parts of a bot.
import { BotFrameworkAdapter } from 'botbuilder';

// This bot's main dialog.
import { ActionBasedMessagingExtensionBot } from './actionBasedMessagingExtensionBot ';

const ENV_FILE = path.join(__dirname, '..', '.env');
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 test your bot, see: https://aka.ms/debug-with-emulator`);
});

// Create adapter.
// See https://aka.ms/about-bot-adapter to learn more about adapters.
const adapter = new BotFrameworkAdapter({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});

// adapter.use(new TranscriptLoggerMiddleware(new FileTranscriptStore('./transcripts')));

// Catch-all for errors.
adapter.onTurnError = async (context, error) => {
// This check writes out errors to console log .vs. app insights.
console.error('[onTurnError]:');
console.error(error);
// Send a message to the user
await context.sendActivity(`Oops. Something went wrong in the bot!\n ${error.message}`);
};

// Create the main dialog.
const myBot = new ActionBasedMessagingExtensionBot();

// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
adapter.processActivity(req, res, async (context) => {
// Route to main dialog.
await myBot.run(context);
});
});
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
{
"$schema": "https://github.com/OfficeDev/microsoft-teams-app-schema/blob/preview/DevPreview/MicrosoftTeams.schema.json",
"manifestVersion": "devPreview",
"version": "1.0",
"id": "<<YOUR_GENERATED_APP_GUID>>",
"packageName": "com.microsoft.teams.samples.v4bot",
"developer": {
"name": "Microsoft Corp",
"websiteUrl": "https://example.azurewebsites.net",
"privacyUrl": "https://example.azurewebsites.net/privacy",
"termsOfUseUrl": "https://example.azurewebsites.net/termsofuse"
},
"name": {
"short": "messaging-extension-action",
"full": "Microsoft Teams V4 Action Messaging Extension Bot - C#"
},
"description": {
"short": "Microsoft Teams V4 Action Messaging Extension Bot - C#",
"full": "Sample Action Messaging Extension Bot using V4 Bot Builder SDK and V4 Microsoft Teams Extension SDK"
},
"icons": {
"outline": "icon-outline.png",
"color": "icon-color.png"
},
"accentColor": "#0080FF",
"bots": [],
"composeExtensions": [
{
"botId": "<<YOUR_BOTS_MSA_APP_ID>>",
"commands": [
{
"id": "createCard",
"type": "action",
"description": "Test command to run action to create a card from Compose Box or Command Bar",
"title": "Create card - manifest params",
"parameters": [
{
"name": "title",
"title": "Title parameter",
"description": "Text for title in Hero Card",
"inputType": "text"
},
{
"name": "subtitle",
"title": "Subtitle parameter",
"description": "Text for subtitle in Hero Card",
"inputType": "text"
},
{
"name": "text",
"title": "Body text",
"description": "Text for body in Hero Card",
"inputType": "text"
}
]
},
{
"id": "shareMessage",
"type": "action",
"context": [ "message" ],
"description": "Test command to run action on message context (message sharing)",
"title": "Share Message",
"parameters": [
{
"name": "includeImage",
"title": "Include Image",
"description": "Include image in Hero Card",
"inputType": "toggle"
}
]
}
]
}
],
"validDomains": [
"*.ngrok.io",
"*.azurewebsites.net",
"*.example.com"
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"composite": true,
"declaration": true,
"sourceMap": true,
"outDir": "./lib",
"rootDir": "./src",
}
}