LINE BOTアプリケーションのエラーを自分のLINEアカウントに通知する

Visual StudioとAzure Functionsで作るLINE BOTアプリケーション入門 - pierre3のブログの続きです。

LINE BOT 内のエラーを自分のLINEアカウントに通知する

BOTアプリケーション内で発生した(処理できない)例外の内容等は、Logに記録するだけでも良いのですが、自分のLINEアカウント宛に通知できるようにするとデバッグが非常にはかどります。

f:id:pierre3:20171008215758p:plain:w300

BOTアカウントを管理するLINEアカウント(自分のLINEアカウント)のユーザーIDはLINE Developers consoleのChannel基本設定ページで確認できます。このユーザーIDにエラーの内容をPush通知するように設定します。

f:id:pierre3:20171008222411p:plain:w600

LINE BOT Functionでの使用例

通知先のユーザーIDはアプリケーション設定に登録しておきます。
Azure ポータルで以下の様に設定しておきます。今回は"DebugUser"という名前で追加しました。

f:id:pierre3:20171008145027p:plain:w500

あとは、LINE Messaging APIがエラーレスポンスを返した際の例外処理に、エラーの詳細をPush通知するコードを記述すればOKです。

public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
    //Webhookイベントを取得する
    IEnumerable<WebhookEvent> events;
    try
    {
        var channelSecret = System.Configuration.ConfigurationManager.AppSettings["ChannelSecret"];
        events = await req.GetWebhookEventsAsync(channelSecret);
    }
    catch (InvalidSignatureException e)
    {
        return req.CreateResponse(HttpStatusCode.Forbidden, new { Message = e.Message });
    }
    
    //Webhookイベントを処理する
    try
    {
        var connectionString = System.Configuration.ConfigurationManager.AppSettings["AzureWebJobsStorage"];
        var tableStorage = await LineBotTableStorage.CreateAsync(connectionString);
        var blobStorage = await BlobStorage.CreateAsync(connectionString, "linebotcontainer");
        var app = new LineBotApp(lineMessagingClient, tableStorage, blobStorage, log);
        await app.RunAsync(events);

    }
    //LINE Messaging APIがエラーレスポンスを返した時の例外
    catch (LineResponseException e) 
    {
        //ログ出力        
        log.Error(e.ToString()); 
    
    //アプリケーション設定に登録しておいたユーザーIDにPush通知
        var debugUserId = System.Configuration.ConfigurationManager.AppSettings["DebugUser"];
        if (debugUserId != null)
        {
            await lineMessagingClient.PushMessageAsync(debugUserId, e.ResponseMessage.ToString());
        }
    }
    catch (Exception e)
    {
        log.Error(e.ToString());
    }

    return req.CreateResponse(HttpStatusCode.OK);
}