我有一个 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);
而且我发现迁移非常困难。我错过了什么吗?
根据文档,机器人的主动消息传递:
只要您的 bot 具有通过先前在个人、groupChat 或团队范围中添加获得的用户信息,bot 就可以与单个 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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句