0

我有一个 Bot Framework V3 SDK 实现(工作正常),它可以使用 Microsoft Teams Bot(安装在同一团队中)与特定团队中的任何用户发起 1:1 私人聊天。我在尝试将其迁移到 V4 SDK 时遇到问题。

我阅读了各种文章和其他问题,除非用户首先联系机器人(以避免向用户发送垃圾邮件),否则不可能做到这一点,但这不适用于 V3 版本,也不是我需要的功能的选项.

原始解决方案使用程序集的“ CreateOrGetDirectConversation”扩展方法Microsoft.Bot.Connector.Teams,但在程序集的 V4 版本中不可用。

我尝试使用CreateDirectConversation/CreateDirectConversationAsync方法但没有成功(它们总是导致“错误请求”错误)。

这是使用 V3 库实际工作的代码:

// Create 1:1 conversation
var conversation = connectorClient.Conversations.CreateOrGetDirectConversation(botAccount, user, tenantId);
// Send message to the user
var message = Activity.CreateMessageActivity();
message.Type = ActivityTypes.Message;
message.Text = "My message";
connectorClient.Conversations.SendToConversation((Activity)message, conversation.Id);

而且我发现迁移非常困难。我错过了什么吗?

4

1 回答 1

2

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

只要您的机器人具有通过先前添加到个人、群聊或团队范围中获得的用户信息,机器人就可以与单个 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); 

资源

于 2019-06-11T17:36:43.887 回答