訓練
模組
使用適用於 Visual Studio Code 的 Teams 工具組建置 Bot - Training
Bot 通常稱為聊天機器人,會使用交談式介面,使用者可以藉由傳送和接收包含文字或互動式卡片的訊息來與其互動。 Bot 具有高度彈性,而且可透過許多方式使用,例如主動傳送訊息、在指示時執行動作,以及執行多步驟工作流程。 Bot 也可用於許多Microsoft Teams 內容、個人 Bot、一對一或群組聊天、Teams 頻道交談或 Teams 會議聊天。
重要
The code samples in this section are based on version 4.6 and later versions of the Bot Framework SDK. If you are looking for documentation for earlier versions, see the bots - v3 SDK section in the Legacy SDKs folder of the documentation.
A proactive message is any message sent by a bot that isn't in response to a request from a user. This message can include content, such as:
重要
To send proactive message, it's recommended to start with building notification bot with JavaScript or incoming webhook notification sample. To get started, download Teams Toolkit explore. For more information, see Teams Toolkit documents.
Bots are available in Government Community Cloud (GCC), GCC High, Department of Defense (DoD), and Teams operated by 21Vianet environments. For proactive messages, the bots must use the following end points for government cloud environments:
- GCC: https://smba.infra.gcc.teams.microsoft.com/teams
- GCC High: https://smba.infra.gov.teams.microsoft.us/teams
- DoD: https://smba.infra.dod.teams.microsoft.us/teams
To send a proactive message to a user, a group chat, or a team, your bot must have the requisite access to send the message. For a group chat or team, the app that contains your bot must be first installed in that location.
You can proactively install your app using Microsoft Graph in a team, if necessary, or use a custom app policy to install an app in your teams and for organization's users. For certain scenarios, you must proactively install your app using Graph. For a user to receive proactive messages, install the app for the user or make the user a part of a team in which the app is installed.
Sending a proactive message is different from sending a regular message. There's no active turnContext
to use for a reply. You must create the conversation before sending the message. For example, a new one-on-one chat or a new conversation thread in a channel. You can't create a new group chat or a new channel in a team with proactive messaging.
To send a proactive message, follow these steps:
The code snippets in the samples section are to create a one-on-one conversation. For links to samples for both one-on-one conversations and group or channels messages, see code sample. To use proactive messages effectively, see best practices for proactive messaging.
You can create a new conversation with a user or a conversation thread in a channel and you must have the correct ID. You can receive or retrieve this ID using any of the following ways:
onMembersAdded
activity.onMembersAdded
activity.Regardless of how you get the information, store the tenantId
and then store either the userId
, or channelId
to create a new conversation. You can also use the teamId
to create a new conversation thread in the general or default channel of a team. Ensure that the bot is installed in the team before you can send a proactive message to a channel.
The aadObjectId
is unique to the user and can be retrieved using the graph API to create a new conversation in personal chat. Ensure that the bot is installed in the personal scope before you can send a proactive message. If the bot isn't installed in a personal scope when sending a proactive message using the aadObjectId
, the bot returns a 403
error with ForbiddenOperationException
message.
The userId
is unique to your bot ID and a particular user. You can't reuse the userId
between bots.
The channelId
is global.
Create the conversation, after you have the user or channel information.
注意
Sending proactive messages using aadObjectId
is supported only in personal scope.
You can create the conversation if it doesn't exist, or you don't know the conversationId
. Create the conversation only once and store the conversationId
value or conversationReference
object.
To create the conversation, you need a aadObjectId
or userId
, tenantId
, and serviceUrl
.
For serviceUrl
, use the value from an incoming activity triggering the flow or one of the global service URLs. If the serviceUrl
isn't available from an incoming activity triggering the proactive scenario, use the following global URL endpoints:
https://smba.trafficmanager.net/teams/
https://smba.infra.gcc.teams.microsoft.com/teams
https://smba.infra.gov.teams.microsoft.us/teams
https://smba.infra.dod.teams.microsoft.us/teams
For a code sample, see the call CreateConversationAsync
in the sample.
You can get the conversation when the app is installed for the first time. After the conversation is created, get the conversation ID. The conversationId
is available in the conversation update events.
The conversation ID is unique for each bot within a specific channel, even in a multitenant environment. This ID ensures that the bot's messages are directed to the appropriate channel and doesn't interrupt with other bots or channels within the same or across different organizations.
If you don't have the conversationId
, you can proactively install your app using Graph to get the conversationId
.
Use either the conversationReference
object or conversationId
and tenantId
to send the message. You can get this ID by either creating the conversation or storing it from any activity sent to you from that context. Store this ID for reference.
After you get the appropriate address information, you can send your message.
Now that you have the right address information, you can send your message. If you're using the SDK, you must use the continueConversation
method, and the conversationId
and tenantId
to make a direct API call. To send your message, set the conversationParameters
. See the samples section or use one of the samples listed in the code sample section.
注意
Teams doesn't support sending proactive messages using email or User Principal Name (UPN).
Now that you've sent the proactive message, you must follow these best practices while sending proactive messages for better information exchange between users and the bot.
See the following video to learn how to send proactive message from bots:
As a developer, you can create a report to understand which users in your organization have blocked, muted, or uninstalled a bot. This information might help your organization's admins to broadcast org-wide messages or drive app usage.
Using Teams, you can send a proactive message to the bot to verify if a user has blocked or uninstalled a bot. If the bot is blocked or uninstalled, Teams returns a 403
response code with a subCode: MessageWritesBlocked
. This response indicates that the message sent by the bot isn't delivered to the user.
The response code is sent on a per-user basis and includes the identity of the user. You can compile the response codes for each user alongside their identity to create a report of all users who have blocked the bot.
The following code sample is an example of a 403 response code:
HTTP/1.1 403 Forbidden
Cache-Control: no-store, must-revalidate, no-cache
Pragma: no-cache
Content-Length: 196
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Strict-Transport-Security: max-age=31536000; includeSubDomains
MS-CV: NXZpLk030UGsuHjPdwyhLw.5.0
ContextId: tcid=0,server=msgapi-canary-eus2-0,cv=NXZpLk030UGsuHjPdwyhLw.5.0
Date: Tue, 29 Mar 2022 17:34:33 GMT
{"errorCode":209,"message":"{\r\n \"subCode\": \"MessageWritesBlocked\",\r\n \"details\": \"Thread is blocked from message writes.\",\r\n \"errorCode\": null,\r\n \"errorSubCode\": null\r\n}"}
Sending proactive messages to the users is an effective way to communicate with your users. However, from the user's perspective, the message appears unprompted. If there's a welcome message, it marks their first interaction with your app. It's important to use this functionality and provide the complete information to the user to understand the purpose of this message.
When proactive messaging is used to send a welcome message to a user, there's no context for why the user receives the message. Also, this is the first interaction of the user with your app. It's an opportunity to create a good first impression. A good user experience ensures better adoption of the app. Poor welcome messages can lead the users to block your app. Write a clear welcome message and iterate on the welcome message if it isn't having the desired effect.
A good welcome message can include the following information:
Reason for the message - It must be clear to the user why they're receiving the message. If your bot was installed in a channel and you sent a welcome message to all users, then let them know what channel it was installed in and who installed it.
Your offer - Users must be able to identify what they can do with your app and what value can you bring to them.
Next steps - Users should understand the next steps. For example, invite users to try out a command or interact with your app.
To send notifications using proactive messaging, ensure your users have a clear path to take common actions based on your notification. If user actions are required in a tab app, use activity feed notifications instead of a bot. Ensure users have a clear understanding of why they've received a notification. Good notification messages include the following items:
What happened? A clear indication of what happened to cause the notification.
What was the result? It must be clear, what item is updated to get the notification.
Who or what triggered it? Who or what took action which caused the notification to be sent.
What can users do in response? Make it easy for your users to take actions based on your notifications.
How can users opt-out? You must provide a path for users to opt-out of more notifications.
To send messages to a large group of users, for example to your organization, proactively install your app using Graph.
To update or delete a proactive message sent by a notification only bot:
Keep track of the sent messages by storing their message IDs or conversation references when sending the proactive message.
Use UpdateActivityAsync
or DeleteActivityAsync
methods to update or delete the original message.
When using proactive messaging to send scheduled messages to users, verify that your time zone is updated to their time zone. This ensures that the messages are delivered to the users at the relevant time. Schedule messages include:
Why is the user receiving the message? Make it easy for your users to understand the reason for which they're receiving the message.
What can user do next? Users can take the required action based on the message content.
Proactively message users that have previously not installed or interacted with your app. For example, you want to use the company communicator to send messages to your entire organization. In this case, you can use the Graph API to proactively install your app for your users. Cache the necessary values from the conversationUpdate
event your app receives upon installation.
You can only install apps that are in your organizational app catalog or the Microsoft Teams Store.
See install apps for users in the Graph documentation and proactive bot installation and messaging in Teams with Graph. There's also a Microsoft .NET framework sample on the GitHub platform.
Ensure that you authenticate and have a bearer token before creating a new conversation using the REST API. The following are REST API to create a conversation in different contexts:
REST API to Update message in conversation: To update an existing activity within a conversation, include the conversationId and activityId in the request endpoint. To complete this scenario, you must cache the activity ID returned by the original post call.
PUT {Service URL of your bot}/v3/conversations/{conversationId}/activities/{activityId}
{
"type": "message",
"text": "This message has been updated"
}
To update an existing activity within a conversation, include the conversationId
and activityId
in the request endpoint. To complete this scenario, you must cache the activity ID
returned by the original post call.
If the call succeeds, the API returns with the following response object.
{
"id": "{{activityID}}"
}
The following code shows how to send proactive messages:
[Route("api/notify")]
[ApiController]
public class NotifyController : ControllerBase
{
private readonly IBotFrameworkHttpAdapter _adapter;
private readonly string _appId;
private readonly ConcurrentDictionary<string, ConversationReference> _conversationReferences;
public NotifyController(IBotFrameworkHttpAdapter adapter, IConfiguration configuration, ConcurrentDictionary<string, ConversationReference> conversationReferences)
{
_adapter = adapter;
_conversationReferences = conversationReferences;
_appId = configuration["MicrosoftAppId"] ?? string.Empty;
}
public async Task<IActionResult> Get()
{
foreach (var conversationReference in _conversationReferences.Values)
{
var newReference = new ConversationReference()
{
Bot = new ChannelAccount()
{
Id = conversationReference.Bot.Id
},
Conversation = new ConversationAccount()
{
Id = conversationReference.Conversation.Id
},
ServiceUrl = conversationReference.ServiceUrl,
};
// Sends a proactive message from the bot to a conversation.
await ((BotAdapter)_adapter).ContinueConversationAsync(_appId, newReference, BotCallback, default(CancellationToken));
}
// Let the caller know proactive messages have been sent.
return new ContentResult()
{
Content = "<html><body><h1>Proactive messages have been sent.</h1></body></html>",
ContentType = "text/html",
StatusCode = (int)HttpStatusCode.OK,
};
}
private async Task BotCallback(ITurnContext turnContext, CancellationToken cancellationToken)
{
// If you encounter permission-related errors when sending this message, see
// https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-howto-proactive-message?view=azure-bot-service-4.0&tabs=csharp#avoiding-401-unauthorized-errors
// Sends an activity to the sender of the incoming activity.
await turnContext.SendActivityAsync("proactive hello");
}
}
Example of a code snippet to demonstrate creating conversation reference.
var newReference = new ConversationReference()
{
Bot = new ChannelAccount()
{
Id = conversationReference.Bot.Id
},
Conversation = new ConversationAccount()
{
Id = conversationReference.Conversation.Id
},
ServiceUrl = conversationReference.ServiceUrl,
};
The following table provides a simple code sample that incorporates basic conversation flow into a Teams application and how to create a new conversation thread in a channel in Teams:
Sample Name | Description | .NET | Node.js | Python | Manifest |
---|---|---|---|---|---|
Teams Conversation Basics | This sample app shows how to use different bot conversation events available in bot framework v4 for personal and teams scope. | View | View | View | View |
Start new thread in a channel | This sample shows how to start a thread in a specific Team's channel using Bot Framework v4. | View | View | View | View |
Proactive installation of app and sending proactive notifications | This sample shows how you can use proactive installation of app for users and send proactive notifications by calling Microsoft Graph APIs. | View | View | NA | View |
Proactive Messaging | This is a sample that shows how to save user's conversation reference information to send proactive reminder message using Bots. | View | View | NA |
訓練
模組
使用適用於 Visual Studio Code 的 Teams 工具組建置 Bot - Training
Bot 通常稱為聊天機器人,會使用交談式介面,使用者可以藉由傳送和接收包含文字或互動式卡片的訊息來與其互動。 Bot 具有高度彈性,而且可透過許多方式使用,例如主動傳送訊息、在指示時執行動作,以及執行多步驟工作流程。 Bot 也可用於許多Microsoft Teams 內容、個人 Bot、一對一或群組聊天、Teams 頻道交談或 Teams 會議聊天。
文件
Teams Specific Context for Bot - Teams
Get Teams specific context for your bot, fetch user profile, get single member, team's, list of channels in a team details. Sample on create a new channel thread.
Send and receive messages with a bot - Teams
In this module, learn to have a conversation with a Microsoft Teams bot, Proactive messages, Conversation basics, Message content and formatting
Send notifications with a Bot - Teams
Learn about sending notifications using a bot app