### Install and Run Bot Source: https://github.com/microsoft/teams.py/blob/main/examples/quoting/README.md Instructions for setting up and running the Teams quoting bot example. Ensure you have the necessary dependencies installed. ```bash cd examples/quoting pip install -e . python src/main.py ``` ```bash uv run python src/main.py ``` -------------------------------- ### Run Reaction Bot Example Source: https://github.com/microsoft/teams.py/blob/main/examples/reactions/README.md Navigate to the example directory, activate the virtual environment, and run the Python script to start the bot. ```bash cd examples/reactions # Activate venv .venv\Scripts\activate python src/main.py ``` -------------------------------- ### Setup MCP Server Source: https://github.com/microsoft/teams.py/blob/main/examples/mcp-server/README.md Install dependencies and configure environment variables for the MCP server. Ensure CLIENT_ID, CLIENT_SECRET, and TENANT_ID are set in the .env file. ```bash uv sync cp .env.example .env # fill in CLIENT_ID, CLIENT_SECRET, TENANT_ID ``` -------------------------------- ### Run Suggested Actions Submit Example Source: https://github.com/microsoft/teams.py/blob/main/examples/suggested-actions/README.md Navigate to the example directory and run the Python bot using `uvicorn`. ```bash cd examples/suggested-actions uv run python src/main.py ``` -------------------------------- ### Run the Targeted Messages Example Source: https://github.com/microsoft/teams.py/blob/main/examples/targeted-messages/README.md Navigate to the example directory and run the Python script using uv. ```bash cd examples/targeted-messages uv run python src/main.py ``` -------------------------------- ### Install Dependencies and Activate Environment Source: https://github.com/microsoft/teams.py/blob/main/CLAUDE.md Commands to synchronize dependencies, activate the virtual environment, and install pre-commit hooks. ```bash uv sync # Install virtual env and dependencies source .venv/bin/activate # Activate virtual environment pre-commit install # Install pre-commit hooks ``` -------------------------------- ### Run Starlette Adapter Example Source: https://github.com/microsoft/teams.py/blob/main/examples/http-adapters/README.md Execute the Starlette adapter example script. This demonstrates a custom adapter for Starlette where the SDK manages the server lifecycle. ```bash python src/starlette_echo.py ``` -------------------------------- ### Set Up Environment Variables Source: https://github.com/microsoft/teams.py/blob/main/examples/proactive-messaging/README.md Configure your application's credentials by setting these environment variables before running the example. ```bash export CLIENT_ID=your_app_id export CLIENT_SECRET=your_app_secret export TENANT_ID=your_tenant_id ``` -------------------------------- ### Scaffold New Package or Example App Source: https://github.com/microsoft/teams.py/blob/main/CLAUDE.md Use cookiecutter to generate new package structures or example applications within the workspace. ```bash cookiecutter templates/package -o packages # New package cookiecutter templates/examples -o examples # New test app ``` -------------------------------- ### Install Nerdbank.GitVersioning CLI Source: https://github.com/microsoft/teams.py/blob/main/RELEASE.md Installs the nbgv CLI tool globally. This is optional for local development but required for publishing releases. ```bash dotnet tool install -g nbgv ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/microsoft/teams.py/blob/main/README.md Use this command to install all development dependencies for the project using the uv package manager. Ensure uv is installed and updated. ```bash uv sync --all-packages --group dev ``` -------------------------------- ### Install Integration Dependencies Source: https://github.com/microsoft/teams.py/blob/main/tests/integration/README.md Installs all project dependencies, including those specifically for the integration group, using UV. ```bash # From repo root — install all deps including integration group uv sync --all-packages --group dev --group integration ``` -------------------------------- ### Run Non-Managed FastAPI Example Source: https://github.com/microsoft/teams.py/blob/main/examples/http-adapters/README.md Execute the non-managed FastAPI example script. This shows how to use the default FastAPI adapter with a user-provided FastAPI instance, where the server lifecycle is managed manually. ```bash python src/fastapi_non_managed.py ``` -------------------------------- ### Run the Stream Test App Source: https://github.com/microsoft/teams.py/blob/main/examples/stream/README.md Execute the main Python script to start the streaming test application. Ensure Python is installed and accessible in your environment. ```bash python src/main.py ``` -------------------------------- ### Install and Login with Teams CLI Source: https://github.com/microsoft/teams.py/blob/main/examples/formatted-messaging/README.md Installs the Teams CLI globally and logs in to your Teams account. This is a prerequisite for managing Teams apps. ```bash npm install -g @microsoft/teams.cli teams --version teams login ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/microsoft/teams.py/blob/main/README.md Install the pre-commit hooks to ensure code quality and consistency before committing changes. This command sets up the necessary hooks. ```bash pre-commit install ``` -------------------------------- ### Start Release Preparation Branch Source: https://github.com/microsoft/teams.py/blob/main/RELEASE.md Creates a new branch for release preparation, starting from the latest main branch. Ensure you have fetched the latest changes from the origin. ```bash git fetch origin git checkout -b /prep-release- origin/main ``` -------------------------------- ### API Usage: Get User Profile Source: https://github.com/microsoft/teams.py/blob/main/packages/graph/README.md A simple example of how to retrieve the current user's profile information using the Graph client. ```python # Get user profile me = await graph.me.get() ``` -------------------------------- ### Run Integration Tests Locally Source: https://github.com/microsoft/teams.py/blob/main/CONTRIBUTING.md Commands to set up the environment and run integration tests locally. Ensure you have the necessary packages installed and environment variables configured. ```bash uv sync --all-packages --group dev --group integration set -a; source tests/integration/.env.botid-prod; set +a pytest tests/integration -v ``` -------------------------------- ### Initialize and Use API Client Source: https://github.com/microsoft/teams.py/blob/main/packages/api/README.md Initialize the ApiClient with the base URL and use it to perform operations like getting bot tokens. ```python from microsoft_teams.api import ApiClient # Initialize API client api = ApiClient("https://smba.trafficmanager.net/amer/") # Bot token operations token_response = await api.bots.token.get(credentials) graph_token = await api.bots.token.get_graph(credentials) # User token operations user_token = await api.users.token.get(params) token_status = await api.users.token.get_status(params) ``` -------------------------------- ### Running the Teams AI Agent Source: https://github.com/microsoft/teams.py/blob/main/examples/ai-mcp/README.md Commands to navigate to the project directory and start the Teams AI Agent using UV. ```bash cd examples/ai-mcp uv run src/main.py ``` -------------------------------- ### Create and Use HTTP Client Source: https://github.com/microsoft/teams.py/blob/main/packages/common/README.md Instantiate an asynchronous HTTP client with custom options like base URL and headers. Make GET and POST requests using the client. ```python from microsoft_teams.common import Client, ClientOptions # Create HTTP client client = Client(ClientOptions( base_url="https://api.example.com", headers={"User-Agent": "Teams-Bot/1.0"} )) # Make requests response = await client.get("/users/me") data = await client.post("/messages", json={"text": "Hello"}) ``` -------------------------------- ### Example Agent Workflow: Ask and Wait for Reply Source: https://github.com/microsoft/teams.py/blob/main/examples/mcp-server/README.md Demonstrates an agent workflow where a question is asked to a user, and the agent waits for a reply. The 'ask' tool returns a request_id, and 'wait_for_reply' polls until an answer is received or a timeout occurs. ```python 1. ask("aad-object-id-of-engineer", "Which region should I deploy to?") → {request_id: "abc"} 2. wait_for_reply("abc", timeout_seconds=30) → server parks; engineer types "East US 2" in Teams and clicks Send → {status: "answered", reply: "East US 2"} ← returns the moment they click 3. agent proceeds with "East US 2" ``` -------------------------------- ### Run the Formatted Messaging Application Source: https://github.com/microsoft/teams.py/blob/main/examples/formatted-messaging/README.md Starts the Python application using the 'uv' command. This command is used to run the local development server for the sample. ```bash uv run python examples/formatted-messaging/src/main.py ``` -------------------------------- ### Install Optional Graph Dependencies Source: https://github.com/microsoft/teams.py/blob/main/packages/apps/README.md Installs the necessary dependencies for Microsoft Graph functionality in the Microsoft Teams Apps Framework using pip or uv. ```bash pip install microsoft-teams-apps[graph] ``` ```bash uv add microsoft-teams-apps[graph] ``` -------------------------------- ### Run Proactive Messaging Example Source: https://github.com/microsoft/teams.py/blob/main/examples/proactive-messaging/README.md Execute the Python script with a conversation ID to send proactive messages. Ensure environment variables are set. ```bash uv run src/main.py ``` -------------------------------- ### Environment Variables Setup Source: https://github.com/microsoft/teams.py/blob/main/examples/quoting/README.md Configuration for the bot requires setting up environment variables in a .env file. Replace placeholders with your actual Azure Bot application credentials. ```env CLIENT_ID= CLIENT_SECRET= TENANT_ID= ``` -------------------------------- ### Run MCP Server Source: https://github.com/microsoft/teams.py/blob/main/examples/mcp-server/README.md Start the MCP server using uvicorn. The bot listens for Teams activity on POST /api/messages and serves the MCP endpoint at http://localhost:3978/mcp. ```bash uv run python src/main.py ``` -------------------------------- ### Create Teams App with CLI Source: https://github.com/microsoft/teams.py/blob/main/examples/formatted-messaging/README.md Creates a new Teams app, specifying the name, the local endpoint for message handling, and environment file. It also outputs configuration details and an install link. ```bash teams app create --name "formatted-messaging" --endpoint "https:///api/messages" --env .env --json ``` -------------------------------- ### Custom HttpServerAdapter Protocol Source: https://github.com/microsoft/teams.py/blob/main/examples/http-adapters/README.md Illustrates the interface for implementing a custom HttpServerAdapter. This includes methods for registering routes, serving static files, and managing the server's start and stop lifecycle. ```python class MyAdapter: def register_route(self, method, path, handler): ... def serve_static(self, path, directory): ... async def start(self, port): ... async def stop(self): ... ``` -------------------------------- ### Configure Regional Bot API Client Settings Source: https://github.com/microsoft/teams.py/blob/main/examples/graph/README.md Update AppOptions to include api_client_settings for regional bot configuration. This example shows setting the OAuth URL for the West Europe region. ```python app = App( default_connection_name='graph', api_client_settings=ApiClientSettings( oauth_url="https://europe.token.botframework.com" ) ) ``` -------------------------------- ### Create a New Test Package with Cookiecutter Source: https://github.com/microsoft/teams.py/blob/main/README.md Use cookiecutter to generate a new test application structure within the 'examples' directory. This is useful for creating sample applications or testing SDK features. ```bash cookiecutter templates/examples -o examples ``` -------------------------------- ### Dynamic Token Fetching with Callable Source: https://github.com/microsoft/teams.py/blob/main/packages/graph/README.md Provides an example of a callable that fetches a fresh token on each invocation. This ensures the Graph client always uses the latest valid token. ```python def get_fresh_token(): """Callable that fetches a fresh token on each invocation.""" # This will be called each time the Graph client needs a token fresh_token = fetch_latest_token_from_api() return fresh_token graph = get_graph_client(get_fresh_token) ``` -------------------------------- ### Bot Token Operations Source: https://github.com/microsoft/teams.py/blob/main/packages/api/README.md Operations related to obtaining tokens for bot interactions. This includes getting a general bot token and a graph token. ```APIDOC ## Bot Token Operations ### Description Operations related to obtaining tokens for bot interactions. This includes getting a general bot token and a graph token. ### Method `api.bots.token.get(credentials)` `api.bots.token.get_graph(credentials)` ### Parameters #### Request Body - **credentials** (Credentials) - Required - Authentication credentials object. ### Response #### Success Response (200) - **token_response** (TokenResponse) - The response containing the bot token. - **graph_token** (GraphTokenResponse) - The response containing the graph token. ``` -------------------------------- ### Configure Version Source with teams-build Source: https://github.com/microsoft/teams.py/blob/main/tools/hatch-teams-build/README.md Specify 'teams-build' as the version source in your pyproject.toml to use Nerdbank.GitVersioning for package versions. This falls back to '0.0.0' if nbgv is not installed, but can be made a hard error by setting NBGV_REQUIRED=1. ```toml [tool.hatch.version] source = "teams-build" ``` -------------------------------- ### User Token Operations Source: https://github.com/microsoft/teams.py/blob/main/packages/api/README.md Operations related to obtaining tokens for user interactions. This includes getting a user token and checking token status. ```APIDOC ## User Token Operations ### Description Operations related to obtaining tokens for user interactions. This includes getting a user token and checking token status. ### Method `api.users.token.get(params)` `api.users.token.get_status(params)` ### Parameters #### Request Body - **params** (dict) - Required - Parameters for the user token operation. ### Response #### Success Response (200) - **user_token** (UserTokenResponse) - The response containing the user token. - **token_status** (TokenStatusResponse) - The response indicating the status of the token. ``` -------------------------------- ### Azure OpenAI Authentication with Service Principal Source: https://github.com/microsoft/teams.py/blob/main/examples/ai-mcp/README.md Example of authenticating to Azure OpenAI using a Service Principal's credentials instead of an API key. This requires granting the Service Principal the 'Azure AI User' role. ```python from azure.identity import ClientSecretCredential client = OpenAIChatClient( model=getenv("AZURE_OPENAI_MODEL"), azure_endpoint=getenv("AZURE_OPENAI_ENDPOINT"), credential=ClientSecretCredential( tenant_id=getenv("TENANT_ID"), client_id=getenv("CLIENT_ID"), client_secret=getenv("CLIENT_SECRET"), ), ) ``` -------------------------------- ### API Usage: Get Recent Emails with Specific Fields Source: https://github.com/microsoft/teams.py/blob/main/packages/graph/README.md Demonstrates how to fetch recent emails for the user, specifying which fields to retrieve and limiting the number of results. This uses the MessagesRequestBuilder for advanced query options. ```python # Get recent emails with specific fields from msgraph.generated.users.item.messages.messages_request_builder import MessagesRequestBuilder query_params = MessagesRequestBuilder.MessagesRequestBuilderGetQueryParameters( select=["subject", "from", "receivedDateTime"], top=5 ) request_config = MessagesRequestBuilder.MessagesRequestBuilderGetRequestConfiguration( query_parameters=query_params ) messages = await graph.me.messages.get(request_configuration=request_config) ``` -------------------------------- ### Build and Inspect Package Metadata Source: https://github.com/microsoft/teams.py/blob/main/tools/hatch-teams-build/README.md Use 'uv build' to create a source distribution (sdist) and then inspect the generated PKG-INFO file to verify that the 'microsoft-teams-*' dependencies have been updated with the correct version specifiers. ```bash uv build packages/apps --sdist # Inspect PKG-INFO — workspace deps should show >= ``` -------------------------------- ### Basic Bot Usage with Graph Client Source: https://github.com/microsoft/teams.py/blob/main/packages/graph/README.md Demonstrates how to create a Graph client using the user's token from the activity context and fetch user profile and joined teams. Ensure the user is signed in before making Graph API calls. ```python from microsoft_teams.graph import get_graph_client from microsoft_teams.apps import App, ActivityContext from microsoft_teams.api import MessageActivity app = App() @app.on_message async def handle_message(ctx: ActivityContext[MessageActivity]): if not ctx.is_signed_in: await ctx.sign_in() return # Create Graph client using user's token graph = get_graph_client(ctx.user_token) # Get user profile me = await graph.me.get() await ctx.send(f"Hello {me.display_name}!") # Get user's Teams teams = await graph.me.joined_teams.get() if teams and teams.value: team_names = [team.display_name for team in teams.value] await ctx.send(f"You're in {len(team_names)} teams: {', '.join(team_names)}") ``` -------------------------------- ### Running the Bots Source: https://github.com/microsoft/teams.py/blob/main/examples/a2a/README.md Commands to launch the Alice and Bob bots using dotenv and uv unicorn. Ensure to run each in a separate terminal. ```bash # Terminal 1 — Alice on port 3978 dotenv -f .env.alice run -- uv run python src/main.py # Terminal 2 — Bob on port 3979 dotenv -f .env.bob run -- uv run python src/main.py ``` -------------------------------- ### Configure and Use SDK Logging Source: https://github.com/microsoft/teams.py/blob/main/packages/common/README.md Configure Python's standard logging module for the SDK. Set the logging level, add a stream handler with a custom formatter, and use module-level loggers. ```python import logging # Configure logging once at application startup logging.getLogger().setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setFormatter(ConsoleFormatter()) logging.getLogger().addHandler(stream_handler) # Use module-level loggers in your code logger = logging.getLogger(__name__) logger.info("Application started") ``` -------------------------------- ### Create Microsoft Graph Client for Delegated Access Source: https://github.com/microsoft/teams.py/blob/main/examples/graph/README.md Create a Graph client using the user's token for delegated access. Requires the user to be signed in. ```python from microsoft_teams.graph import get_graph_client # Delegated access — create Graph client using the user's token graph = get_graph_client(ctx.user_token) me = await graph.me.get() messages = await graph.me.messages.get() ``` -------------------------------- ### Configure Bot Environment Variables Source: https://github.com/microsoft/teams.py/blob/main/examples/reactions/README.md Set up the necessary Azure Bot application ID and secret in a .env file for the bot to authenticate. ```env CLIENT_ID= CLIENT_SECRET= ``` -------------------------------- ### Create Basic Adaptive Card Source: https://github.com/microsoft/teams.py/blob/main/packages/cards/README.md Use this snippet to create a basic Adaptive Card with text and a submit action. Ensure you have imported the necessary components. ```python from microsoft_teams.cards import AdaptiveCard, TextBlock, SubmitAction # Create adaptive card components card = AdaptiveCard( body=[ TextBlock(text="Hello from Teams!") ], actions=[ SubmitAction(title="Click Me", data={"action": "hello"}) ] ) ``` -------------------------------- ### String Token Usage for Graph Client Source: https://github.com/microsoft/teams.py/blob/main/packages/graph/README.md Illustrates the simplest way to provide a token to the Graph client: as a direct string. This is suitable when you have a static token available. ```python # Direct string token graph = get_graph_client("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIs...") ``` -------------------------------- ### Basic Message Handling in Microsoft Teams App Source: https://github.com/microsoft/teams.py/blob/main/packages/apps/README.md Demonstrates setting up a basic Microsoft Teams app and handling incoming text messages. Requires importing App, ActivityContext, and MessageActivity. ```python from microsoft_teams.apps import App, ActivityContext from microsoft_teams.api import MessageActivity app = App() @app.on_message async def handle_message(ctx: ActivityContext[MessageActivity]): await ctx.send(f"You said: {ctx.activity.text}") # Start the app await app.start() ``` -------------------------------- ### Testing MCP Server with Inspector Source: https://github.com/microsoft/teams.py/blob/main/examples/mcp-server/README.md Launch the MCP Inspector to test server interactions. Connect using Streamable HTTP to the /mcp endpoint and test tool calls like 'ask' and 'wait_for_reply'. ```bash npx @modelcontextprotocol/inspector ``` -------------------------------- ### Initialize and Submit Message Extension Settings Source: https://github.com/microsoft/teams.py/blob/main/examples/message-extensions/src/index.html Initializes the Microsoft Teams SDK, retrieves a selected option from URL parameters, and submits the task when the form is submitted. Ensure the Microsoft Teams SDK is loaded before this script. ```javascript microsoftTeams.initialize(); // Get the selectedOption from URL parameters const urlParams = new URLSearchParams(window.location.search); const selectedOption = urlParams.get('selectedOption'); if (selectedOption) { document.getElementById('selectedOption').value = selectedOption; } document.getElementById('settingsForm').addEventListener('submit', function(event) { event.preventDefault(); let selectedValue = document.getElementById('selectedOption').value; microsoftTeams.tasks.submitTask(selectedValue); }); ``` -------------------------------- ### Bob Bot Configuration Source: https://github.com/microsoft/teams.py/blob/main/examples/a2a/README.md Environment variables for configuring the Bob bot, similar to Alice but with Bob's specific identity and peer information. ```dotenv BOT_APP_ID= BOT_APP_PASSWORD= TENANT_ID= BOT_NAME=Bob BOT_DESCRIPTION=Backend and infrastructure specialist — databases, scaling, DevOps BOT_SELF_URL=https:// PEER_NAME=Alice PEER_URL=https:// AZURE_OPENAI_ENDPOINT= AZURE_OPENAI_API_KEY= AZURE_OPENAI_MODEL= PORT=3979 ``` -------------------------------- ### Create a New Package with Cookiecutter Source: https://github.com/microsoft/teams.py/blob/main/README.md Use cookiecutter to generate a new package structure within the 'packages' directory. Follow the prompts to define the package name and directory. ```bash cookiecutter templates/package -o packages ``` -------------------------------- ### Run All Integration Tests Source: https://github.com/microsoft/teams.py/blob/main/tests/integration/README.md Loads environment variables from a .env file and then executes all integration tests using pytest. ```bash # From repo root — load env and run set -a; source tests/integration/.env.botid-prod; set +a pytest tests/integration -v ``` -------------------------------- ### Activate Python Virtual Environment Source: https://github.com/microsoft/teams.py/blob/main/README.md Activate the Python virtual environment before running any project commands. The activation command differs between macOS and Windows. ```bash # On Mac `source .venv/bin/activate` ``` ```bash # On Windows `.venv\Scripts\Activate` ``` -------------------------------- ### Code Formatting and Linting Commands Source: https://github.com/microsoft/teams.py/blob/main/CLAUDE.md Commands for formatting code with Ruff and running linting checks. Use 'poe check' to run both. ```bash poe fmt # Format code with ruff poe lint # Lint code with ruff poe check # Run both format and lint ``` -------------------------------- ### Current Version Configuration (main branch) Source: https://github.com/microsoft/teams.py/blob/main/RELEASE.md This JSON configuration is used on the main branch to define the versioning scheme. Builds on main produce development versions. ```json { "version": "2.0.13-dev.{height}", "versionHeightOffset": 1 } ``` -------------------------------- ### Full Hatchling Configuration with teams-build Source: https://github.com/microsoft/teams.py/blob/main/tools/hatch-teams-build/README.md This configuration sets up Hatchling to use the 'teams-build' plugin for version sourcing and metadata hooks, along with specifying the build requirements. ```toml [build-system] requires = ["hatchling", "hatch-teams-build"] build-backend = "hatchling.build" [tool.hatch.version] source = "teams-build" [tool.hatch.metadata.hooks.teams-build] ``` -------------------------------- ### Create Pull Request for Release Preparation Source: https://github.com/microsoft/teams.py/blob/main/RELEASE.md Pushes the preparation branch to the origin and creates a pull request targeting the 'release' branch. This is the final step in preparing the release branch. ```bash git push -u origin /prep-release- gh pr create --base release --title "Release : merge main into release" ``` -------------------------------- ### Utilize Local Storage Implementations Source: https://github.com/microsoft/teams.py/blob/main/packages/common/README.md Use LocalStorage for key-value data and ListLocalStorage for list data. Supports both synchronous and asynchronous operations. ```python from microsoft_teams.common import LocalStorage, ListLocalStorage # Key-value storage storage = LocalStorage[str]() storage.set("key", {"data": "value"}) data = storage.get("key") # Async operations await storage.async_set("key", {"data": "value"}) data = await storage.async_get("key") # List storage list_storage = ListLocalStorage[str]() list_storage.append("new-item") items = list_storage.items() ``` -------------------------------- ### Token Integration with Callable Source: https://github.com/microsoft/teams.py/blob/main/packages/graph/README.md Shows how to create a callable token that refreshes automatically by returning the current valid user token. This callable can be used to initialize the Graph client. ```python from microsoft_teams.common.http.client_token import Token def create_token_callable(ctx: ActivityContext) -> Token: """Create a callable token that refreshes automatically.""" def get_fresh_token(): # This is called on each Graph API request return ctx.user_token # Always returns current valid token return get_fresh_token # Use with Graph client graph = get_graph_client(create_token_callable(ctx)) # Or, use the user token that's already available in the context graph = get_graph_client(ctx.user_token) ``` -------------------------------- ### Run Tests and Type Checker Source: https://github.com/microsoft/teams.py/blob/main/CLAUDE.md Commands to execute tests using pytest and run the Pyright type checker. ```bash poe test # Run tests with pytest pyright # Run type checker ``` -------------------------------- ### Async Callable Token for Graph Client Source: https://github.com/microsoft/teams.py/blob/main/packages/graph/README.md Shows how to use an asynchronous callable function to provide a token to the Graph client. This is useful for fetching tokens that require an awaitable operation. ```python async def get_token_async(): """Async callable that returns a string token.""" # Fetch token asynchronously token_response = await some_api_call() return token_response.access_token graph = get_graph_client(get_token_async) ``` -------------------------------- ### Client Credentials Authentication Source: https://github.com/microsoft/teams.py/blob/main/packages/api/README.md Use ClientCredentials for authentication with your application's ID and secret. ```python from microsoft_teams.api import ClientCredentials, TokenCredentials # Client credentials authentication credentials = ClientCredentials( client_id="your-app-id", client_secret="your-app-secret" ) ``` -------------------------------- ### Create Draft GitHub Release Source: https://github.com/microsoft/teams.py/blob/main/RELEASE.md Use this command to create a draft release on GitHub. It targets the release branch, sets the title, generates notes based on previous tags, and keeps the release in draft mode. ```bash gh release create v -R microsoft/teams.py \ --target release --title "v" --draft \ --generate-notes --notes-start-tag v ``` -------------------------------- ### Create Teams-Specific Actions Source: https://github.com/microsoft/teams.py/blob/main/packages/cards/README.md This snippet demonstrates how to create various Teams-specific actions like InvokeAction, MessageBackAction, and SignInAction. These actions are used for different interaction types within Teams. ```python from microsoft_teams.cards import InvokeAction, MessageBackAction, SignInAction # Create Teams-specific actions invoke_action = InvokeAction({"action": "getData"}) message_action = MessageBackAction("Send Message", {"text": "Hello"}) signin_action = SignInAction() ``` -------------------------------- ### Create Microsoft Graph Client for App-Only Access Source: https://github.com/microsoft/teams.py/blob/main/examples/graph/README.md Create a Graph client for app-only access, which does not require user sign-in. This is useful for querying organization-wide data. ```python # App-only access — no user sign-in needed graph = app.get_app_graph() users = await graph.users.get() ``` -------------------------------- ### Run Specific Integration Test Case Source: https://github.com/microsoft/teams.py/blob/main/tests/integration/README.md Targets and runs a particular test case, identified by the string 'test_create_activity', within the integration test suite. ```bash # Run a specific test pytest tests/integration -k "test_create_activity" -v ``` -------------------------------- ### Stable Release Version Configuration Source: https://github.com/microsoft/teams.py/blob/main/RELEASE.md This JSON configuration is used when preparing a stable release. Edit version.json before pushing to ensure a plain stable version string without a -dev suffix. ```json { "version": "2.0.0", "versionHeightOffset": 1 } ``` -------------------------------- ### OAuth and Graph Integration for Teams App Source: https://github.com/microsoft/teams.py/blob/main/packages/apps/README.md Shows how to check user sign-in status and access Microsoft Graph data or prompt for sign-in. Handles potential errors during Graph access. ```python @app.on_message async def handle_message(ctx: ActivityContext[MessageActivity]): if ctx.is_signed_in: try: # Access user's Graph data me = await ctx.user_graph.me.get() await ctx.send(f"Hello {me.display_name}!") except (ValueError, RuntimeError, ImportError) as e: await ctx.send(f"Graph access failed: {e}") else: # Prompt user to sign in await ctx.sign_in() ``` -------------------------------- ### Validate and Work with Activity Models Source: https://github.com/microsoft/teams.py/blob/main/packages/api/README.md Use ActivityTypeAdapter to validate incoming activities and then work with typed activities like MessageActivity. ```python from microsoft_teams.api import MessageActivity, Activity, ActivityTypeAdapter # Validate incoming activities activity = ActivityTypeAdapter.validate_python(activity_data) # Work with typed activities if isinstance(activity, MessageActivity): print(f"Message: {activity.text}") ``` -------------------------------- ### Alice Bot Configuration Source: https://github.com/microsoft/teams.py/blob/main/examples/a2a/README.md Environment variables for configuring the Alice bot, including Teams app registration, bot identity, A2A peer information, and LLM settings. ```dotenv # Teams app registration for Alice BOT_APP_ID= BOT_APP_PASSWORD= TENANT_ID= # Bot identity BOT_NAME=Alice BOT_DESCRIPTION=General assistant specialising in front-end development and UX BOT_SELF_URL=https:// # used for the A2A AgentCard URL PEER_NAME=Bob PEER_URL=https:// # A2A CardResolver fetches /.well-known/agent-card.json here # LLM AZURE_OPENAI_ENDPOINT= AZURE_OPENAI_API_KEY= AZURE_OPENAI_MODEL= PORT=3978 ``` -------------------------------- ### Implement Type-Safe Event Emitter Source: https://github.com/microsoft/teams.py/blob/main/packages/common/README.md Create a type-safe event emitter to manage application lifecycle events. Register, emit, and unregister event handlers. ```python from microsoft_teams.common import EventEmitter # Create type-safe event emitter emitter = EventEmitter[str]() # Register handler def handle_message(data: str): print(f"Received: {data}") subscription_id = emitter.on("message", handle_message) # Emit event emitter.emit("message", "Hello World") # Remove handler emitter.off(subscription_id) ``` -------------------------------- ### Environment Variables for Teams AI Agent Source: https://github.com/microsoft/teams.py/blob/main/examples/ai-mcp/README.md Configuration for Azure OpenAI and Teams bot credentials. Ensure to replace placeholders with your actual resource details. ```env AZURE_OPENAI_ENDPOINT=https://.openai.azure.com AZURE_OPENAI_MODEL= AZURE_OPENAI_API_KEY= CLIENT_ID= TENANT_ID= CLIENT_SECRET= ``` -------------------------------- ### Callable Token for Dynamic Token Retrieval Source: https://github.com/microsoft/teams.py/blob/main/packages/graph/README.md Demonstrates using a callable function to provide a token to the Graph client. The callable should return the access token string when invoked. ```python def get_token(): """Callable that returns a string token.""" # Get your access token from wherever (Teams API, cache, etc.) return get_access_token_from_somewhere() # Use the callable with get_graph_client graph = get_graph_client(get_token) ``` -------------------------------- ### Token-Based Authentication Source: https://github.com/microsoft/teams.py/blob/main/packages/api/README.md Use TokenCredentials for authentication when you have a token, such as from a token function. ```python from microsoft_teams.api import ClientCredentials, TokenCredentials # Token-based authentication credentials = TokenCredentials( client_id="your-app-id", token=your_token_function ) ``` -------------------------------- ### Initialize and Submit Form Data Source: https://github.com/microsoft/teams.py/blob/main/examples/dialogs/src/views/customform/index.html Initializes the Microsoft Teams app and adds an event listener to the form. When the form is submitted, it prevents the default submission, collects form data, and submits it using `microsoftTeams.dialog.url.submit`. ```javascript async function init() { await microsoftTeams.app.initialize(); document.getElementById('customForm').addEventListener('submit', function(event) { event.preventDefault(); let formData = { name: document.getElementById('name').value, email: document.getElementById('email').value, submissiondialogtype: 'webpage_dialog' }; microsoftTeams.dialog.url.submit(formData); }); } init(); ``` -------------------------------- ### Configure Metadata Hook with teams-build Source: https://github.com/microsoft/teams.py/blob/main/tools/hatch-teams-build/README.md Enable the 'teams-build' metadata hook in your pyproject.toml to automatically rewrite bare 'microsoft-teams-*' dependencies to include the current version specifier (e.g., '>=2.0.0a49'). This ensures compatibility with sibling packages in published wheels. ```toml [tool.hatch.metadata.hooks.teams-build] ``` -------------------------------- ### Run Specific Integration Test File Source: https://github.com/microsoft/teams.py/blob/main/tests/integration/README.md Executes integration tests located within a specific file, `test_activities.py`, using pytest. ```bash # Run a specific test file pytest tests/integration/test_activities.py -v ``` -------------------------------- ### Configure Bot Scopes in Manifest Source: https://github.com/microsoft/teams.py/blob/main/examples/meetings/README.md Ensure the 'team' and 'groupChat' scopes are included in your bot's configuration within the Teams app manifest to handle meeting events. ```json "bots": [ { "botId": "", "scopes": [ "team", "personal", "groupChat" ], "isNotificationOnly": false } ] ``` -------------------------------- ### Custom Adapter Handler Signature Source: https://github.com/microsoft/teams.py/blob/main/examples/http-adapters/README.md Defines the framework-agnostic signature for handlers used within a custom HttpServerAdapter. It specifies the expected structure for incoming requests and outgoing responses. ```python async def handler(request: HttpRequest) -> HttpResponse: # request = { "body": dict, "headers": dict } # return { "status": int, "body": object } ``` -------------------------------- ### Access App-Only Graph Client via Context Source: https://github.com/microsoft/teams.py/blob/main/examples/graph/README.md Alternatively, access the app-only Graph client directly through the context object. This also does not require user sign-in. ```python # Or via context users = await ctx.app_graph.users.get() ``` -------------------------------- ### Configure Resource-Specific Permissions in Manifest Source: https://github.com/microsoft/teams.py/blob/main/examples/meetings/README.md Specify the necessary resource-specific application permissions in the authorization section of your Teams app manifest to read meeting data. ```json "authorization":{ "permissions":{ "resourceSpecific":[ { "name":"OnlineMeetingParticipant.Read.Chat", "type":"Application" }, { "name":"ChannelMeeting.ReadBasic.Group", "type":"Application" }, { "name":"OnlineMeeting.ReadBasic.Chat", "type":"Application" } ] } } ``` -------------------------------- ### Generate Release Notes from Merged PRs Source: https://github.com/microsoft/teams.py/blob/main/RELEASE.md This command queries GitHub API for merged pull requests in the main branch since a specified date. It formats the output to list PR titles and authors, suitable for pasting into release notes. Note: macOS users may need to adapt the `tac` command. ```bash # Note: macOS has no `tac` — the awk one-liner below works everywhere gh api -X GET search/issues \ -f q='repo:microsoft/teams.py is:pr is:merged base:main merged:>=' \ --jq '.items[] | "* \(.title) by @\(.user.login) in \(.html_url)"' \ | awk '{ a[NR] = $0 } END { for (i = NR; i >= 1; i--) print a[i] }' \ > /tmp/notes.md ``` -------------------------------- ### Merge Release Branch into Preparation Branch Source: https://github.com/microsoft/teams.py/blob/main/RELEASE.md Merges the existing release branch into your preparation branch using the 'ours' strategy. This records the release branch as a parent without incorporating its content, preserving the main branch's tree. ```bash git merge -s ours origin/release -m "Release : merge main into release" ``` -------------------------------- ### Commit Version Update in version.json Source: https://github.com/microsoft/teams.py/blob/main/RELEASE.md Updates the version.json file to reflect the stable release version and commits the change. This step is crucial for version management. ```bash git add version.json git commit -m "Release : set version to stable" ``` -------------------------------- ### Suppress Experimental API Warning Source: https://github.com/microsoft/teams.py/blob/main/examples/suggested-actions/README.md This code suppresses the `ExperimentalTeamsSuggestedAction` warning for experimental APIs. Remove this opt-in when the API stabilizes. ```python import warnings warnings.filterwarnings("ignore", category=ExperimentalWarning, message=".*ExperimentalTeamsSuggestedAction.*") ``` -------------------------------- ### Apply Custom Filtering to Console Handler Source: https://github.com/microsoft/teams.py/blob/main/packages/common/README.md Add a custom filter to a console stream handler to control which log messages are displayed based on the logger name. ```python stream_handler.addFilter(ConsoleFilter("microsoft_teams.*")) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.