PowerAutomate: Teams の Emoticons 解析を返信させて簡易投票に使えるようにする

# 背景
社内講義をした際に、Teams の Poll を利用してアンケートを取ろうとしたんですがやっぱり面倒でした。

> @forms questions? choise1, choise2

みたいにして入力するのも面倒な上、入力ミスなのか動かないときもあった。普段使わないから・・かな。

ってことで、簡単で皆が慣れてる Emoticons を利用して簡易投票が出来るようにしてみよう、と

## 返信イメージ

こんな感じで、スレッド、もしくはチャットに返信させる。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/120072/cc46e337-6d9b-574e-51b3-e29c2ff9521a.png)

#  フロー概要

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/120072/49c0eb68-ebd1-7bb5-c645-e4e1359b384a.png)

以下、個別に説明追記

## 起動UI
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/120072/0df6794b-8445-9e83-6287-1c394f7268dd.png)

```json: 起動UI
{
    "type": "AdaptiveCard",
    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
    "version": "1.3",
    "msteams": {
        "width": "full"
    },
    "body": [
        {
            "type": "TextBlock",
            "text": "いいね解析をします"
        },
        {
            "text": "Cancel は右上の ☒ を",
            "type": "TextBlock",
            "size": "Small",
            "horizontalAlignment": "Right",
            "weight": "Lighter",
            "color": "Accent"
        }
    ]
}
```

## 変数初期化
Reactions の格納用変数の用意
- Channel/Chat で別アクションで取得が必要なので、変数を用意
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/120072/be8ecb5e-2fa9-c3cf-6e3a-71a255e5cc9b.png)

## 残りのアクション

### Reactions 取得
Channel と Chat で取得アクションが違うので、分岐して処理
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/120072/d5e794d9-28fa-aa2e-4117-c26b0fc268f2.png)

判断方法は以下
- ChannelData/Team/Name が null か？
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/120072/81ee37d6-8a0e-249c-2c34-f369819818c0.png)

:::note warn
動的コンテンツで Reactions を拾うと、バグってるので注意
- 下図のように body/temp になってしまうので、 body/reactions へ修正必要
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/120072/cb884b0e-e2d3-db93-4045-b641d4fbdb2d.png)

:::

### Reactions 解析
Reactions （Channel/Chatで同一型）をFilterして、Card 生成時に Length() で集計するだけ
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/120072/2fe9d097-8002-415d-2fb7-3bb6683dde1d.png)

フィルターは、以下
- reactionType で。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/120072/43570795-f056-16a5-536c-36a26c78078f.png)

集計は以下のようにCard生成時に

また、Teams の Emoticons は、[ここで紹介](https://qiita.com/baku2san/items/db24e2cd8760a6c88542)

```json: Card
{
  "type": "AdaptiveCard",
  "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
  "version": "1.4",
  "msteams": {
    "width": "full"
  },
  "body": [
    {
      "type": "ColumnSet",
      "columns": [
        {
          "type": "Column",
          "width": "stretch",
          "items": [
            {
              "type": "ColumnSet",
              "columns": [
                {
                  "type": "Column",
                  "width": "stretch",
                  "items": [
                    {
                      "type": "Image",
                      "url": "https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons/yes/default/20_f.png"
                    },
                    {
                      "type": "TextBlock",
                      "text": "@{length(body('Filter_array_yes'))}",
                      "wrap": true
                    }
                  ]
                },
                {
                  "type": "Column",
                  "width": "stretch",
                  "items": [
                    {
                      "type": "Image",
                      "url": "https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons/heart/default/20_f.png"
                    },
                    {
                      "type": "TextBlock",
                      "text": "@{length(body('Filter_array_heart'))}",
                      "wrap": true
                    }
                  ]
                },
                {
                  "type": "Column",
                  "width": "stretch",
                  "items": [
                    {
                      "type": "Image",
                      "url": "https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons/laugh/default/20_f.png"
                    },
                    {
                      "type": "TextBlock",
                      "text": "@{length(body('Filter_array_laugh'))}",
                      "wrap": true
                    }
                  ]
                },
                {
                  "type": "Column",
                  "width": "stretch",
                  "items": [
                    {
                      "type": "Image",
                      "url": "https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons/surprised/default/20_f.png"
                    },
                    {
                      "type": "TextBlock",
                      "text": "@{length(body('Filter_array_surprised'))}",
                      "wrap": true
                    }
                  ]
                },
                {
                  "type": "Column",
                  "width": "stretch",
                  "items": [
                    {
                      "type": "Image",
                      "url": "https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons/sad/default/20_f.png"
                    },
                    {
                      "type": "TextBlock",
                      "text": "@{length(body('Filter_array_sad'))}",
                      "wrap": true
                    }
                  ]
                },
                {
                  "type": "Column",
                  "width": "stretch",
                  "items": [
                    {
                      "type": "Image",
                      "url": "https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons/angryface/default/20_f.png"
                    },
                    {
                      "type": "TextBlock",
                      "text": "@{length(body('Filter_array_angry'))}",
                      "wrap": true
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}
```

### 解析結果の返信
あとは、Channel/Chat に応じて返信するだけ
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/120072/736514a3-4619-2152-564d-5a0912e583bb.png)

スレッドの場合、返信先はスレッドの親のメッセージIDが必要
- 親の場合は、Message ID そのまま
- 子の場合は、replyToId で、親の Message ID を取得

### 残りのアクションの共有用JSON
クリップボードコピペで、全体をコピペ出来ます。詳細は以下

https://qiita.com/baku2san/items/ad4f7fa744d104b23f50

:::note warn
トリガーと、変数初期化は Scope に含められないので、クリップボードコピペには含まれてないので注意
:::

```json: 残りのアクション
{"id":"6d23eea6-22ba-485c-8f89-b7eaa9bd926f","brandColor":"#8C3900","connectionReferences":{"shared_teams":{"connection":{"id":"/providers/Microsoft.PowerApps/apis/shared_teams/connections/shared-teams-864099d5-54a7-4002-93b6-565ecf481128"}}},"connectorDisplayName":"制御","icon":"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZlcnNpb249IjEuMSIgdmlld0JveD0iMCAwIDMyIDMyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPg0KIDxwYXRoIGQ9Im0wIDBoMzJ2MzJoLTMyeiIgZmlsbD0iIzhDMzkwMCIvPg0KIDxwYXRoIGQ9Im04IDEwaDE2djEyaC0xNnptMTUgMTF2LTEwaC0xNHYxMHptLTItOHY2aC0xMHYtNnptLTEgNXYtNGgtOHY0eiIgZmlsbD0iI2ZmZiIvPg0KPC9zdmc+DQo=","isTrigger":false,"operationName":"Scope","operationDefinition":{"type":"Scope","actions":{"Reactions_取得（Emoticon）":{"type":"Scope","actions":{"ChannelMessage？":{"type":"If","expression":{"not":{"equals":["@triggerBody()?['teamsFlowRunContext']?['channelData']?['team']","@null"]}},"actions":{"Get_message_details_InChannel":{"type":"OpenApiConnection","inputs":{"host":{"connectionName":"shared_teams","operationId":"GetMessageDetails","apiId":"/providers/Microsoft.PowerApps/apis/shared_teams"},"parameters":{"messageId":"@triggerBody()?['teamsFlowRunContext']?['messagePayload']?['id']","threadType":"channel","body/recipient/groupId":"@triggerBody()?['teamsFlowRunContext']?['channelData']?['team']?['aadGroupId']","body/recipient/channelId":"@triggerBody()?['teamsFlowRunContext']?['channelData']?['channel']?['id']","body/recipient/parentMessageId":"@triggerBody()?['teamsFlowRunContext']?['messagePayload']?['replyToId']"},"authentication":{"type":"Raw","value":"@json(decodeBase64(triggerOutputs().headers['X-MS-APIM-Tokens']))['$ConnectionKey']"}},"runAfter":{},"metadata":{"operationMetadataId":"06210aad-f59f-4c39-aae8-8ab53571ea91"}},"Compose":{"type":"Compose","inputs":"@outputs('Get_message_details_InChannel')?['body/reactions']","runAfter":{"Get_message_details_InChannel":["Succeeded"]},"metadata":{"operationMetadataId":"52790c17-d868-4fd1-987e-34c1e138584a"}},"Set_variable":{"type":"SetVariable","inputs":{"name":"Reactions","value":"@outputs('Get_message_details_InChannel')?['body/reactions']"},"runAfter":{"Compose":["Succeeded"]},"metadata":{"operationMetadataId":"284935d6-bd58-44c4-9b4c-07827cad73b8"}}},"runAfter":{},"else":{"actions":{"Get_message_details_InChat":{"type":"OpenApiConnection","inputs":{"host":{"connectionName":"shared_teams","operationId":"GetMessageDetails","apiId":"/providers/Microsoft.PowerApps/apis/shared_teams"},"parameters":{"messageId":"@triggerBody()?['teamsFlowRunContext']?['messagePayload']?['id']","threadType":"groupchat","body/recipient":"@triggerBody()?['teamsFlowRunContext']?['conversation']?['id']"},"authentication":{"type":"Raw","value":"@json(decodeBase64(triggerOutputs().headers['X-MS-APIM-Tokens']))['$ConnectionKey']"}},"runAfter":{},"metadata":{"operationMetadataId":"9dd45887-faf7-4325-8992-b04901a414e3"}},"Set_variable_2":{"type":"SetVariable","inputs":{"name":"Reactions","value":"@outputs('Get_message_details_InChat')?['body/reactions']"},"runAfter":{"Get_message_details_InChat":["Succeeded"]},"metadata":{"operationMetadataId":"ea211d03-6b6a-4620-b691-f35055cdaebe"}}}},"metadata":{"operationMetadataId":"4004a979-97c8-45c6-9fb0-2d3788cff941"}}},"runAfter":{},"metadata":{"operationMetadataId":"cd7790be-db53-4b1b-a50b-f9c043d30fc3"}},"Reactions_解析":{"type":"Scope","actions":{"Filter_array_yes":{"type":"Query","inputs":{"from":"@variables('Reactions')","where":"@equals(item()?['reactionType'], 'like')"},"runAfter":{"Compose_3":["Succeeded"]},"metadata":{"operationMetadataId":"97c83fc7-c9be-4502-8551-dbbe1a1054ca"}},"Filter_array_heart":{"type":"Query","inputs":{"from":"@variables('Reactions')","where":"@equals(item()?['reactionType'], 'heart')"},"runAfter":{"Compose_3":["Succeeded"]},"metadata":{"operationMetadataId":"7c92990a-581e-4c87-9703-f588d1400ac2"}},"Filter_array_laugh":{"type":"Query","inputs":{"from":"@variables('Reactions')","where":"@equals(item()?['reactionType'], 'laugh')"},"runAfter":{"Compose_3":["Succeeded"]},"metadata":{"operationMetadataId":"d0818a23-fc47-44fa-b10e-48b64804b29f"}},"Filter_array_surprised":{"type":"Query","inputs":{"from":"@variables('Reactions')","where":"@equals(item()?['reactionType'], 'surprised')"},"runAfter":{"Compose_3":["Succeeded"]},"metadata":{"operationMetadataId":"67238927-2e93-4558-8b98-4342b9efc26d"}},"Filter_array_sad":{"type":"Query","inputs":{"from":"@variables('Reactions')","where":"@equals(item()?['reactionType'], 'sad')"},"runAfter":{"Compose_3":["Succeeded"]},"metadata":{"operationMetadataId":"63dfac04-af85-4fca-a4e0-e206d3ad3652"}},"Filter_array_angry":{"type":"Query","inputs":{"from":"@variables('Reactions')","where":"@equals(item()?['reactionType'], 'angry')"},"runAfter":{"Compose_3":["Succeeded"]},"metadata":{"operationMetadataId":"12c6cd61-4b5a-44ca-a354-94ec0db9e747"}},"Compose_Card":{"type":"Compose","inputs":{"type":"AdaptiveCard","$schema":"http://adaptivecards.io/schemas/adaptive-card.json","version":"1.4","msteams":{"width":"full"},"body":[{"type":"ColumnSet","columns":[{"type":"Column","width":"stretch","items":[{"type":"ColumnSet","columns":[{"type":"Column","width":"stretch","items":[{"type":"Image","url":"https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons/yes/default/20_f.png"},{"type":"TextBlock","text":"@{length(body('Filter_array_yes'))}","wrap":true}]},{"type":"Column","width":"stretch","items":[{"type":"Image","url":"https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons/heart/default/20_f.png"},{"type":"TextBlock","text":"@{length(body('Filter_array_heart'))}","wrap":true}]},{"type":"Column","width":"stretch","items":[{"type":"Image","url":"https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons/laugh/default/20_f.png"},{"type":"TextBlock","text":"@{length(body('Filter_array_laugh'))}","wrap":true}]},{"type":"Column","width":"stretch","items":[{"type":"Image","url":"https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons/surprised/default/20_f.png"},{"type":"TextBlock","text":"@{length(body('Filter_array_surprised'))}","wrap":true}]},{"type":"Column","width":"stretch","items":[{"type":"Image","url":"https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons/sad/default/20_f.png"},{"type":"TextBlock","text":"@{length(body('Filter_array_sad'))}","wrap":true}]},{"type":"Column","width":"stretch","items":[{"type":"Image","url":"https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons/angryface/default/20_f.png"},{"type":"TextBlock","text":"@{length(body('Filter_array_angry'))}","wrap":true}]}]}]}]}]},"runAfter":{"Filter_array_angry":["Succeeded"],"Filter_array_surprised":["Succeeded"],"Filter_array_laugh":["Succeeded"],"Filter_array_yes":["Succeeded"],"Filter_array_sad":["Succeeded"],"Filter_array_heart":["Succeeded"]},"metadata":{"operationMetadataId":"63b80885-1c4a-4dfe-b50a-e1b0062d346a"}},"Compose_3":{"type":"Compose","inputs":"@variables('Reactions')","runAfter":{},"metadata":{"operationMetadataId":"3e28b804-5e33-47be-bda2-a71c2a09440c"}}},"runAfter":{"Reactions_取得（Emoticon）":["Succeeded"]},"metadata":{"operationMetadataId":"f73d3379-e546-490b-a4fc-fb92bfbf0b4a"}},"結果投稿":{"type":"Scope","actions":{"Condition":{"type":"If","expression":{"not":{"equals":["@triggerBody()?['teamsFlowRunContext']?['channelData']['Team']","@null"]}},"actions":{"Reply_with_adaptive_card_in_a_channel":{"type":"OpenApiConnection","inputs":{"host":{"connectionName":"shared_teams","operationId":"ReplyWithCardToConversation","apiId":"/providers/Microsoft.PowerApps/apis/shared_teams"},"parameters":{"poster":"Flow bot","location":"Channel","body/parentMessageId":"@outputs('replyToId')","body/recipient/groupId":"@triggerBody()?['teamsFlowRunContext']?['channelData']?['team']?['aadGroupId']","body/recipient/channelId":"@triggerBody()?['teamsFlowRunContext']?['channelData']?['channel']?['id']","body/messageBody":"@outputs('Compose_Card')"},"authentication":{"type":"Raw","value":"@json(decodeBase64(triggerOutputs().headers['X-MS-APIM-Tokens']))['$ConnectionKey']"}},"runAfter":{"replyToId":["Succeeded"]},"metadata":{"operationMetadataId":"8600d900-094f-4cc9-9294-aa5f59c17860"}},"replyToId":{"type":"Compose","inputs":"@if(empty(outputs('Get_message_details_InChannel')?['body/replyToId']),outputs('Get_message_details_InChannel')?['body/Id'] ,outputs('Get_message_details_InChannel')?['body/replyToId'])","runAfter":{},"description":"null: 親なので、Id, !null: 親Id"}},"runAfter":{},"else":{"actions":{"Post_adaptive_card_in_a_chat_or_channel":{"type":"OpenApiConnection","inputs":{"host":{"connectionName":"shared_teams","operationId":"PostCardToConversation","apiId":"/providers/Microsoft.PowerApps/apis/shared_teams"},"parameters":{"poster":"Flow bot","location":"Group chat","body/recipient":"@triggerBody()?['teamsFlowRunContext']?['conversation']?['id']","body/messageBody":"@outputs('Compose_Card')"},"authentication":{"type":"Raw","value":"@json(decodeBase64(triggerOutputs().headers['X-MS-APIM-Tokens']))['$ConnectionKey']"}},"runAfter":{},"metadata":{"operationMetadataId":"f1fa9c6b-da04-4149-9896-8870b0f57b05"}}}},"metadata":{"operationMetadataId":"cc1202d5-e154-4abe-b279-982378592833"}}},"runAfter":{"Reactions_解析":["Succeeded"]},"metadata":{"operationMetadataId":"fcfd03b0-ae6e-4948-9bba-032adc98a8c9"}}},"runAfter":{"変数を初期化する":["Succeeded"]},"metadata":{"operationMetadataId":"f3810333-05bf-4a43-a6e2-8323a7efcd24"}}}
```

# 補足
Teams Icons は、以下でまとめてるので、利用したい場合にはどうぞ

https://qiita.com/baku2san/items/db24e2cd8760a6c88542

# あとがき
解析対象の Reactions を起動時に☑ボックスで選ばせようかと思ったが・・
Default で☑させる方法が見つからなかったので選択自体をやめ。

除外を選ぶようにすると意図が反転して間違えやすいかなとも思うしね。

# keyword
how to reply the results of analyzing reactions