### Install Handler Example Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/pages/templates/essentials/sending-messages/proactive-messaging.mdx This example shows how to install an activity handler to capture conversation IDs for later use in proactive messaging. ```typescript import { app, ConversationInfo, MessageInfo } from "@microsoft/teams-js"; // Initialize the Teams app app.initialize(); // Define an activity handler to capture conversation information const activityHandler = { onMessage: (message: MessageInfo) => { // Handle incoming messages if needed }, onConversationUpdate: (conversation: ConversationInfo) => { // Store conversation ID for proactive messaging console.log("Conversation ID:", conversation.id); // You would typically store this ID in your application's storage }, onTeamsUserIdentityInfo: (userIdentityInfo: any) => { // Handle user identity info if needed } }; // Register the activity handler app.registerActivityHandler(activityHandler); ``` -------------------------------- ### Project Lifecycle Commands Source: https://github.com/microsoft/teams-sdk/blob/main/packages/cli/templates/typescript/tab/README.md Standard commands for installing dependencies and starting the development server. ```bash npm install ``` ```bash npm start ``` -------------------------------- ### Self-Managing Server Setup (Python) Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/pages/templates/in-depth-guides/server/http-server.mdx Initialize the Teams app with your custom server and adapter, then start the server manually. Do not call `app.start()`. ```python app = TeamsApp(...) adapter = MyFastAPIAdapter(fastapi_app) await app.initialize(adapter) fastapi_app.run(port=port) ``` -------------------------------- ### Initialize and Run Teams Bot Source: https://github.com/microsoft/teams-sdk/blob/main/packages/cli/templates/python/graph/README.md Commands to set up the virtual environment, install dependencies, and start the bot application. ```bash python -m venv .venv ``` ```bash . .venv/bin/activate ``` ```bash .venv\Scripts\activate ``` ```bash pip install -e . ``` ```bash python src/main.py ``` -------------------------------- ### Development Server Output Example Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/getting-started/quickstart/typescript.incl.md This is an example of the console output when the development server starts successfully, indicating the agent is listening on port 3978. ```sh > quote-agent@0.0.0 dev > npx nodemon -w "./src/**" -e ts --exec "node -r ts-node/register -r dotenv/config ./src/index.ts" [nodemon] 3.1.9 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): src/** [nodemon] watching extensions: ts [nodemon] starting `node -r ts-node/register -r dotenv/config ./src/index.ts` [INFO] @teams/app/http listening on port 3978 🚀 ``` -------------------------------- ### Console Output Example Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/getting-started/quickstart/csharp.incl.md This is an example of the console output you can expect when your Teams agent starts successfully. It indicates the listening address and port. ```sh [INFO] Microsoft.Hosting.Lifetime Now listening on: http://localhost:3978 [INFO] Microsoft.Hosting.Lifetime Application started. Press Ctrl+C to shut down. [INFO] Microsoft.Hosting.Lifetime Hosting environment: Development ``` -------------------------------- ### Self-Managing Server Setup (TypeScript) Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/pages/templates/in-depth-guides/server/http-server.mdx Initialize the Teams app with your custom server and adapter, then start the server manually. Do not call `app.start()`. ```typescript const app = new TeamsApp(...); const adapter = new MyExpressAdapter(expressApp); await app.initialize(adapter); expressApp.listen(port, () => { console.log(`Server listening on ${port}`); }); ``` -------------------------------- ### Example Agent Session: Create Echo Bot Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/docs/main/developer-tools/agent-skills.md Illustrates an AI agent session where the user requests an echo bot. The agent outlines the steps it will take, including CLI commands and setup. ```text You: Help me create a Teams bot that echoes what I'm saying back to me Agent: I'll create an echo bot for you. [checks Teams Developer CLI installation and authentication] [creates development tunnel: https://abc123.ngrok.io] [runs teams app create with endpoint] ✓ Bot registered, credentials saved to .env [runs teams project new typescript echo-bot -t echo] ✓ Bot code created in ./echo-bot [installs dependencies and starts bot server] ✓ Bot running at http://localhost:3978 Your bot is ready! Install it in Teams: https://teams.microsoft.com/l/app/[app-id] ``` -------------------------------- ### Run Python agent Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/docs/main/get-started/quickstart-register.md Installs the Python project in editable mode and starts the main application script. ```bash pip install -e . python src/main.py ``` -------------------------------- ### Run TypeScript agent Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/docs/main/get-started/quickstart-register.md Installs npm dependencies and starts the development server for a TypeScript Teams bot. ```bash npm install npm run dev ``` -------------------------------- ### FastAPI Self-Managed Server Example Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/in-depth-guides/server/http-server/python.incl.md Demonstrates how to use the Teams SDK with a self-managed FastAPI application. This involves creating a FastAPI instance, wrapping it with FastAPIAdapter, initializing the Teams app, and starting the server manually. ```python import asyncio import uvicorn from fastapi import FastAPI from microsoft_teams.apps import App, FastAPIAdapter # 1. Create your FastAPI app with your own routes my_fastapi = FastAPI(title="My App + Teams Bot") @my_fastapi.get("/health") async def health(): return {"status": "healthy"} # 2. Wrap it in the FastAPIAdapter adapter = FastAPIAdapter(app=my_fastapi) # 3. Create the Teams app with the adapter app = App(http_server_adapter=adapter) @app.on_message async def handle_message(ctx): await ctx.send(f"Echo: {ctx.activity.text}") async def main(): # 4. Initialize — registers /api/messages on your FastAPI app (does NOT start a server) await app.initialize() # 5. Start the server yourself config = uvicorn.Config(app=my_fastapi, host="0.0.0.0", port=3978) server = uvicorn.Server(config) await server.serve() asyncio.run(main()) ``` -------------------------------- ### Install and Login to Teams CLI Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/blog/2026-04-28-teams-cli-preview/index.md Install the preview version of the Teams Developer CLI globally and log in to your Teams account. ```bash npm install -g @microsoft/teams.cli@preview teams login ``` -------------------------------- ### Install Teams CLI Preview Package Source: https://github.com/microsoft/teams-sdk/blob/main/RELEASE.md Use this command to install the preview version of the Teams CLI package. ```bash npm install -g @microsoft/teams.cli@preview ``` -------------------------------- ### Install Agents Playground via npm Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/docs/main/developer-tools/agents-playground/README.md Install the Microsoft 365 Agents Playground CLI globally using npm. This is the recommended installation method. ```bash npm install -g @microsoft/m365agentsplayground ``` -------------------------------- ### Install Azure CLI on Windows Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/docs/cli/getting-started/installation.md Installs the Azure CLI using winget on Windows. This is optional and required for Azure bot operations. ```bash winget install Microsoft.AzureCLI ``` -------------------------------- ### Program.cs Setup for Teams Application Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/getting-started/code-basics/csharp.incl.md This snippet shows the basic setup for a Teams application in C#, including adding Teams functionality and middleware. It's used for initializing the application and its Teams-specific features. ```csharp using Microsoft.Teams.Apps.Activities; using Microsoft.Teams.Apps.Extensions; using Microsoft.Teams.Plugins.AspNetCore.Extensions; var builder = WebApplication.CreateBuilder(args); builder.AddTeams(); var app = builder.Build(); var teams = app.UseTeams(); teams.OnMessage(async (context, cancellationToken) { await context.Typing(cancellationToken); await context.Send($"you said '{context.Activity.Text}'", cancellationToken); }); app.Run(); ``` -------------------------------- ### Handle Installation and Send Proactive Message Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/essentials/sending-messages/proactive-messaging/csharp.incl.md This snippet shows how to handle the installation event for a bot, save the conversation ID, and schedule a proactive reminder. It requires the 'Microsoft.Bot.Builder' and 'Microsoft.Teams.Api' namespaces. ```csharp app.OnInstall(async (context, cancellationToken) => { // Save the conversation id in context.Storage.Set(activity.From.AadObjectId!, activity.Conversation.Id); await context.Send("Hi! I am going to remind you something to me soon!", cancellationToken); notificationQueue.AddReminder(activity.From.AadObjectId!, Notifications.SendProactive, 10_000); }); ``` -------------------------------- ### Install Agents Playground Standalone Binary Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/docs/main/developer-tools/agents-playground/README.md Install the Agents Playground as a standalone binary using winget. This is an alternative installation method for Windows. ```bash winget install agentsplayground ``` -------------------------------- ### Display Bot Install Link Source: https://github.com/microsoft/teams-sdk/blob/main/plugins/teams-sdk/skills/teams-dev/references/guide-create-bot-infra.md Extract and display the install link from the JSON output to allow users to install the bot in Microsoft Teams. ```bash Install your bot in Teams: ``` -------------------------------- ### Install OpenTelemetry and Teams SDK Packages Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/in-depth-guides/observability/opentelemetry/csharp.incl.md Install the necessary NuGet packages for OpenTelemetry instrumentation and the Teams SDK. For Azure Monitor export, include the Azure Monitor package. ```bash dotnet add package Microsoft.Teams.Apps --prerelease dotnet add package OpenTelemetry.Extensions.Hosting dotnet add package OpenTelemetry.Instrumentation.Http dotnet add package OpenTelemetry.Instrumentation.AspNetCore ``` ```bash dotnet add package Azure.Monitor.OpenTelemetry.AspNetCore ``` -------------------------------- ### Install Teams SDK Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/pages/templates/migrations/slack-bolt.mdx Instructions for installing the Microsoft Teams SDK. This typically involves using a package manager like npm or yarn. ```bash npm install @microsoft/teams-js # or yarn add @microsoft/teams-js ``` -------------------------------- ### Start Teams Application Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/blog/2026-04-17-bring-your-agent-to-teams/index.md Initializes the Teams application and starts the HTTP server to listen for incoming messages. ```typescript import 'dotenv/config'; import http from 'http'; import { expressApp, teamsApp } from './teams-app'; await teamsApp.initialize(); http.createServer(expressApp).listen(3978); ``` -------------------------------- ### Install Teams SDK in an existing project Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/pages/templates/getting-started/quickstart.mdx Install the Teams SDK directly into an existing project using npm. ```sh npm install @microsoft/teams-js ``` -------------------------------- ### Install Dependencies Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/getting-started/running-in-teams/python.incl.md Install the project dependencies using pip. This command installs the package in editable mode, allowing for direct code changes. ```sh pip install -e . ``` -------------------------------- ### Action Planner Setup with OpenAI Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/migrations/v1/typescript.incl.md Configures an ActionPlanner with OpenAI integration, defining functions for light control and pausing. This setup is suitable for AI-driven task automation. ```typescript const prompt = new ActionPlanner({ model: new OpenAIModel({ apiKey: process.env.OPENAI_API_KEY, }), }); prompt.function('get_light_status', 'get the current light status', () => { return state.status; }) .function('toggle_lights', 'toggles the lights on/off', () => { state.status = !state.status; storage.set(client.activity.from.id, state); }) .function( 'pause', 'delays for a period of time', { type: 'object', properties: { time: { type: 'number', description: 'the amount of time to delay in milliseconds', }, }, required: ['time'], }, async ({ time }: { time: number }) => { await new Promise((resolve) => setTimeout(resolve, time)); } ); await prompt.send(client.activity.text, { onChunk: (chunk) => { client.stream.emit(new MessageActivity(chunk)); }, }); }); (async () => { await app.start(); })(); ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/getting-started/quickstart/csharp.incl.md Restore and install all necessary NuGet packages for your C# Teams agent project. ```bash dotnet restore ``` -------------------------------- ### Teams SDK v1 Application Setup Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/migrations/v1/typescript.incl.md This snippet shows the v1 setup for a Teams application using botbuilder components and restify for the server. It includes adapter creation and error handling. ```ts import { ConfigurationServiceClientCredentialFactory, MemoryStorage, TurnContext, } from 'botbuilder'; import { Application, TeamsAdapter } from '@microsoft/teams-ai'; import * as restify from 'restify'; // Create adapter. const adapter = new TeamsAdapter( {}, new ConfigurationServiceClientCredentialFactory({ MicrosoftAppId: process.env.ENTRA_APP_CLIENT_ID, MicrosoftAppPassword: process.env.ENTRA_APP_CLIENT_SECRET, MicrosoftAppType: 'SingleTenant', MicrosoftAppTenantId: process.env.ENTRA_APP_TENANT_ID }) ); // Catch-all for errors. const onTurnErrorHandler = async (context: TurnContext, error: any) => { console.error(`\n [onTurnError] unhandled error: ${error}`); // Send a message to the user await context.sendActivity('The bot encountered an error or bug.'); }; // Set the onTurnError for the singleton CloudAdapter. adapter.onTurnError = onTurnErrorHandler; // Create HTTP server. const server = restify.createServer(); server.use(restify.plugins.bodyParser()); server.listen(process.env.port || process.env.PORT || 3978, () => { console.log(`\n${server.name} listening to ${server.url}`); }); // Define storage and application const app = new Application({ storage: new MemoryStorage() }); // Listen for incoming server requests. server.post('/api/messages', async (req, res) => { // Route received a request to adapter for processing await adapter.process(req, res, async (context) => { // Dispatch to application for routing await app.run(context); }); }); ``` -------------------------------- ### Start the Development Server Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/getting-started/quickstart/typescript.incl.md Run the development server to start your Teams agent. This command watches for changes in the 'src' directory and restarts the server automatically. ```sh npm run dev ``` -------------------------------- ### Create and auto-start a new C# Teams app Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/docs/cli/commands/project/new-csharp.md This command creates a new C# Teams application and automatically starts the project after creation. Use the `-s` or `--start` flag to enable this behavior. ```bash teams project new csharp -s ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/getting-started/quickstart/typescript.incl.md Change into the newly created project directory to begin setup. ```sh cd quote-agent ``` -------------------------------- ### Get Install Link for a Teams App Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/docs/cli/commands/app/get.md Use the --web flag to obtain the install link for a Teams app. This is useful for generating direct installation URLs. ```bash teams app get --web ``` -------------------------------- ### Get Teams App install link Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/docs/main/get-started/quickstart-register.md Retrieves the sideload install link for a Teams app using its App ID. ```bash teams app get --install-link ``` -------------------------------- ### Run local development server Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/BLOGGING.md Start the local development server to verify blog post rendering. ```bash # From the repo root npm run docs:dev ``` -------------------------------- ### Handle Installation and Store Conversation ID Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/essentials/sending-messages/proactive-messaging/python.incl.md When your app is installed, capture the conversation ID from the installation activity. This ID is crucial for sending proactive messages later. Store it persistently, for example, in a dictionary. ```python from microsoft_teams.api import InstalledActivity, MessageActivityInput from microsoft_teams.apps import ActivityContext # ... # This would be some persistent storage storage = dict[str, str]() # Installation is just one place to get the conversation_id. All activities have this field as well. @app.on_install_add async def handle_install_add(ctx: ActivityContext[InstalledActivity]): # Save the conversation_id storage[ctx.activity.from_.aad_object_id] = ctx.activity.conversation.id await ctx.send("Hi! I am going to remind you to say something to me soon!") # This queues up the proactive notifaction to be sent in 1 minute notication_queue.add_reminder(ctx.activity.from_.aad_object_id, send_proactive_notification, 60000) ``` -------------------------------- ### Navigate to Agent Directory Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/getting-started/quickstart/csharp.incl.md Change into the newly created agent's directory to access its files and begin the setup process. ```bash cd Quote.Agent/Quote.Agent ``` -------------------------------- ### Get Meeting Information using BotBuilder and Teams SDK Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/migrations/botbuilder/the-api-client/python.incl.md This snippet illustrates how to retrieve information about a Teams meeting. The BotBuilder SDK uses `TeamsInfo.get_meeting_info`, while the Teams SDK uses `api.meetings.get_by_id`. This is useful for accessing meeting-related data such as start time, end time, and participants. ```python # BotBuilder (TeamsInfo) # TeamsInfo.get_meeting_info(context, meeting_id) ``` ```python # Teams SDK (ApiClient) # api.meetings.get_by_id(meeting_id) ``` -------------------------------- ### Initialize and Mount MCP App with FastAPI Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/in-depth-guides/ai-integrations/mcp-server/python.incl.md Sets up the FastAPI adapter, mounts the MCP HTTP app, and starts the main application. This code should be run in the main entry point of the application. ```python import asyncio from microsoft_teams.apps.http.fastapi_adapter import FastAPIAdapter # Assume app and mcp are defined elsewhere async def main() -> None: await app.initialize() adapter = app.server.adapter assert isinstance(adapter, FastAPIAdapter) mcp_http_app = mcp.streamable_http_app() adapter.lifespans.append(mcp_http_app.router.lifespan_context) adapter.app.mount("/mcp", mcp_http_app) await app.start() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install Microsoft Teams SDK Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/migrations/v1/python.incl.md Command to install the Microsoft Teams SDK package into your Python project environment. ```shell pip install microsoft-teams-apps ``` -------------------------------- ### Teams SDK v2 Application Setup Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/migrations/v1/typescript.incl.md Initialize the v2 application with client credentials and set up optional local storage. Includes an error event listener for handling runtime issues. ```ts import { App } from '@microsoft/teams.apps'; import { LocalStorage } from '@microsoft/teams.common/storage'; // Define app const app = new App({ clientId: process.env.ENTRA_APP_CLIENT_ID!, clientSecret: process.env.ENTRA_APP_CLIENT_SECRET!, tenantId: process.env.ENTRA_APP_TENANT_ID!, }); // Optionally create local storage const storage = new LocalStorage(); // Listen for errors app.event('error', async (client) => { console.error('Error event received:', client.error); if (client.activity) { await app.send( client.activity.conversation.id, 'An error occurred while processing your message.', ); } }); // App creates local server with route for /api/messages // To reuse your restify or other server, // create a custom `HttpPlugin`. (async () => { // starts the server await app.start(); })(); ``` -------------------------------- ### Update Startup Code: Bot Framework v4 Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/blog/2026-05-19-announcing-teams-sdk-dotnet-2-1-preview/index.md Illustrates the service registration and setup for a Bot Framework v4 bot before migration. ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddSingleton(); builder.Services.AddTransient(); var app = builder.Build(); app.MapControllers(); app.Run(); ``` -------------------------------- ### Create Teams App with appsettings.json Output for C# Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/docs/cli/commands/app/create.md Create a Teams app and write credentials to an appsettings.json file, suitable for C# projects. Credentials will be formatted under a 'Teams' section with PascalCase keys. ```bash teams app create --name "My Bot" --env appsettings.json ``` -------------------------------- ### Get Team Members using BotBuilder and Teams SDK Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/migrations/botbuilder/the-api-client/python.incl.md This snippet shows how to retrieve a list of members in a Teams conversation. The BotBuilder example uses `TeamsInfo.get_members`, while the Teams SDK example uses `context.api.conversations.members`. Both achieve the same outcome of fetching member information. ```python from botbuilder.core import ActivityHandler, TurnContext from botbuilder.core.teams import TeamsInfo class MyActivityHandler(ActivityHandler): async def on_message_activity(self, turn_context: TurnContext): # highlight-next-line members = await TeamsInfo.get_members(turn_context) ``` ```python from microsoft_teams.api import MessageActivity from microsoft_teams.apps import ActivityContext @app.on_message async def on_message(context: ActivityContext[MessageActivity]): # highlight-next-line members = await context.api.conversations.members(context.activity.conversation.id).get() ``` -------------------------------- ### Run OTelBotWithAspire Sample Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/in-depth-guides/observability/opentelemetry/csharp.incl.md Use the OTelBotWithAspire sample project which includes an Aspire AppHost for orchestrating the bot and providing a dashboard. The dashboard is accessible at http://localhost:18888. ```csharp // OTelBotWithAspire.AppHost/AppHost.cs IDistributedApplicationBuilder builder = DistributedApplication.CreateBuilder(args); builder.AddProject("otelbot"); builder.Build().Run(); ``` -------------------------------- ### Get Bot Information Source: https://github.com/microsoft/teams-sdk/blob/main/plugins/teams-sdk/skills/teams-dev/references/guide-setup-sso.md Retrieve details about your Teams bot, including its location. This is crucial for determining if migration is needed for SSO setup. ```bash teams app bot get ``` -------------------------------- ### Run Teams App Bot Command Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/docs/cli/commands/app/bot.md Use this command to manage bot registration for your Teams application. No specific setup is required beyond having the Teams CLI installed. ```bash teams app bot ``` -------------------------------- ### Minimal ASP.NET Core Bot with Teams SDK Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/blog/2026-05-19-announcing-teams-sdk-dotnet-2-1-preview/index.md A basic C# example demonstrating how to set up a minimal bot using the Teams SDK within an ASP.NET Core application. It registers the bot and sets up a handler for incoming messages. ```csharp using Microsoft.Teams.Apps; WebApplicationBuilder builder = WebApplication.CreateSlimBuilder(args); builder.Services.AddTeamsBotApplication(); WebApplication app = builder.Build(); TeamsBotApplication teams = app.UseTeamsBotApplication(); teams.OnMessage(async (context, cancellationToken) => { await context.SendActivityAsync($"You said: {context.Activity.Text}", cancellationToken); }); app.Run(); ``` -------------------------------- ### Get Meeting Participant Information Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/essentials/api/csharp.incl.md This example shows how to fetch details about a participant in a meeting. It requires the meeting ID, user ID, and tenant ID. The participant object contains information about their meeting role and status. ```csharp app.OnMeetingStart(async (context, cancellationToken) => { var meetingId = context.Activity.Value.Id; var tenantId = context.Activity.ChannelData?.Tenant?.Id; var userId = context.Activity.From?.AadObjectId; if (meetingId != null && tenantId != null && userId != null) { var participant = await context.Api.Meetings.GetParticipantAsync(meetingId, userId, tenantId); // participant.Meeting?.Role — "Organizer", "Presenter", "Attendee" // participant.Meeting?.InMeeting — true/false } }); ``` -------------------------------- ### Get App Details with Specific Fields in JSON Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/docs/cli/commands/app/get.md Use the --json flag with a comma-separated list of fields to retrieve specific app details for scripting purposes. This example fetches the appId, name, and endpoint. ```bash teams app get --json appId,name,endpoint ``` -------------------------------- ### Initialize Microsoft Teams Bot Application Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/migrations/v1/python.incl.md Demonstrates the initialization of a Teams bot application using MemoryStorage and a TeamsAdapter. This setup is required to manage bot state and handle incoming activities. ```python storage = MemoryStorage() app = Application[TurnState]( ApplicationOptions( bot_app_id=config.APP_ID, adapter=TeamsAdapter(config), storage=storage ) ) ``` -------------------------------- ### Create a new C# Bot Project Source: https://github.com/microsoft/teams-sdk/blob/main/plugins/teams-sdk/skills/teams-dev/references/guide-create-bot-app.md Use this command to create a new bot project with C#. ```bash teams project new cs ``` -------------------------------- ### Pre-warm Specific Scopes in Teams App Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/pages/templates/in-depth-guides/tabs/app-options.mdx This code example shows how to pre-warm a specific set of scopes required by your Teams app. By listing the desired scopes in `prewarmScopes`, you can ensure the user is prompted for consent for these specific permissions as the app starts. ```typescript import { App } from '@microsoft/teams.client'; const app = new App(clientId, { msalOptions: { prewarmScopes: ['User.Read', 'Chat.ReadBasic'] }, }); // if the user hasn't already given consent for each listed scope, // this will prompt them await app.start(); ``` -------------------------------- ### Configure Authentication and Handlers in Teams SDK v1 Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/migrations/v1/python.incl.md Shows the setup of the Application object with OAuth options and storage in Teams SDK v1. It demonstrates how to register sign-out commands and event listeners for authentication success and failure. ```python app = Application[TurnState[ConversationState, UserState, TempState]]( ApplicationOptions( bot_app_id=config.APP_ID, storage=MemoryStorage(), adapter=TeamsAdapter(config), auth=AuthOptions( default="graph", auto=True, settings={ "graph": OAuthOptions( connection_name=config.OAUTH_CONNECTION_NAME, title="Sign In", text="please sign in", end_on_invalid_message=True, enable_sso=True, ), }, ), ) ) auth = app.auth.get("graph") @app.message("/signout") async def on_sign_out( context: TurnContext, state: TurnState[ConversationState, UserState, TempState] ): await auth.sign_out(context, state) await context.send_activity("you are now signed out...👋") return False @auth.on_sign_in_success async def on_sign_in_success( context: TurnContext, state: TurnState[ConversationState, UserState, TempState] ): await context.send_activity("successfully logged in!") await context.send_activity(f"token: {state.temp.auth_tokens['graph']}") @auth.on_sign_in_failure async def on_sign_in_failure( context: TurnContext, _state: TurnState[ConversationState, UserState, TempState], _res: SignInResponse, ): await context.send_activity("failed to login...") ``` -------------------------------- ### Update Multiple App Properties Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/docs/cli/commands/app/update.md This example demonstrates updating several app properties, such as name, version, and developer, in a single command execution. ```bash teams app update --name "New Name" --version "2.0.0" --developer "My Team" ``` -------------------------------- ### Handle Authentication Flow using Teams SDK v2 Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/migrations/v1/python.incl.md This snippet demonstrates the new authentication flow in Teams SDK v2. It includes handling sign-in requests, success, and failure events, as well as a sign-out command. This replaces the older, more verbose authentication setup. ```python from botbuilder.core.teams import App, ActivityContext, MessageActivity, SignInEvent, ErrorEvent app = App() @app.on_message async def handle_message(ctx: ActivityContext[MessageActivity]): ctx.logger.info("User requested sign-in.") if ctx.is_signed_in: await ctx.send("You are already signed in.") else: await ctx.sign_in() @app.on_message_pattern("/signout") async def handle_sign_out(ctx: ActivityContext[MessageActivity]): await ctx.sign_out() await ctx.send("You have been signed out.") @app.event("sign_in") async def handle_sign_in(event: SignInEvent): """Handle sign-in events.""" await event.activity_ctx.send("You are now signed in!") @app.event("error") async def handle_error(event: ErrorEvent): # Error handling logic here ``` -------------------------------- ### Initialize ConfigurationServiceClientCredentialFactory Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/migrations/v1/typescript.incl.md Sets up credentials for the bot using environment variables for application ID, password, and tenant ID. This is a prerequisite for bot authentication. ```typescript new ConfigurationServiceClientCredentialFactory({ MicrosoftAppId: process.env.ENTRA_APP_CLIENT_ID, MicrosoftAppPassword: process.env.ENTRA_APP_CLIENT_SECRET, MicrosoftAppType: 'SingleTenant', MicrosoftAppTenantId: process.env.ENTRA_APP_TENANT_ID }) ); ``` -------------------------------- ### Handle Sign-In Command Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/in-depth-guides/user-authentication/csharp.incl.md Implement logic to handle a '/signin' command, checking if the user is already signed in and initiating the sign-in process if not. ```csharp teams.OnMessage("/signin", async (context, cancellationToken) => { if (context.IsSignedIn) { await context.Send("you are already signed in!", cancellationToken); return; } else { await context.SignIn(cancellationToken); } }); ``` -------------------------------- ### Initialize Azure OpenAI Client Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/in-depth-guides/ai-integrations/build-agent/typescript.incl.md Sets up the AzureOpenAI client with necessary credentials and deployment information. Ensure environment variables for endpoint, API key, and deployment name are set. ```typescript import { AzureOpenAI } from 'openai'; const client = new AzureOpenAI({ endpoint: process.env.AZURE_OPENAI_ENDPOINT!, apiKey: process.env.AZURE_OPENAI_API_KEY!, deployment: process.env.AZURE_OPENAI_MODEL_DEPLOYMENT_NAME!, apiVersion: process.env.AZURE_OPENAI_API_VERSION || '2024-10-21', }); const SYSTEM_PROMPT = 'You are a helpful Teams assistant.'; ``` -------------------------------- ### Get Chat Instance ID using User Graph Client (TypeScript) Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/essentials/graph/typescript.incl.md Illustrates how to retrieve the `id` of a chat instance between a user and an app using the `userGraph` client. This example demonstrates passing arguments for URL path parameters and query string selections to the `call` method, mirroring a specific Microsoft Graph API endpoint. ```typescript import { users } from '@microsoft/teams.graph-endpoints'; const chat = await userGraph.call(users.teamwork.installedApps.chat.get, { 'user-id': user.id, 'userScopeTeamsAppInstallation-id': appInstallationId, '$select': ['id'], }); ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/getting-started/quickstart/typescript.incl.md Install all necessary npm packages for your Teams agent project. ```sh npm install ``` -------------------------------- ### Install and Use Teams Developer CLI Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/blog/2026-06-04-devtools-to-agents-playground/index.md Install the Teams Developer CLI, log in, and create a new Teams app. Provide your agent's endpoint, which should be a publicly accessible URL, often obtained via a tunneling service. ```bash npm install -g @microsoft/teams.cli@preview teams login teams app create --name "My Agent" --endpoint https:///api/messages --env .env ``` -------------------------------- ### Install Teams Apps Package Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/getting-started/quickstart/typescript.incl.md Manually install the necessary Teams Apps package for your project. ```sh npm i @microsoft/teams.apps ``` -------------------------------- ### Verify Teams CLI Installation Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/docs/cli/getting-started/installation.md Checks if the Teams CLI is installed correctly by displaying its current version. ```bash teams --version ``` -------------------------------- ### Install DevTunnels CLI Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/docs/cli/concepts/local-tunnels.md Install the DevTunnels CLI tool using package managers for macOS/Linux or Windows. ```bash # macOS / Linux brew install devtunnel ``` ```bash # Windows (winget) winget install Microsoft.devtunnel ``` -------------------------------- ### Adaptive Card with Input Association Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/in-depth-guides/adaptive-cards/executing-actions/python.incl.md This example demonstrates creating an `AdaptiveCard` with various input elements (`TextInput`, `ToggleInput`) and an `ExecuteAction`. The `with_data` method includes static data, and the comment shows the structure of data received in the handler, including input values. ```python from microsoft_teams.cards import AdaptiveCard, ActionSet, ExecuteAction, OpenUrlAction from microsoft_teams.cards.core import TextInput, ToggleInput # ... profile_card = AdaptiveCard( schema="http://adaptivecards.io/schemas/adaptive-card.json", body=[ TextInput(id="name").with_label("Name").with_value("John Doe"), TextInput(id="email", label="Email", value="john@contoso.com"), ToggleInput(title="Subscribe to newsletter").with_id("subscribe").with_value("false"), ActionSet( actions=[ ExecuteAction(title="Save") # entity_id will come back after the user submits .with_data({"action": "save_profile", "entity_id": "12345"}), ] ), ], ) # Data received in handler: """ { "action": "save_profile", "entity_id": "12345", # From action data "name": "John Doe", # From name input "email": "john@doe.com", # From email input "subscribe": "true" # From toggle input (as string) } """ ``` -------------------------------- ### Start Teams Application Lifecycle Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/getting-started/code-basics/typescript.incl.md Starts the Teams application lifecycle. This should be called after setting up event handlers. ```typescript await app.start(); ``` -------------------------------- ### Migrate Bot to Azure with Resource Group Creation and Region Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/docs/cli/commands/app/bot-migrate.md This example demonstrates migrating a bot to Azure Bot Service, including the creation of the resource group if it does not exist and specifying the Azure region. The bot's App ID is a required argument. ```bash teams app bot migrate --subscription --resource-group my-rg --create-resource-group --region eastus ``` -------------------------------- ### Create Teams App with Defaults Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/docs/cli/commands/app/create.md Use this command to create a new Teams app with a bot using default settings. The bot will be Teams-managed and a manifest will be generated. ```bash teams app create --name "My Bot" ``` -------------------------------- ### StarletteAdapter Usage Example Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/in-depth-guides/server/http-server/python.incl.md Illustrates how to integrate the custom StarletteAdapter with the Teams SDK. This involves creating a Starlette application, instantiating the adapter, initializing the Teams app, and preparing for server startup. ```python starlette_app = Starlette() adapter = StarletteAdapter(starlette_app) app = App(http_server_adapter=adapter) await app.initialize() # Start Starlette with uvicorn yourself ``` -------------------------------- ### Install Teams Apps Python Package Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/getting-started/quickstart/python.incl.md Install the necessary Python package for interacting with the Microsoft Teams Apps SDK. ```sh pip install microsoft-teams-apps ``` -------------------------------- ### Apps command test Source: https://github.com/microsoft/teams-sdk/blob/main/packages/cli/agentic-tests.md Lists available apps; requires a successful build and active login session. ```bash node dist/index.js apps ``` -------------------------------- ### Configure App for China Cloud with Tenant Override Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/components/include/essentials/app-configuration/sovereign-cloud/python.incl.md Instantiate the App class for the China sovereign cloud, specifying a login tenant ID using with_overrides. ```python from microsoft_teams.api.auth.cloud_environment import CHINA, with_overrides from microsoft_teams.apps import App app = App(cloud=with_overrides(CHINA, login_tenant="your-tenant-id")) ``` -------------------------------- ### Send Proactive Threaded Message Example Source: https://github.com/microsoft/teams-sdk/blob/main/teams.md/src/pages/templates/essentials/sending-messages/proactive-messaging.mdx This example demonstrates how to send a proactive message as a reply to a specific thread in a channel. ```typescript import { app } from "@microsoft/teams-js"; // Assume conversationId and threadRootMessageId are retrieved from storage const conversationId = "YOUR_STORED_CONVERSATION_ID"; const threadRootMessageId = "YOUR_STORED_THREAD_ROOT_MESSAGE_ID"; // Send a proactive message as a reply to a thread app.reply( { conversationId: conversationId, messageId: threadRootMessageId, text: "This is a proactive reply to a thread." }, (result) => { console.log("Threaded message sent successfully:", result); }, (error) => { console.error("Error sending threaded message:", error); } ); ```