使用Azure的Facebook Messenger Bot主动/推送通知

时间:2018-01-23 17:33:29

标签: facebook azure botframework azure-functions facebook-messenger-bot

我正在使用Microsoft Bot Framework为Facebook Messenger构建机器人。我打算将CosmosDB用于状态管理,也作为我的后端数据存储。 (我不会坚持使用CosmosBD,如果需要可以使用任何其他商店)

我需要根据用户的时间偏好向用户发送每日/每周主动消息(推送通知)。我会在他们第一次与机器人交互时捕捉他们的时间偏好。

提供这些通知的最佳方式是什么?

由于我将这些首选项存储在CosmosDB中,我正在考虑使用ComosDB trigger of creating an Azure Function并根据用户时间偏好安排它。此Azure功能将调用我的webhook,它将传递这些消息。如果需要,我会在用户改变他/她的偏好时更改功能计划。

我的问题是:

  1. 这是一个好方法吗?
  2. 还有其他选择(通知中心吗?)
  3. 我应该可以设置通知的特定时间(例如在小时或类似的时间),安排Azure功能在这些时间运行而不是根据用户首选项创建功能是否有意义(我实际上也可以将这两种方法结合起来)
  4. 提前谢谢。

2 个答案:

答案 0 :(得分:2)

我使用botframwork和messenger进行广泛的主动对话,没有任何问题。在您的Facebook批准过程中,您只需告知他们您将通过信使与您的机器人发送通知。通常,如果您使用它来通知您的用户并远离促销内容,那么您应该没问题。

我还使用azure函数从自定义控制器端点触发主动对话框。

天蓝色功能的贝娄示例代码:

public static void Run(TimerInfo notificationTrigger, TraceWriter log)
{
    try
    {
        //Serialize request object
        string timerInfo = JsonConvert.SerializeObject(notificationTrigger);

        //Create a request for bot service with security token
        HttpRequestMessage hrm = new HttpRequestMessage()
        {
            Method = HttpMethod.Post,
            RequestUri = new Uri(NotificationEndPointUrl),
            Content = new StringContent(timerInfo, Encoding.UTF8, "application/json")
        };
        hrm.Headers.Add("Authorization", NotificationApiKey);


        log.Info(JsonConvert.SerializeObject(hrm));

        //Call service
        using (var client = new HttpClient())
        {
            Task task = client.SendAsync(hrm).ContinueWith((taskResponse) =>
            {
                HttpResponseMessage result = taskResponse.Result;
                var jsonString = result.Content.ReadAsStringAsync();
                jsonString.Wait();

                if (result.StatusCode != System.Net.HttpStatusCode.OK)        
                {
                    //Throw what ever problem as an exception with  details
                    throw new Exception($"AzureFunction - ERRROR - HTTP {result.StatusCode}");
                }
            });

            task.Wait();
        }

    }
    catch (Exception ex)
    {
        //TODO log
    }
}

用于启动主动对话框的Bellow示例代码:

public static async Task Resume<T, R>(string resumptionCookie) where T : IDialog<R>, new()
{
    //Deserialize reference to conversation
    ConversationReference conversationReference = JsonConvert.DeserializeObject<ConversationReference>(resumptionCookie);

    //Generate message from bot to user
    var message = conversationReference.GetPostToBotMessage();

    var builder = new ContainerBuilder();
    using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
    {
        //From a cold start the service is not yet authenticated with dev bot azure services 
        //We thus must trust endpoint url.
        if (!MicrosoftAppCredentials.IsTrustedServiceUrl(message.ServiceUrl))
        {
            MicrosoftAppCredentials.TrustServiceUrl(message.ServiceUrl, DateTime.MaxValue);
        }


        var botData = scope.Resolve<IBotData>();
        await botData.LoadAsync(CancellationToken.None);

        //This is our dialog stack
        var task = scope.Resolve<IDialogTask>();

        T dialog = scope.Resolve<T>(); //Resolve the dialog using autofac        

        try
        {
            task.Call(dialog.Void<R, IMessageActivity>(), null);
            await task.PollAsync(CancellationToken.None);
        }
        catch (Exception ex)
        {
            //TODO log
        }
        finally
        {
            //flush dialog stack
            await botData.FlushAsync(CancellationToken.None);
        }
    }
}

您的对话框需要在autofac中注册。 您的resumptionCookie需要保存在您的数据库中。

答案 1 :(得分:1)

您可能需要查看有关主动消息的FB政策 有一个24小时的限制,但它可能不会完全搞砸你的情况

https://developers.facebook.com/docs/messenger-platform/policy/policy-overview#standard_messaging