Да, весь мой код основан на этой официальной демонстрации .
Замените все содержимое в 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-адресе запроса, как показано ниже:
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);
}
Результат:
Как видите, уведомление получил только пользователь с указанным идентификатором.Пожалуйста, отметьте меня, если это решило вашу проблему:)