小编典典

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

c#

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

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

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


阅读 669

收藏
2020-07-11

共1个答案

小编典典

更新资料
Bot Framework已添加了特定于Teams的代码,该代码使此答案中的许多代码变得毫无意义或不正确。现在,请参阅此示例 以在团队中发送主动消息。

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

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

机器人可以与单个Microsoft Teams用户创建新的对话,只要您的机器人在个人,groupChat或团队范围内具有通过先前添加获得的用户信息即可。该信息使您的机器人可以主动通知他们。例如,如果您的机器人被添加到团队中,它可以查询团队花名册并在个人聊天中向用户发送个人消息,或者用户可以@提及另一个用户以触发该机器人向该用户发送直接消息。

最简单的方法是通过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); 
2020-07-11