GitHub

Microsoft Teams

Run a pyfect.chat bot on Microsoft Teams: the adapter, the messaging endpoint that checks Bot Framework tokens, and the capabilities still behind live checks.

pyfect.chat.teams is Effect's @effect/chat-teams, the Microsoft Teams adapter for Chat. teams_chat.layer(app_id=..., tenant_id=..., credentials=...) registers it for one bot in one tenant. It talks to the Bot Framework Connector over HTTP, with no Bot Framework SDK, and needs an HttpClient plus Mac and Digest (pyfect.crypto.native). A thread is teams_chat.thread(conversation_id), the Bot Framework conversation id as it is; a channel thread is the channel's id followed by ;messageid={root}. credentials is the app's client secret, or a function that gets a Connector token for a scope, for certificates or managed identities. The token is cached until five minutes before it expires.

The messaging endpoint

teams_chat.layer_webhook(path=...) adds the bot's messaging endpoint to an HttpRouter. Every request is untrusted until its bearer token checks out: an RS256 JWT signed by a key from Bot Framework's key set that is endorsed for msteams, with Bot Framework's issuer, your app id as audience, an expiry and at most five minutes of clock skew. The token's serviceurl must equal the activity's serviceUrl, the channel must be msteams and the tenant yours. Anything else, including alg: none or an HMAC token, is answered 403. A body over max_body_bytes (1 MiB) is answered 413 and one that is not a JSON object 400, both before the token is read.

The key set is found from Bot Framework's OpenID metadata, fetched with redirects off and read to at most 64 KiB, and its jwks_uri must be on the metadata's own host. When it can't be read the endpoint answers 503, so Teams retries, and waits 30 seconds before fetching it again. A token signed with a key the set does not hold refetches it, at most once every 30 seconds, as Effect's Jwks does: a key Microsoft adds within 30 seconds of the last fetch is refused with 403 until those 30 seconds pass. Token checks use Signature (pyfect.crypto.native.layer_signature).

Verified activities go through teams_chat.normalize to the ChatHandler. A message becomes MessageCreated, with Teams' <at>…</at> text and mentions pointing into it, and a reaction becomes ReactionAdded or ReactionRemoved. When the handler fails NotAccepted, or the request runs past deadline (10 seconds), the endpoint answers 503.

teams_bot.py
import json
import time
from typing import Never, NotRequired, TypedDict
from urllib.parse import urlsplit

import pyfect as fx
from pyfect import layer
from pyfect import schema as S
from pyfect.chat import chat, chat_handler, chat_markdown
from pyfect.chat.chat import Chat
from pyfect.chat.chat_event import ChatEvent, MessageCreated
from pyfect.chat.teams import teams_chat
from pyfect.crypto.native import layer_digest, layer_mac, layer_signature
from pyfect.http import body as http_body
from pyfect.http import client, router
from pyfect.http import request as http_request
from pyfect.http import response as http_response
from pyfect.http.request import HttpClientRequest
from pyfect.jose import jwk, jwt
from pyfect.redacted import make as redacted
from pyfect.redacted import value as reveal

APP_ID = "00000000-0000-0000-0000-0000000000a1"
TENANT_ID = "00000000-0000-0000-0000-0000000000b2"
SERVICE_URL = "https://smba.trafficmanager.net/emea/"
crypto = layer.merge(layer.merge(layer_mac, layer_digest), layer_signature)


# Answers every message in the thread it came from.
def on_event(event: ChatEvent) -> fx.Effect[None, Never, Chat]:
    if not isinstance(event, MessageCreated):
        return fx.void
    reply = chat_markdown.post(event.thread, f"You said: {event.message.text}")
    return reply.as_void().or_die()


# The bot: the messaging endpoint, the adapter and the handler.
app = (
    teams_chat.layer_webhook(path="/api/messages")
    .pipe(layer.provide(chat_handler.layer(on_event)))
    .pipe(
        layer.provide_merge(
            teams_chat.layer(app_id=APP_ID, tenant_id=TENANT_ID, credentials=redacted("secret"))
        )
    )
    .pipe(layer.provide_merge(chat.layer))
)


class Claims(TypedDict):
    iss: str
    aud: str
    exp: int
    serviceurl: NotRequired[str]


# Stands in for Bot Framework here: its key set, Entra's token endpoint and the
# Connector, printing what the bot posts.
def bot_framework(keys: object) -> layer.Layer[client.HttpClient]:
    def answer(request: HttpClientRequest) -> fx.Effect[http_response.HttpClientResponse]:
        url = urlsplit(request.url)
        body: object = {"id": "1800000000002"}
        if url.path.endswith("/openidconfiguration"):
            body = {"jwks_uri": "https://login.botframework.com/v1/.well-known/keys"}
        elif url.path.endswith("/keys"):
            body = keys
        elif url.hostname == "login.microsoftonline.com":
            body = {"access_token": "connector-token", "expires_in": 3600}
        elif isinstance(request.body, http_body.Bytes):
            print("POST", url.path, json.loads(request.body.body)["text"])
        return fx.succeed(http_response.make(request, json.dumps(body)))

    return client.layer_test(answer)


@fx.gen
def program():
    # Bot Framework signs its requests with RS256 keys endorsed for Teams.
    pair = yield from jwk.generate_key_pair("RS256", kid="k1")
    key = yield from jwk.import_private(pair.private_key, "RS256")
    keys = {"keys": [{**pair.public_key, "endorsements": ["msteams"]}]}
    claims: Claims = {
        "iss": "https://api.botframework.com",
        "aud": APP_ID,
        "exp": int(time.time()) + 600,
        "serviceurl": SERVICE_URL,
    }
    token = reveal((yield from jwt.sign(S.Struct(Claims), claims, key)))
    activity = {
        "type": "message",
        "id": "1800000000001",
        "timestamp": "2026-11-15T10:00:00.000Z",
        "serviceUrl": SERVICE_URL,
        "channelId": "msteams",
        "from": {"id": "29:user", "aadObjectId": "user", "name": "User"},
        "recipient": {"id": f"28:{APP_ID}", "name": "Bot"},
        "conversation": {"id": "a:direct", "conversationType": "personal", "tenantId": TENANT_ID},
        "text": "deploy the docs",
    }
    served = app.pipe(layer.provide(bot_framework(keys)))
    http = yield from router.in_memory_client(served)
    body = http_request.post("http://x").body_text(json.dumps(activity), "application/json").body
    url = "http://localhost/api/messages"
    signed = yield from http.post(url, body=body, headers={"authorization": f"Bearer {token}"})
    print("answered", signed.status)
    unsigned = yield from http.post(url, body=body)
    print("unsigned", unsigned.status)


fx.run_blocking(fx.scoped(program).pipe(fx.provide(crypto)).or_die())

What a post sends

A post without buttons is Markdown in text, with every < and & sent as an entity, so no HTML and no <at> mention gets through, and every $ outside code escaped, so Teams reads no math. Mentions notify nobody. A post with buttons is one Adaptive Card. limits.message_length is 44,288: half of the 100 KB Microsoft documents for an activity, less what the card's structure and mention entities can take, and measure prices each character by what escaping makes of it.

Your Markdown is sent as Markdown, so text a user wrote forms syntax inside it: a display name of [x](https://evil.example) is a live link. Put such text through teams_chat.escape_markdown first, within a line, and it shows as typed.

A request Teams answers 429 is retried after its Retry-After, however long Teams asks for, which can be an hour. Pass max_retry_after to teams_chat.layer, such as "1 minute", and a longer wait fails the op at once with RateLimited, its retry_after the wait Teams asked for, so the caller decides.

Capabilities behind live checks

Buttons, modals, commands, start_thread and downloads are off until you turn each on with Unverified(...): their checks against a live tenant have not passed yet. Off, a capability is missing from the descriptor and its op fails Unsupported.

  • buttons needs interaction_keys, HMAC keys with a kid each. A button carries a token signed with the first key and bound to the app, the tenant and the conversation. It is signed, not encrypted: anyone who sees the card can read the id and value.
  • modals opens a dialog from the buttons named in modal_buttons. The dialog's token also binds the user and expires after an hour, and a submit is checked against the modal it signed.
  • commands takes a message only the bot can see as a command: its first word names the command. Commands are answered privately or in public, and follow_up works for 24 hours.

fetch_message, history, opener, replies, files and selects are not supported.

Testing

teams_chat.normalize is a pure function from an activity to events, so captured activities test it directly; it checks no token. For the adapter's writes, provide an HttpClient that answers like the Connector, as the example above does. Effect's conformance suite runs against the adapter this way in pyfect's own tests (chat_test.conformance).

Reference: teams_chat.