根据文档,机器人的主动消息传递:
只要您的机器人具有通过先前添加到个人、群聊或团队范围中获得的用户信息,机器人就可以与单个 Microsoft 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 错误,您可能需要信任 Teams ServiceUrl:
MicrosoftAppCredentials.TrustServiceUrl(turnContext.Activity.ServiceUrl);
资源