Bot Framework (Python)を使ってTeamsのBot作成

カテゴリー:Microsoft投稿日:2024-07-16

とても久しぶりの投稿です。なかなか時間が取れなくて更新できず....

少し前にTeamsのBotを作る機会がありまして、備忘録ついでに載せていきます。

開発環境DocライブラリDocはこちらから。

基本はこれ。

from botbuilder.core import TurnContext, ActivityHandler

class TeamsBot(ActivityHandler);
    async def on_message_activity(self, turn_context: TurnContext):
        # ↓でユーザーの入力が取得できる
        # message = turn_context.activity.text
        return await turn_context.send_activity("こんにちは!質問があればお気軽にどうぞ。")

on_message_activityをオーバーライドしてsend_activityを使うと任意の言葉をbotに話させることができる

大体はこのon_message_activityをを使うことでどうにかできるはず。

そして今回はユーザーに特定の選択をしてもらいたくカードも作成。

こんなjsonを準備。

{
  "$schema": "http://adaptivecards.io/schemas/1.2.0/adaptive-card.json",
  "type": "AdaptiveCard",
  "version": "1.0",
  "body": [
    {
      "type": "TextBlock",
      "text": "会話内容の選択",
      "size": "large",
      "isSubtle": true
    }
  ],
  "actions": [
    {
      "type": "Action.Submit",
      "title": "通常の会話",
      "data": {
        "type": "normal_conversation"
      }
    },
    {
      "type": "Action.Submit",
      "title": "社内情報",
      "data": {
        "type": "secret_info"
      }
    }
  ]
}

そして作ったjsonを開き、これもsend_activityを使って送信すると

from botbuilder.core import TurnContext, ActivityHandler, CardFactory
from botbuilder.schema import Activity, ActivityTypes

class TeamsBot(ActivityHandler):

    async def on_message_activity(self, turn_context: TurnContext): 
        activity = Activity(
                    type=ActivityTypes.message,
                    attachments=[self._create_adaptive_card_attachment()]
                )
        return await turn_context.send_activity(activity)

    def _create_adaptive_card_attachment(self):
        card_path = os.path.join(os.getcwd(), "default_card.json")
        with open(card_path, "rb") as in_file:
            card_data = json.load(in_file)
        return CardFactory.adaptive_card(card_data)

こんなふうにカードを表示させられる。

ちなみにカード内で選択されたものはこんなふうにハンドリングする。

from botbuilder.core import TurnContext, ActivityHandler

class TeamsBot(ActivityHandler);
    async def on_message_activity(self, turn_context: TurnContext):
        user_action = turn_context.activity.value.get("type")
        if user_action == "normal_conversation":
            return await turn_context.send_activity("今日はいい天気ですね。")
        if user_action == "secret_info":
            return awiat turn_context.send_activity("社内情報について回答します。")

ちなみに表示するカードの見た目はここで色々試すことができる。

あとはflaskなりでAPIサーバーたててAWS,GCP,Azureなりでデプロイすれば大体オッケー。よきTeamsライフを。