c# - 从 JSON 获取主动消息
问题描述
如果您有 ConversationReference,是否可以从 C# 中的 json 的 HTTP POST 发送主动消息?
JSON POST 正文看起来像这样,附加了 ConversationReference。
[{ "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"}]
解决方案
是的,我所有的代码都是基于这个官方演示。
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 的用户收到了通知。如果它解决了您的问题,请标记我:)
推荐阅读
- spring - 如何创建自定义 Spring Boot @component - 注释以遵守干净代码/架构原则?
- php - 使用 PHP 创建 Firebase 动态链接
- javascript - 我希望粘性侧边栏在页脚中停止。我该怎么做?
- spring-integration - Spring Boot、Spring 集成 RabbitMQ 和 AWS Kinesis 集成
- python - 如何暂停线程池、运行函数和恢复?
- javascript - 带有 data-url href 的元素不会显示在 svg 中
- oauth - 使用 passport-auth0-openidconnect 时,如何获取完整的访问令牌来调用 /api/v2/users/?
- google-sheets - 基于跨列和跨行的单个单元格的条件格式
- visual-studio - 由于 CRC 错误导致 nuget 配置错误,.NET 框架解决方案开始失败
- python - 无法在反向 shell 中执行 cd 命令