我的 Teams 机器人如何与已知用户开始新的 1:1 聊天



我正在开发一个 Teams 机器人,该机器人需要能够与已知用户(即我们知道团队用户 ID)开始新的 1:1 对话。

我已经查看了GitHub(https://github.com/OfficeDev/microsoft-teams-sample-complete-csharp)上的"完整"OfficeDev示例以及Graph API的Teams相关部分,但我没有看到任何开始新对话的功能。

我们的目标是通过邀请已知用户进行 1:1 聊天并请求他们的反馈,让我们的机器人按计划对已知用户进行 ping 操作。机器人消息中的按钮将显示反馈表单(通过任务模块)。

更新

机器人框架添加了特定于 Teams 的代码,这使得此答案中的许多代码没有实际意义或不正确。现在,请参阅此示例,了解如何在 Teams 中发送主动消息。

团队将其称为"主动消息"。只要获取 Teams 使用的用户 ID,就很容易做到。

根据文档,机器人的主动消息传递:

只要机器人具有通过以前在个人、群聊或团队范围中添加的用户信息,机器人就可以与单个 Microsoft Teams 用户创建新对话。此信息使机器人能够主动通知他们。例如,如果机器人已添加到团队,它可以查询团队名单并在个人聊天中向用户发送个人消息,或者用户可以@mention其他用户来触发机器人向该用户发送直接消息。

最简单的方法是通过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 错误,您可能需要信任 Teams ServiceUrl:

MicrosoftAppCredentials.TrustServiceUrl(turnContext.Activity.ServiceUrl); 

资源

  • MyGet 上的团队扩展
  • 团队扩展 MyGet 包存储库
  • 使用扩展的示例
  • 主动团队示例
  • 有用的非官方博客文章

相关内容

最新更新