更新
Bot Framework 已添加特定于 Teams 的代码,这使得此答案中的许多代码没有实际意义或不正确。现在,请参阅 this sample 在 Teams 中发送主动消息。
Teams 将其称为“主动消息”。只要您获得 Teams 使用的用户 ID,就很容易做到。
根据文档,Proactive messaging for bots:
只要您的 bot 具有通过先前添加到个人、groupChat 或团队范围中获得的用户信息,Bots 就可以与单个 Microsoft Teams 用户创建新对话。此信息使您的机器人能够主动通知他们。例如,如果您的机器人被添加到团队中,它可以查询团队名册并在个人聊天中向用户发送个人消息,或者用户可以@提及另一个用户以触发机器人向该用户发送直接消息。
最简单的方法是通过Microsoft.Bot.Builder.Teams 中间件。
注意:Microsoft.Bot.Builder.Teams 扩展仍处于 V4 的预发布版本中,这就是为什么很难找到它的示例和代码的原因。
添加中间件
在Startup.cs:
var credentials = new SimpleCredentialProvider(Configuration["MicrosoftAppId"], Configuration["MicrosoftAppPassword"]);
services.AddSingleton(credentials);
[...]
services.AddBot<YourBot>(options =>
{
options.CredentialProvider = credentials;
options.Middleware.Add(
new TeamsMiddleware(
new ConfigurationCredentialProvider(this.Configuration)));
[...]
准备你的机器人
在你的主要<YourBot>.cs:
private readonly SimpleCredentialProvider _credentialProvider;
[...]
public <YourBot>(ConversationState conversationState, SimpleCredentialProvider CredentialProvider)
{
_credentialProvider = CredentialProvider;
[...]
发送消息
var teamConversationData = turnContext.Activity.GetChannelData<TeamsChannelData>();
var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl), _credentialProvider.AppId, _credentialProvider.Password);
var userId = <UserIdToSendTo>;
var tenantId = teamConversationData.Tenant.Id;
var parameters = new ConversationParameters
{
Members = new[] { new ChannelAccount(userId) },
ChannelData = new TeamsChannelData
{
Tenant = new TenantInfo(tenantId),
},
};
var conversationResource = await connectorClient.Conversations.CreateConversationAsync(parameters);
var message = Activity.CreateMessageActivity();
message.Text = "This is a proactive message.";
await connectorClient.Conversations.SendToConversationAsync(conversationResource.Id, (Activity)message);
注意:如果需要获取用户ID,可以使用:
var members = (await turnContext.TurnState.Get<IConnectorClient>().Conversations.GetConversationMembersAsync(
turnContext.Activity.GetChannelData<TeamsChannelData>().Team.Id).ConfigureAwait(false)).ToList();
另外,我在测试中不需要这个,但如果你遇到 401 错误,你可能需要trust the Teams ServiceUrl:
MicrosoftAppCredentials.TrustServiceUrl(turnContext.Activity.ServiceUrl);
资源