> ## Documentation Index
> Fetch the complete documentation index at: https://docs.argalabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Test Microsoft Teams bots

> Run a Python bot against a Microsoft twin, approve an Adaptive Card, and exercise synthetic calling controls

Test messaging, Adaptive Card actions, and Graph calling controls with a Microsoft Twin Run. These examples use the Microsoft Teams Python SDK and synthetic identities. You do not need a live Microsoft tenant or access to Arga's server repository.

## 1. Create a bot scenario

Install or update the [Arga CLI](https://docs.argalabs.com/cli-and-mcp.md) to version `0.1.24` or later, then sign in. Save the following as `scenario.json`, then [import the Scenario](https://docs.argalabs.com/twins/seeding.md):

```json scenario.json theme={null}
{
  "name": "Teams bot examples",
  "twins": ["microsoft"],
  "seed_config": {
    "microsoft": {
      "seed": 17,
      "tenants": [{
        "id": "11111111-2222-4333-8444-555555555555",
        "primary_domain": "contoso.onmicrosoft.com",
        "display_name": "Teams Bot Test"
      }],
      "users": [{
        "object_id": "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee",
        "tenant_id": "11111111-2222-4333-8444-555555555555",
        "preferred_username": "ada@contoso.onmicrosoft.com",
        "display_name": "Ada Lovelace"
      }],
      "applications": [{
        "client_id": "22222222-3333-4444-8555-666666666666",
        "object_id": "bbbbbbbb-cccc-4ddd-8eee-ffffffffffff",
        "home_tenant_id": "11111111-2222-4333-8444-555555555555",
        "display_name": "Example bot",
        "sign_in_audience": "AzureADMyOrg",
        "client_secrets": [{"value": "teams-bot-example-secret"}],
        "required_application_permissions": {
          "00000003-0000-0000-c000-000000000000": ["Calls.Initiate.All"]
        }
      }],
      "service_principals": [{
        "object_id": "cccccccc-dddd-4eee-8fff-000000000001",
        "tenant_id": "11111111-2222-4333-8444-555555555555",
        "app_id": "22222222-3333-4444-8555-666666666666",
        "display_name": "Example bot"
      }],
      "consents": [{
        "tenant_id": "11111111-2222-4333-8444-555555555555",
        "client_id": "22222222-3333-4444-8555-666666666666",
        "resource_app_id": "00000003-0000-0000-c000-000000000000",
        "application_roles": ["Calls.Initiate.All"],
        "admin_consent": true
      }],
      "bots": {
        "bots": [{
          "app_id": "22222222-3333-4444-8555-666666666666",
          "tenant_id": "11111111-2222-4333-8444-555555555555",
          "name": "Example bot",
          "delivery_method": "socket",
          "supports_calling": true,
          "calling_endpoint": "https://bot.example.invalid/api/calls"
        }],
        "conversations": [{
          "id": "personal-example",
          "bot_id": "22222222-3333-4444-8555-666666666666",
          "members": ["aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"]
        }]
      }
    }
  }
}
```

```bash theme={null}
arga test-runner scenarios import --file scenario.json
arga twin-runs create --twins microsoft --scenario-id <scenario-id> --wait
```

Replace `<scenario-id>` with the ID returned by the import. Wait until the run is `ready`. Copy the Microsoft `base_url` from the run's status; the examples use its public drop-in URL.

The fixed IDs and password above are synthetic test data. The Graph permission is granted inside the twin only. See the [Microsoft reference](https://docs.argalabs.com/twins/microsoft.md) for other seed fields.

## 2. Configure Python

Use Python 3.12 or later. These examples target Teams SDK `2.2.1`.

```bash theme={null}
python3 -m venv .venv
source .venv/bin/activate
python -m pip install httpx microsoft-teams-api==2.2.1 microsoft-teams-apps==2.2.1

export MICROSOFT_TWIN_BASE_URL="https://YOUR-MICROSOFT-TWIN-HOST"
export BOT_ID="22222222-3333-4444-8555-666666666666"
export BOT_TENANT_ID="11111111-2222-4333-8444-555555555555"
export BOT_PASSWORD="teams-bot-example-secret"
```

Replace the URL with the Microsoft twin's returned `base_url`. Keep these environment variables set in each terminal used below. The SDK uses this public API URL; the inspector uses a separate authenticated URL.

Read the run status:

```bash theme={null}
arga twin-runs status <run-id> --json
```

To open the inspector, append `/ui/bots?token=<proxy_token>` to `twins.microsoft.admin_url`, using the `proxy_token` from the same status response. For example, replace both placeholders in `https://<admin-host>/ui/bots?token=<proxy_token>`. Treat the token and this URL as credentials. The browser exchanges the token for a session cookie.

Do not use the public `base_url` for the inspector: it blocks the control requests that the UI needs.

## 3. Echo messages and approve a card

Save this complete example as `socket_bot.py`. Socket Mode connects outward to the twin, so you do not need to expose a local callback server.

```python socket_bot.py theme={null}
import asyncio
import os

import httpx
from microsoft_teams.api import MessageActivityInput
from microsoft_teams.api.clients import ApiClient
from microsoft_teams.apps.socket_mode.connection import (
    SignalRSocketConnection, SocketConnectionContext,
)
from microsoft_teams.apps.socket_mode.envelope import (
    build_reply_frame, read_envelope_activity,
)
from microsoft_teams.apps.socket_mode.types import SocketConnectionHandlers
from microsoft_teams.common import ClientOptions

TWIN = os.environ["MICROSOFT_TWIN_BASE_URL"].rstrip("/")
BOT = os.environ["BOT_ID"]
TENANT = os.environ["BOT_TENANT_ID"]


async def get_token(scope="https://api.botframework.com/.default"):
    async with httpx.AsyncClient(trust_env=False, timeout=30) as http:
        response = await http.post(
            f"{TWIN}/{TENANT}/oauth2/v2.0/token",
            data={
                "grant_type": "client_credentials",
                "client_id": BOT,
                "client_secret": os.environ["BOT_PASSWORD"],
                "scope": scope,
            },
        )
        response.raise_for_status()
        return response.json()["access_token"]


async def on_activity(envelope):
    activity = read_envelope_activity(envelope)
    result = None
    if activity and activity["type"] == "message":
        api = ApiClient(TWIN, ClientOptions(token=await get_token()))
        card = {
            "type": "AdaptiveCard", "version": "1.5",
            "body": [{"type": "TextBlock", "text": "Approve this request?"}],
            "actions": [{
                "type": "Action.Execute", "title": "Approve", "verb": "approve"
            }],
        }
        await api.conversations.create_activity(
            activity["conversation"]["id"],
            MessageActivityInput(
                text="Echo: " + activity.get("text", ""),
                attachments=[{
                    "contentType": "application/vnd.microsoft.card.adaptive",
                    "content": card,
                }],
            ),
        )
    elif activity and activity.get("name") == "adaptiveCard/action":
        result = {
            "statusCode": 200,
            "type": "application/vnd.microsoft.card.adaptive",
            "value": {
                "type": "AdaptiveCard", "version": "1.5",
                "body": [{"type": "TextBlock", "text": "Approved"}],
            },
        }
    return build_reply_frame(envelope, bot_key=BOT, body=result)


async def main():
    while True:
        closed = asyncio.Event()

        def on_closed(error):
            print("Socket closed; reconnecting:", type(error).__name__, flush=True)
            closed.set()

        connection = SignalRSocketConnection(
            SocketConnectionContext(TWIN + "/v3/websockets/connect", get_token),
            SocketConnectionHandlers(
                on_activity,
                lambda _: print("Socket ready; open the authenticated bot inspector.", flush=True),
                on_closed,
            ),
        )
        try:
            await connection.start()
            await closed.wait()
        except Exception as error:
            print("Connection failed; retrying:", type(error).__name__, flush=True)
        finally:
            await connection.stop()
        await asyncio.sleep(1)


if __name__ == "__main__":
    asyncio.run(main())
```

```bash theme={null}
python socket_bot.py
```

After the terminal prints **Socket ready**:

1. Open the authenticated inspector described above and select **Example bot · personal-example**.
2. Send `Hello Teams` as Ada Lovelace. The bot replies `Echo: Hello Teams` with an approval card.
3. Click **Approve**. The card changes to **Approved**.
4. Check **Delivery history** for successful acknowledgments. Click **Refresh** if the reply has not appeared yet.

The token helper requests a Connector token. The SDK handles socket negotiation, SignalR frames, and acknowledgments. The example creates a fresh connection after a close or connection failure. Keep the bot running while you interact with the inspector.

## 4. Exercise calling controls

Save this as `calling.py` beside `socket_bot.py`. It reuses the token helper, requests a separate Graph token, and creates a synthetic call to the seeded user.

```python calling.py theme={null}
import asyncio

import httpx

from socket_bot import TWIN, get_token

USER = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"


async def main():
    bearer = await get_token("https://graph.microsoft.com/.default")
    async with httpx.AsyncClient(
        base_url=TWIN,
        headers={"Authorization": "Bearer " + bearer},
        trust_env=False,
        timeout=30,
    ) as http:
        created = await http.post("/v1.0/communications/calls", json={
            "callbackUri": "https://bot.example.invalid/api/calls",
            "requestedModalities": ["audio"],
            "mediaConfig": {"@odata.type": "#microsoft.graph.serviceHostedMediaConfig"},
            "targets": [{"identity": {"user": {"id": USER}}}],
        })
        created.raise_for_status()
        path = "/v1.0/communications/calls/" + created.json()["id"]
        try:
            for _ in range(20):
                response = await http.get(path)
                response.raise_for_status()
                if response.json()["state"] == "established":
                    break
                await asyncio.sleep(0.5)
            else:
                raise RuntimeError("Call did not reach established")

            participants = await http.get(path + "/participants")
            participants.raise_for_status()
            print("Participants:", len(participants.json()["value"]))
            for action in ["mute", "unmute", "keepAlive"]:
                response = await http.post(path + "/" + action, json={})
                response.raise_for_status()
                print(action, response.status_code)
        finally:
            ended = await http.delete(path)
            ended.raise_for_status()
            print("Hangup requested:", ended.status_code)


if __name__ == "__main__":
    asyncio.run(main())
```

```bash theme={null}
python calling.py
```

You should see successful participant reads, `200` for the three controls, and `204` for hangup. Call state is visible in the inspector under **Sockets and calls**.

This example checks call state and controls without delivering callbacks. Its `.invalid` callback URL is a placeholder. To test calling notifications, use a reachable HTTPS receiver, validate the twin's signed JWTs, and deliver the queued call events. Socket Mode activity delivery and Graph calling notifications use separate transports.

## Reset and scope

Use [Twin Run reset](https://docs.argalabs.com/features/twin-resets.md) to restore the saved Scenario. Reset removes messages, calls, socket sessions, and pending deliveries; restart the bot after the reset finishes. Stop the bot with **Ctrl+C** and tear down the Twin Run when you finish.

Calling media is synthetic: these examples do not connect to PSTN, capture a microphone, or stream real audio/video. For production bot authentication and SDK behavior, use Microsoft's [Bot Connector authentication guide](https://learn.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-connector-authentication?view=azure-bot-service-4.0) and [Teams SDK](https://microsoft.github.io/teams-sdk/).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.