Teams AI Library v2 で Teams アプリを作る
2025/06/20
v2 で作る
https://github.com/microsoft/teams-ai/tree/v2-preview
準備
Prerequisites
- Node.js v20↑
Install the Teams CLI
npm install -g @microsoft/teams.cli@preview
teams <command>
系コマンドはこのCLIを使ってる。グローバルインストールする必要はなくて、都度 npx @microsoft/teams.cli@preview <command>
で実行してもOK。
プロジェクト作成
teams new typescript <アプリ名>
オウム返しするだけのアプリが作成される。
デバッグ
Dev Tool上で動かす
npm run dev
http://localhost:3979/devtools でチャット送ったり、発生したアクティビティを確認できる。ただし、メンションはできないっぽい?
Teams上で動かす
Microsoft 365 Agents Toolkit (VSCode拡張機能)をインストールしておく。
以下のコマンドで設定ファイルを追加する(環境変数追加されたり、マニフェストファイル追加されたり、vscodeでのデバッグ設定追加されたり)
teams config add atk.basic
VSCodeで M365 Agents Toolkit 拡張機能のパネルを開いて、”Accounts” セクションでM365アカウント、Azureアカウントでログインする。
次に、”Environment” セクションで “local” を選んでデバッグを開始する。「Debug(好きなブラウザ)」を選べばOK。
ブラウザでTeamsが立ち上がってくるが、無視してDesktopアプリのTeamsを起動。「アプリ > アプリを管理」から「アプリをアップロード」を選択(ブラウザではなぜか選択できない)
作成したTeamsアプリプロジェクトの appPackage/build/appPackage.local.zip
を選択してアップロード。
後は、チャネルにインストールして使うだけ。オウム返しボットの場合ボット宛にメンションすれば、反応してくれる。
メッセージに反応する
メッセージは Activity の一種で、Activity Router (app.on()
) を使ってハンドリングする。
app.on("message", async ({ activity, send }) => {
await send (`You said: ${activity.text}`);
});
他にもいろいろ Activity はある
メッセージの場合、チャネルではbotに対するメンションが必要。↑のドキュメントでは mention
がアクティビティであるとされているが、このSDKでは、"mention” をアクティビティとしてハンドリングできなかった。
メンション判定
botと1対1(DM)の時はメンションではないので、メンション判定できたほうが便利かもしれない。
activity.entities
にメッセージ内のメンション情報が入っている。こんな感じ?
const isMention = activity.entities && activity.entities.some(entity => entity.type === 'mention');
チャネルかDMかの判定でもいいかも。
DM/チャネル判定
const isDM = activity.conversation.conversationType === 'personal';
型定義間違ってて補完には出てこないが、以下でチャネル判定できる
const isChannel = activity.conversation.conversationType === 'channel'
DMにメッセージを送る
例えば、何らかのアクティビティにトリガしてDMで通知を送るような場合
// メッセージを受け取ったら通知
app.on("message", async ({ activity, api }) => {
const isChannel = activity.conversation.conversationType === "channel"
if (!isChannel) {
return;
}
const conversation = await api.conversations.create({
tenantId: activity.conversation.tenantId,
isGroup: false,
bot: { id: activity.recipient.id },
members: [activity.from]
});
await api.conversations.activities(conversation.id).create({
type: 'message',
text: `チャネルでのメッセージを受信しました: ${activity.text}`,
from: activity.recipient,
recipient: activity.from
});
});
conversationを作って、そのidに対してアクティビティ(メッセージ)を作る。
メッセージリンク
const channelId = activity.channelData?.teamsChannelId || activity.conversation.id.split(';')[0];
const timestamp = activity.timestamp;
const conversationId = activity.converstation.id;
const parentMessageId = conversationId.split(';messageid=')[1];
const groupId = '多分テナント内で固定値?どれでもいいからメッセージリンクコピーして抜き出す';
const messageUrl = `https://teams.microsoft.com/l/message/${channelId}/${activity.id}?tenantId=${activity.conversation.tenantId}&groupId=${groupId}&parentMessageId=${parentMessageId}&createdTime=${timestamp}`;
ユーザーのトークンでGraph APIを使う
認証する必要あり。
基本はドキュメント通りだが、デバッグの過程で、自動的にAzure側にリソースを作成されるので、対象サブスクリプションにリソースを作れる権限が必要。