如果您有ConversationReference,是否可以从C#中的json的HTTP POST发送主动消息?
附加了ConversationReference的JSON POST主体将类似于以下内容。
[{ "message" : "Test message"},{"activityId":"4bead591-de0b-11e9-b5cf-dd1a7b37f8bc","user":{"id":"011e42cf-60ab-47e1-89af-6b698c383d54","name":"User","aadObjectId":null,"role":null},"bot":{"id":"8b9e0710-9ef5-11e9-9393-8929068282f7","name":"Bot","aadObjectId":null,"role":"bot"},"conversation":{"isGroup":null,"conversationType":null,"id":"4b67a140-de0b-11e9-8c9e-e7efbea8c8c9|livechat","name":null,"aadObjectId":null,"role":null,"tenantId":null},"channelId":"emulator","serviceUrl":"http://localhost:54673"}]
答案 0 :(得分:2)
是的,我所有的代码都基于this official demo。
用以下代码替换NotifyController.cs
中的所有内容:
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Integration.AspNet.Core;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Configuration;
namespace ProactiveBot.Controllers
{
[Route("api/notify/{userid?}")]
[ApiController]
public class NotifyController : ControllerBase
{
private readonly IBotFrameworkHttpAdapter _adapter;
private readonly string _appId;
private readonly ConcurrentDictionary<string, ConversationReference> _conversationReferences;
public NotifyController(IBotFrameworkHttpAdapter adapter, IConfiguration configuration, ConcurrentDictionary<string, ConversationReference> conversationReferences)
{
_adapter = adapter;
_conversationReferences = conversationReferences;
_appId = configuration["MicrosoftAppId"];
// If the channel is the Emulator, and authentication is not in use,
// the AppId will be null. We generate a random AppId for this case only.
// This is not required for production, since the AppId will have a value.
if (string.IsNullOrEmpty(_appId))
{
_appId = Guid.NewGuid().ToString(); //if no AppId, use a random Guid
}
}
public async Task<IActionResult> Post(string userid,[FromBody] NotifyMessage notifyMessage)
{
if (string.IsNullOrEmpty(userid))
{
foreach (var conversationReference in _conversationReferences.Values)
{
await ((BotAdapter)_adapter).ContinueConversationAsync(_appId, conversationReference, (ITurnContext turnContext, CancellationToken cancellationToken) => turnContext.SendActivityAsync(notifyMessage.message), default(CancellationToken));
}
}
else {
_conversationReferences.TryGetValue(userid,out var conversationReference);
await ((BotAdapter)_adapter).ContinueConversationAsync(_appId, conversationReference, (ITurnContext turnContext, CancellationToken cancellationToken) => turnContext.SendActivityAsync(notifyMessage.message), default(CancellationToken));
}
// Let the caller know proactive messages have been sent
return new ContentResult()
{
Content = "<html><body><h1>Proactive messages have been sent:"+ userid + "</h1></body></html>",
ContentType = "text/html",
StatusCode = (int)HttpStatusCode.OK,
};
}
}
public class NotifyMessage
{
public string message { get; set; }
}
}
好吧,如果您想向机器人发布一个http请求以发送通知,请尝试使用c#代码中的以下代码:
var request = (HttpWebRequest)WebRequest.Create("http://localhost:3978/api/notify"); //change the request url as your bot endpoint if you use it on Azure
request.Method = "POST";
request.ContentType = "application/json";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
var postData = "{\"message\":\"hello! this is a test message from a notify \"}";
streamWriter.Write(postData);
streamWriter.Flush();
streamWriter.Close();
}
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
如果只想向一个用户发送通知,则可以在请求URL中指定用户ID,如下代码:
var request = (HttpWebRequest)WebRequest.Create("http://localhost:3978/api/notify/139dbd54-5bc9-4995-8589-a219fcd8ba8a"); //139dbd54-5bc9-4995-8589-a219fcd8ba8a is userid,you can find it in your conversationReference
request.Method = "POST";
request.ContentType = "application/json";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
var postData = "{\"message\":\"hello! this is a test message from a notify \"}";
streamWriter.Write(postData);
streamWriter.Flush();
streamWriter.Close();
}
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
如您所见,只有我指定ID的用户收到了通知。 如果它解决了您的问题,请标记我:)
答案 1 :(得分:0)
在@Stanley Gong的帮助下,我找到了一种适用于JSON的方法。
我需要为每个JSON数据创建一个类。
JSON数据:
{ "message" : "This is a test", "reference" : {"activityId":"bea79fa0-deaa-11e9-b5cf-dd1a7b37f8bc","user":{"id":"d77fef1e11-789b-4a6b-bf86-c832e5ed0e10","name":"User","aadObjectId":null,"role":null},"bot":{"id":"8bea0710-9ef5-11e9-9393-8929068282f7","name":"Bot","aadObjectId":null,"role":"bot"},"conversation":{"isGroup":null,"conversationType":null,"id":"begrfcf0-deaa-11e9-8c9e-e7efbe98c8c9|livechat","name":null,"aadObjectId":null,"role":null,"tenantId":null},"channelId":"emulator","serviceUrl":"http://localhost:54673"}}
C#:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Integration.AspNet.Core;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
namespace Guyde.Controllers
{
[Route("api/notify")]
[ApiController]
public class NotifyController : ControllerBase
{
private readonly IBotFrameworkHttpAdapter _adapter;
private readonly string _appId;
public NotifyController(IBotFrameworkHttpAdapter adapter, IConfiguration configuration)
{
_adapter = adapter;
_appId = configuration["MicrosoftAppId"];
// If the channel is the Emulator, and authentication is not in use,
// the AppId will be null. We generate a random AppId for this case only.
// This is not required for production, since the AppId will have a value.
if (string.IsNullOrEmpty(_appId))
{
_appId = Guid.NewGuid().ToString(); //if no AppId, use a random Guid
}
}
public async Task<IActionResult> Post([FromBody] RootObject payload)
{
var message = payload.message;
var json = JsonConvert.SerializeObject(payload.reference);
ConversationReference reference = JsonConvert.DeserializeObject<ConversationReference>(json);
await ((BotAdapter)_adapter).ContinueConversationAsync(_appId, reference, (ITurnContext turnContext, CancellationToken cancellationToken) => turnContext.SendActivityAsync(message), default(CancellationToken));
// Let the caller know proactive messages have been sent
return new ContentResult()
{
Content = "<html><body><h1>Proactive messages have been sent</h1></body></html>",
ContentType = "text/html",
StatusCode = (int)HttpStatusCode.OK,
};
}
}
public class User
{
public string id { get; set; }
public string name { get; set; }
public object aadObjectId { get; set; }
public object role { get; set; }
}
public class Bot
{
public string id { get; set; }
public string name { get; set; }
public object aadObjectId { get; set; }
public string role { get; set; }
}
public class Conversation
{
public object isGroup { get; set; }
public object conversationType { get; set; }
public string id { get; set; }
public object name { get; set; }
public object aadObjectId { get; set; }
public object role { get; set; }
public object tenantId { get; set; }
}
public class Reference
{
public string activityId { get; set; }
public User user { get; set; }
public Bot bot { get; set; }
public Conversation conversation { get; set; }
public string channelId { get; set; }
public string serviceUrl { get; set; }
}
public class RootObject
{
public string message { get; set; }
public Reference reference { get; set; }
}
}