通过api控制器向用户发送主动消息

时间:2019-08-08 11:57:22

标签: c# botframework

我正在尝试为聊天机器人提供提醒功能。我想到了使用azure函数在与日期匹配时发出api发布请求。我使用发现的this指南制作了控制器。

我在bot模拟器上尝试过,发现它只能像这样工作: 运行代码和机器人模拟器,然后在提琴手上发出请求,但是什么也没有发生。 然后,我停止运行代码,然后再次运行它,但不重新启动模拟器。 然后,我再次提出提琴手请求,现在它成功发送了一条主动消息。而且我也无法继续对话。我要实现的是发送主动消息时,如果用户处于对话框中间,则用户仍然可以继续对话框。

OnTurnAsync()

        var conversationReference = turnContext.Activity.GetConversationReference();
        var filepath = Path.Combine(_hostingEnvironment.WebRootPath, "resume.json");
        File.WriteAllText(filepath, JsonConvert.SerializeObject(conversationReference));

控制器

namespace BasicBot.Controllers
{
    [Route("api/callBack")]
    public class CallBackController : Controller
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public CallBackController(IHostingEnvironment hostingEnvironment)
        {
            this._hostingEnvironment = hostingEnvironment;
        }

        [HttpPost]
        public async Task<HttpResponseMessage> Post([FromBody] ProactiveMessage message)
        {
            var filepath = Path.Combine(_hostingEnvironment.WebRootPath, "resume.json");

            if (System.IO.File.Exists(filepath))
            {
                var resumeJson = System.IO.File.ReadAllText(filepath);
                var resumeData = JsonConvert.DeserializeObject<ConversationReference>(resumeJson);
                var client = new ConnectorClient(new Uri(resumeData.ServiceUrl));
                var message1 = resumeData.GetContinuationActivity().CreateReply($"Try send proactive message");
                await client.Conversations.ReplyToActivityAsync((Activity)message1);
                return new HttpResponseMessage(System.Net.HttpStatusCode.OK);

            }
            else
            {
                return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
            }
        }
    }

    public class ProactiveMessage
    {
        public string Text { get; set; }
    }
}

0 个答案:

没有答案
相关问题