您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

实现通道特定的功能Implement channel-specific functionality

适用于: SDK v4APPLIES TO: SDK v4

某些通道提供无法仅使用消息文本和附件实现的功能。Some channels provide features that cannot be implemented by using only message text and attachments. 若要实现特定于通道的功能,可以将本机元数据传递给活动对象的 通道数据 属性。To implement channel-specific functionality, you can pass native metadata to a channel in the activity object's channel data property. 例如,机器人可使用通道数据属性来指示 Telegram 发送贴纸或指示 Office365 发送电子邮件。For example, your bot can use the channel data property to instruct Telegram to send a sticker or to instruct Office365 to send an email.

本文介绍如何使用消息活动的通道数据属性来实现此通道特定的功能:This article describes how to use a message activity's channel data property to implement this channel-specific functionality:

ChannelChannel 功能Functionality
电子邮件Email 发送和接收包含正文、主题和重要性元数据的电子邮件Send and receive an email that contains body, subject, and importance metadata
SlackSlack 发送全保真的 Slack 消息Send full fidelity Slack messages
FacebookFacebook 本机发送 Facebook 通知Send Facebook notifications natively
TelegramTelegram 执行 Telegram 特定操作,例如共享语音备忘录或贴纸Perform Telegram-specific actions, such as sharing a voice memo or a sticker
KikKik 发送和接收本机 Kik 消息Send and receive native Kik messages

备注

活动对象的通道数据属性的值是 JSON 对象。The value of an activity object's channel data property is a JSON object. 因此,本文中的示例显示了各种方案中 channelData JSON 属性的预期格式。Therefore, the examples in this article show the expected format of the channelData JSON property in various scenarios. 要使用 .NET 创建 JSON 对象,请使用 JObject (.NET) 类。To create a JSON object using .NET, use the JObject (.NET) class.

创建自定义电子邮件Create a custom Email message

若要创建自定义电子邮件,请将活动 channelData 属性设置为包含以下属性的 JSON 对象:To create a custom email message, set the activity channelData property to a JSON object that contains the following properties:

propertiesProperty 说明Description
bccRecipientsbccRecipients 添加到邮件“Bcc(密件抄送)”字段的用分号 (;) 分隔的电子邮件地址字符串。A semicolon (;) delimited string of email addresses to add to the message's Bcc (blind carbon copy) field.
ccRecipientsccRecipients 添加到邮件“Cc(抄送)”字段的用分号 (;) 分隔的电子邮件地址字符串。A semicolon (;) delimited string of email addresses to add to the message's Cc (carbon copy) field.
htmlBodyhtmlBody 用于指定电子邮件正文的 HTML 文档。An HTML document that specifies the body of the email message. 要了解受支持的 HTML 元素和特性,请参阅通道的相关文档。See the channel's documentation for information about supported HTML elements and attributes.
importanceimportance 电子邮件的重要性级别。The email's importance level. 有效值为 high、normal 和 low 。Valid values are high, normal, and low. 默认值为 normal 。The default value is normal.
subjectsubject 电子邮件的主题。The email's subject. 要了解字段要求,请参阅通道的相关文档。See the channel's documentation for information about field requirements.
toRecipientstoRecipients 添加到邮件“收件人”字段的用分号 (;) 分隔的电子邮件地址字符串。A semicolon (;) delimited string of email addresses to add to the message's To field.

用户与机器人之间的传出消息和传入消息可能 channelData 包含一个活动,其中包含上表中指定了其属性的 JSON 对象。The outgoing and incoming messages between the user and the bot may have a channelData activity that contains a JSON object whose properties are specified in the previous table. 下面的代码片段显示 channelData 传入自定义电子邮件消息(从机器人到用户)的属性示例。The snippet below shows an example of the channelData property for an incoming custom email message, from the bot to the user.

propertiesProperty 说明Description
htmlBodyhtmlBody 用于邮件正文的 HTML。The HTML to use for the body of the message.
subjectsubject 用于邮件的主题。The subject to use for the message.
importanceimportance 用于邮件的重要性标志:lownormalhighThe importance flag to use for the message: low, normal, or high.
toRecipientstoRecipients 添加到邮件“收件人”字段的用分号 (;) 分隔的电子邮件地址字符串。A semicolon (;) delimited string of email addresses to add to the message's To field.
ccRecipientsccRecipients 添加到邮件“Cc(抄送)”字段的用分号 (;) 分隔的电子邮件地址字符串。A semicolon (;) delimited string of email addresses to add to the message's Cc (carbon copy) field.
bccRecipientsbccRecipients 添加到邮件“Bcc(密件抄送)”字段的用分号 (;) 分隔的电子邮件地址字符串。A semicolon (;) delimited string of email addresses to add to the message's Bcc (blind carbon copy) field.

创建全保真的 Slack 消息Create a full-fidelity Slack message

若要创建完全保真的 Slack 消息,请将活动对象的通道数据属性设置为 JSON 对象,该对象指定 Slack 消息Slack 附件和/或 Slack 按钮To create a full-fidelity Slack message, set the activity object's channel data property to a JSON object that specifies Slack messages, Slack attachments, and/or Slack buttons.

备注

要使用户能在 Slack 消息中使用按钮,必须在将机器人连接到 Slack 通道时启用“交互式消息” 。To support buttons in Slack messages, you must enable Interactive Messages when you connect your bot to the Slack channel.

此代码片段显示了自定义 Slack 消息的 channelData 属性示例。This snippet shows an example of the channelData property for a custom Slack message.

"channelData": {
   "text": "Now back in stock! :tada:",
   "attachments": [
        {
            "title": "The Further Adventures of Slackbot",
            "author_name": "Stanford S. Strickland",
            "author_icon": "https://api.slack.com/img/api/homepage_custom_integrations-2x.png",
            "image_url": "http://i.imgur.com/OJkaVOI.jpg?1"
        },
        {
            "fields": [
                {
                    "title": "Volume",
                    "value": "1",
                    "short": true
                },
                {
                    "title": "Issue",
                    "value": "3",
                    "short": true
                }
            ]
        },
        {
            "title": "Synopsis",
            "text": "After @episod pushed exciting changes to a devious new branch back in Issue 1, Slackbot notifies @don about an unexpected deploy..."
        },
        {
            "fallback": "Would you recommend it to customers?",
            "title": "Would you recommend it to customers?",
            "callback_id": "comic_1234_xyz",
            "color": "#3AA3E3",
            "attachment_type": "default",
            "actions": [
                {
                    "name": "recommend",
                    "text": "Recommend",
                    "type": "button",
                    "value": "recommend"
                },
                {
                    "name": "no",
                    "text": "No",
                    "type": "button",
                    "value": "bad"
                }
            ]
        }
    ]
}

当用户单击 Slack 消息中的按钮时,机器人将收到一条答复消息,其中的通道数据属性填充了 payload JSON 对象。When a user clicks a button within a Slack message, your bot will receive a response message in which the channel data property is populated with a payload JSON object. payload 对象指定原始消息的内容,标识单击的按钮,并标识单击该按钮的用户。The payload object specifies contents of the original message, identifies the button that was clicked, and identifies the user who clicked the button.

此代码片段显示了当用户单击 Slack 消息中的按钮时,机器人收到的消息中 channelData 属性的示例。This snippet shows an example of the channelData property in the message that a bot receives when a user clicks a button in the Slack message.

"channelData": {
    "payload": {
        "actions": [
            {
                "name": "recommend",
                "value": "yes"
            }
        ],
        . . .
        "original_message": "{…}",
        "response_url": "https://hooks.slack.com/actions/..."
    }
}

机器人可以按常规方式回复此消息,也可以将其答复直接发布到由 payload 对象的 response_url 属性指定的终结点。Your bot can reply to this message in the normal manner, or it can post its response directly to the endpoint that is specified by the payload object's response_url property. 要了解何时以及如何将答复发布到 response_url,请参阅 Slack 按钮For information about when and how to post a response to the response_url, see Slack Buttons.

可使用以下 JSON 创建动态按钮。You can create dynamic buttons using the following JSON.

{
    "text": "Would you like to play a game ? ",
    "attachments": [
        {
            "text": "Choose a game to play!",
            "fallback": "You are unable to choose a game",
            "callback_id": "wopr_game",
            "color": "#3AA3E3",
            "attachment_type": "default",
            "actions": [
                {
                    "name": "game",
                    "text": "Chess",
                    "type": "button",
                    "value": "chess"
                },
                {
                    "name": "game",
                    "text": "Falken's Maze",
                    "type": "button",
                    "value": "maze"
                },
                {
                    "name": "game",
                    "text": "Thermonuclear War",
                    "style": "danger",
                    "type": "button",
                    "value": "war",
                    "confirm": {
                        "title": "Are you sure?",
                        "text": "Wouldn't you prefer a good game of chess?",
                        "ok_text": "Yes",
                        "dismiss_text": "No"
                    }
                }
            ]
        }
    ]
}

若要创建交互式菜单,请使用以下 JSON:To create interactive menus, use the following JSON:

{
    "text": "Would you like to play a game ? ",
    "response_type": "in_channel",
    "attachments": [
        {
            "text": "Choose a game to play",
            "fallback": "If you could read this message, you'd be choosing something fun to do right now.",
            "color": "#3AA3E3",
            "attachment_type": "default",
            "callback_id": "game_selection",
            "actions": [
                {
                    "name": "games_list",
                    "text": "Pick a game...",
                    "type": "select",
                    "options": [
                        {
                            "text": "Hearts",
                            "value": "menu_id_hearts"
                        },
                        {
                            "text": "Bridge",
                            "value": "menu_id_bridge"
                        },
                        {
                            "text": "Checkers",
                            "value": "menu_id_checkers"
                        },
                        {
                            "text": "Chess",
                            "value": "menu_id_chess"
                        },
                        {
                            "text": "Poker",
                            "value": "menu_id_poker"
                        },
                        {
                            "text": "Falken's Maze",
                            "value": "menu_id_maze"
                        },
                        {
                            "text": "Global Thermonuclear War",
                            "value": "menu_id_war"
                        }
                    ]
                }
            ]
        }
    ]
}

创建 Facebook 通知Create a Facebook notification

若要创建 Facebook 通知,请将活动对象的通道数据属性设置为指定以下属性的 JSON 对象:To create a Facebook notification, set the activity object's channel data property to a JSON object that specifies these properties:

propertiesProperty 说明Description
notification_typenotification_type 通知的类型(例如 REGULAR、SILENT_PUSH 和 NO_PUSH) 。The type of notification (e.g., REGULAR, SILENT_PUSH, NO_PUSH).
attachmentattachment 附件(用于指定图像、视频或其他多媒体类型)或模板化附件(如收据)。An attachment that specifies an image, video, or other multimedia type, or a templated attachment such as a receipt.

备注

要详细了解 notification_type 属性和attachment 属性的格式和内容,请参阅 Facebook API 文档For details about format and contents of the notification_type property and attachment property, see the Facebook API documentation.

此代码片段显示了Facebook 收据附件的 channelData 属性示例。This snippet shows an example of the channelData property for a Facebook receipt attachment.

"channelData": {
    "notification_type": "NO_PUSH",
    "attachment": {
        "type": "template"
        "payload": {
            "template_type": "receipt",
            . . .
        }
    }
}

创建 Telegram 消息Create a Telegram message

若要创建实现特定于 Telegram 的操作的消息,例如共享语音备忘录或贴纸,请将活动对象的通道数据属性设置为指定以下属性的 JSON 对象:To create a message that implements Telegram-specific actions, such as sharing a voice memo or a sticker, set the activity object's channel data property to a JSON object that specifies these properties:

propertiesProperty 说明Description
methodmethod 要调用的 Telegram 机器人 API 方法。The Telegram Bot API method to call.
parametersparameters 已指定的方法的参数。The parameters of the specified method.

支持以下 Telegram 方法:These Telegram methods are supported:

  • answerInlineQueryanswerInlineQuery
  • editMessageCaptioneditMessageCaption
  • editMessageReplyMarkupeditMessageReplyMarkup
  • editMessageTexteditMessageText
  • forwardMessageforwardMessage
  • kickChatMemberkickChatMember
  • sendAudiosendAudio
  • sendChatActionsendChatAction
  • sendContactsendContact
  • sendDocumentsendDocument
  • sendLocationsendLocation
  • sendMessagesendMessage
  • sendPhotosendPhoto
  • sendStickersendSticker
  • sendVenuesendVenue
  • sendVideosendVideo
  • sendVoicesendVoice
  • unbanChateMemberunbanChateMember

要详细了解这些 Telegram 方法及其参数,请参阅 Telegram 机器人 API 文档For details about these Telegram methods and their parameters, see the Telegram Bot API documentation.

备注

  • chat_id 参数可通用于所有 Telegram 方法。The chat_id parameter is common to all Telegram methods. 如果未将 chat_id 指定为参数,则框架将为你提供 ID。If you do not specify chat_id as a parameter, the framework will provide the ID for you.
  • 不要内联传递文件内容,而是使用 URL 和媒体类型指定文件,如下面的示例所示。Instead of passing file contents inline, specify the file using a URL and media type as shown in the example below.
  • 在机器人从 Telegram 通道接收的每条消息中,ChannelData 属性都将包含机器人之前发送的消息。Within each message that your bot receives from the Telegram channel, the ChannelData property will include the message that your bot sent previously.

此代码片段显示了一个指定单个 Telegram 方法的 channelData 属性的示例。This snippet shows an example of a channelData property that specifies a single Telegram method.

"channelData": {
    "method": "sendSticker",
    "parameters": {
        "sticker": {
            "url": "https://domain.com/path/gif",
            "mediaType": "image/gif",
        }
    }
}

此代码片段显示了一个指定一组 Telegram 方法的 channelData 属性的示例。This snippet shows an example of a channelData property that specifies an array of Telegram methods.

"channelData": [
    {
        "method": "sendSticker",
        "parameters": {
            "sticker": {
                "url": "https://domain.com/path/gif",
                "mediaType": "image/gif",
            }
        }
    },
    {
        "method": "sendMessage",
        "parameters": {
            "text": "<b>This message is HTML formatted.</b>",
            "parse_mode": "HTML"
        }
    }
]

实现 Telegram 方法时,机器人会收到一条答复消息,其中的通道数据属性填充了 JSON 对象。When a Telegram method is implemented, your bot will receive a response message in which the channel data property is populated with a JSON object. 此响应对象指定原始消息的内容,其中包括 update_id 以及最多一个可选参数。This response object specifies the contents of the original message, including an update_id and, at most, one optional parameter. 若要了解如何接收传入响应,请参阅获取更新For information about receiving incoming responses, see Getting updates.

此代码片段显示了机器人在创建轮询时收到的消息中的 channelData 属性的示例。This snippet shows an example of the channelData property in the message that a bot receives when a poll is created.

"channelData": {
    "update_id": 43517575,
    "message": {
        "message_id": 618,
        "from": {
            "id": 803613355,
            "is_bot": false,
            "first_name": "Joe",
            "last_name": "Doe",
            "username": "jdoe",
            "language_code": "en"
        },
        "chat": {
            "id": 803613355,
            "first_name": "Joe",
            "last_name": "Doe",
            "username": "jdoe",
            "type": "private"
        },
        "date": 1582577834,
        "poll": {
        "id": "5089525250643722242",
        "question": "How to win?",
        "options": [
            {
                "text": "Be the best",
                "voter_count": 0
            },
            {
                "text": "Help those in need",
                "voter_count": 0
            },
            {
                "text": "All of the above",
                "voter_count": 0
            }
        ],
        "total_voter_count": 0,
        "is_closed": false,
        "is_anonymous": true,
        "type": "regular",
        "allows_multiple_answers": false
        }
    }
}

创建本机 Kik 消息Create a native Kik message

若要创建本机 Kik 消息,请将活动对象的通道数据属性设置为指定以下属性的 JSON 对象:To create a native Kik message, set the activity object's channel data property to a JSON object that specifies this property:

propertiesProperty 说明Description
messagesmessages 一组 Kik 消息。An array of Kik messages. 有关 Kik 消息格式的详细信息,请参阅 Kik 消息格式For details about Kik message format, see Kik Message Formats.

此代码片段显示了本机 Kik 消息的 channelData 属性示例。This snippet shows an example of the channelData property for a native Kik message.

"channelData": {
    "messages": [
        {
            "chatId": "c6dd8165…",
            "type": "link",
            "to": "kikhandle",
            "title": "My Webpage",
            "text": "Some text to display",
            "url": "http://botframework.com",
            "picUrl": "http://lorempixel.com/400/200/",
            "attribution": {
                "name": "My App",
                "iconUrl": "http://lorempixel.com/50/50/"
            },
            "noForward": true,
            "kikJsData": {
                    "key": "value"
                }
        }
    ]
}

创建 LINE 消息Create a LINE message

若要创建一条消息以实现特定于 LINE 的消息类型,例如便签、模板或特定于 LINE 的操作类型(例如打开手机摄像头),请将活动对象的通道数据属性设置为可指定 LINE 消息类型和操作类型的 JSON 对象。To create a message that implements LINE-specific message types (such as sticker, templates, or LINE specific action types like opening the phone camera), set the activity object's channel data property to a JSON object that specifies LINE message types and action types.

propertiesProperty 说明Description
typetype LINE 操作/消息类型名称The LINE action/message type name

支持以下 LINE 消息类型:These LINE message types are supported:

  • 便签Sticker
  • ImagemapImagemap
  • 模板(按钮、确认、轮播)Template (Button, confirm, carousel)
  • FlexFlex

以下 LINE 操作可以在消息类型为 JSON 对象的操作字段中指定:These LINE actions can be specified in the action field of the message type JSON object:

  • 回发Postback
  • 消息Message
  • URIURI
  • DatetimerpickerDatetimerpicker
  • 照相机Camera
  • 本机照片Camera roll
  • 位置Location

若要详细了解这些 LINE 方法及其参数,请参阅 LINE 机器人 API 文档For details about these LINE methods and their parameters, see the LINE Bot API documentation.

此代码片段显示的示例介绍了 channelData 属性(用于指定通道消息类型 ButtonTemplate)和 3 个操作类型:相机、cameraRoll、Datetimepicker。This snippet shows an example of a channelData property that specifies a channel message type ButtonTemplate and 3 action types: camera, cameraRoll, Datetimepicker.

"channelData": {
    "type": "ButtonsTemplate",
    "altText": "This is a buttons template",
    "template": {
        "type": "buttons",
        "thumbnailImageUrl": "https://example.com/bot/images/image.jpg",
        "imageAspectRatio": "rectangle",
        "imageSize": "cover",
        "imageBackgroundColor": "#FFFFFF",
        "title": "Menu",
        "text": "Please select",
        "defaultAction": {
            "type": "uri",
            "label": "View detail",
            "uri": "http://example.com/page/123"
        },
        "actions": [{
                "type": "cameraRoll",
                "label": "Camera roll"
            },
            {
                "type": "camera",
                "label": "Camera"
            },
            {
                "type": "datetimepicker",
                "label": "Select date",
                "data": "storeId=12345",
                "mode": "datetime",
                "initial": "2017-12-25t00:00",
                "max": "2018-01-24t23:59",
                "min": "2017-12-25t00:00"
            }
        ]
    }
}

将机器人添加到 TeamsAdding a bot to Teams

添加到团队的机器人将成为另一个团队成员,在聊天过程中可以 @mentioned(提到)它们。Bots added to a team become another team member, who can be @mentioned as part of the conversation. 事实上,机器人只会在 @mentioned 时才接收消息,因此,通道上的其他聊天不会发送到机器人。In fact, bots only receive messages when they are @mentioned, so other conversations on the channel are not sent to the bot. 有关详细信息,请参阅使用 Microsoft Teams 机器人进行通道和组聊天For more information, see Channel and Group chat conversations with a Microsoft Teams bot.

由于组或通道中的机器人只会在消息中被提到 (@botname) 时才做出响应,因此,组通道中的机器人收到的每条消息包含其自身的名称;必须确保消息分析功能可以处理这种情况。Because bots in a group or channel respond only when they are mentioned (@botname) in a message, every message received by a bot in a group channel contains its own name, and you must ensure your message parsing handles that. 此外,机器人还可以分析提到的其他用户,并在其消息中提到用户。In addition, bots can parse out other users mentioned and mention users as part of their messages.

检查和去除 @bot 点名Check for and strip @bot mention


Mention[] m = sourceMessage.GetMentions();
var messageText = sourceMessage.Text;

for (int i = 0;i < m.Length;i++)
{
    if (m[i].Mentioned.Id == sourceMessage.Recipient.Id)
    {
        //Bot is in the @mention list.
        //The below example will strip the bot name out of the message, so you can parse it as if it wasn't included. Note that the Text object will contain the full bot name, if applicable.
        if (m[i].Text != null)
            messageText = messageText.Replace(m[i].Text, "");
    }
}
var text = message.text;
if (message.entities) {
    message.entities
        .filter(entity => ((entity.type === "mention") && (entity.mentioned.id.toLowerCase() === botId)))
        .forEach(entity => {
            text = text.replace(entity.text, "");
        });
    text = text.trim();
}

重要

除非出于测试目的,否则不建议按 GUID 添加机器人。Adding a bot by GUID, for anything other than testing purposes, is not recommended. 这会严重限制机器人的功能。Doing so severely limits the functionality of a bot. 应将生产环境中的机器人作为应用的一部分添加到 Teams。Bots in production should be added to Teams as part of an app. 请参阅创建机器人以及测试和调试 Microsoft Teams 机器人See Create a bot and Test and debug your Microsoft Teams bot.

其他资源Additional resources