1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

#はじめに
複数の電話番号にTwilio発でコール&レスポンスをする必要があり、複数Flowを並行実行させる方法をとりました。
その際に課題となったのが、「呼び出し元のFlowと呼び出し先のFlowで同期をとる」でした。
時間的猶予がなかったため、今回は各Flowの処理状況をSyncではなく、Executionのステータスと経由したWidget(Step)で判断することにしました。

#別Flowを実行する
別FlowのExecutionを作成することで、そのFlowを非同期で実行できます。
toに設定の電話番号を変更すると、Execution作成のたびにコール先の電話番号を
変更できます。

別Flowを実行する。(別FlowのExecutionを作成する。)
exports.handler = function (context, event, callback) {
    const client = context.getTwilioClient();
    client.studio.v1.flows("FlowのSID").executions.create({
        to: "発信先電話番号",
        from: "発信元電話番号",
    })
        .then((success) => {
            callback(null, success);
        })
        .catch((error) => {
            callback(null, error);
        });
};

#非同期実行のExecutionが完了するまで呼び出し元のFlowを待機する。
非同期で実行しているExecutionの処理状況は、statusフィールドから取得できます。

このExecutionのステータスがactiveの時に一定数秒待機した後に再度ステータスを
チェックし、endedに変更後、先に進む制御を入れることで、呼び出し元のFlowを
待機させることができます。

status 状態
active 処理中
ended 処理終了
別FlowのExecutionのステータスを取得する。
exports.handler = function (context, event, callback) {
    const client = context.getTwilioClient();
    client.studio.flows("FlowのSID")
        .executions("ExecutionのSID")
        .fetch()
        .then((execution) => {
            callback(null, execution.status)
        })
        .catch((error) => {
            callback(null, error)
        });
};

#呼び出し先のFlowで1をダイヤルされたかどうかを確認する。

※呼び出し先のFlowの例
 コール先のスタッフが1をダイヤルした場合のみ、acceptのSay/Playウィジェットを経由します。
CallFlowImage.PNG

stepsで取得のstep情報のtransitionedFromフィールドから、最後に経由したWidget
の名前を取得できます。

最後に経由したWidgetの名前を取得する。
exports.handler = function (context, event, callback) {
    const client = context.getTwilioClient();
    client.studio.flows("FlowのSID")
        .executions("ExecutionのSID")
        .steps
        .list({ limit: 1 })
        .then((steps) => {
            callback(null, steps[0].transitionedFrom)
        })
        .catch((error) => {
            console.log(error)
            callback(null, error)
        });
};

#注意点
・1つのExecutionの経由できるWidgetの上限は1,000 stepsに設定されています。
 そのため、飛び出し元のFlowの処理を待機する際に経由するwidgetのstep数を
 少量に抑えることをお勧めします。

・Functionの実行時間の上限は10秒に設定されています。
 そのため、Flowを待機させる際にExecutionのstatusのチェックのスパンを10秒超
 に設定する場合で、Waitする処理をFunctionで実行する場合は、実行時間が10秒を下回るよう実行する必要がございます。

9秒間待機する処理をfunctionで実行する。
exports.handler = function (context, event, callback) {
    const timerUp = () => callback(null, `9秒間待機しました。`);
    setTimeout(timerUp, 9000);
};
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?