Get proactive message from JSON

元气小坏坏 提交于 2021-02-11 10:44:10

问题


Is it possible to send a proactive message from an HTTP POST of json in C# if you have the ConversationReference?

The JSON POST body will look something like this with the ConversationReference attached.

[{ "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"}]

回答1:


Yes , all my code is based on this official demo .

Replace all content in NotifyController.cs with the code below :

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; }

    }
}

Ok, if you want to post a http request to your bot to send a notify , try the code below in your c# code :

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);

Result :

If you just want to send a notify to one user, you can specify the userid in request URL,as the code below :

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);

            }

Result :

As you can see , only the user with id I specified received the notification. Pls mark me if it solved your issue :)




回答2:


With the help of @Stanley Gong I found a way that worked for my purpose with the JSON.

I needed to create a class for each of the JSON data.

JSON data:

{ "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; }
    }
}


来源:https://stackoverflow.com/questions/58069530/get-proactive-message-from-json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!