Получить активное сообщение от JSON - PullRequest
1 голос
/ 23 сентября 2019

Можно ли отправить упреждающее сообщение из HTTP POST json в C #, если у вас есть ConversationReference?

Тело 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"}]

Ответы [ 2 ]

2 голосов
/ 24 сентября 2019

Да, весь мой код основан на этой официальной демонстрации .

Замените все содержимое в 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);

Результат: enter image description here

Если вы просто хотите отправить уведомление одному пользователю, вы можете указать идентификатор пользователя в 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);

            }

Результат: enter image description here

Как видите, уведомление получил только пользователь с указанным идентификатором.Пожалуйста, отметьте меня, если это решило вашу проблему:)

0 голосов
/ 24 сентября 2019

С помощью @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; }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...