次の方法で共有


Azure Functions の Twilio バインド

This article explains how to send text messages by using Twilio bindings in Azure Functions. Azure Functions は、Twilio の出力バインドをサポートします。

これは、Azure Functions の開発者向けリファレンス情報です。 Azure Functions を初めて使用する場合は、先に次のリソースを参照してください。

Install extension

インストールする拡張機能 NuGet パッケージは、関数アプリで使用している C# モードによって異なります。

関数は分離された C# ワーカー プロセスで実行されます。 詳しくは、「分離ワーカー プロセスにおける C# Azure Functions の実行のガイド」をご覧ください。

拡張機能の機能性は、拡張機能のバージョンによって異なります。

現在、分離ワーカー プロセス アプリに対して Twilio はサポートされていません。

Install bundle

Starting with Functions version 2.x, the HTTP extension is part of an extension bundle, which is specified in your host.json project file. To learn more, see extension bundle.

This version of the extension should already be available to your function app with extension bundle, version 2.x.

Example

特に指定がない限り、これらの例はバージョン 2.x 以降のバージョンの Functions ランタイムに固有です。

C# 関数は、次のいずれかの C# モードを使用して作成できます。

  • 分離されたワーカー モデル: ランタイムから分離されたワーカー プロセスで実行されるコンパイル済みの C# 関数。 .NET および .NET Framework の長期サポート (LTS) および LTS 以外のバージョンで実行されている C# 関数をサポートするには、分離ワーカー プロセスが必要です。
  • In-process model: Compiled C# function that runs in the same process as the Azure Functions runtime.
  • C# script: Used primarily when you create C# functions in the Azure portal.

現在、Twilio バインドは、分離ワーカー プロセスで実行されている関数アプリについてはサポートされていません。

The following example shows a Twilio output binding in a function.json file and a JavaScript function that uses the binding.

Here's binding data in the function.json file:

Example function.json:

{
  "type": "twilioSms",
  "name": "message",
  "accountSidSetting": "TwilioAccountSid",
  "authTokenSetting": "TwilioAuthToken",
  "from": "+1425XXXXXXX",
  "direction": "out",
  "body": "Azure Functions Testing"
}

JavaScript コードを次に示します。

module.exports = async function (context, myQueueItem) {
    context.log('Node.js queue trigger function processed work item', myQueueItem);

    // In this example the queue item is a JSON string representing an order that contains the name of a
    // customer and a mobile number to send text updates to.
    var msg = "Hello " + myQueueItem.name + ", thank you for your order.";

    // Even if you want to use a hard coded message in the binding, you must at least
    // initialize the message binding.
    context.bindings.message = {};

    // A dynamic message can be set instead of the body in the output binding. The "To" number 
    // must be specified in code. 
    context.bindings.message = {
        body : msg,
        to : myQueueItem.mobileNumber
    };
};

現在、SendGrid バインドについての PowerShell の完全な例は利用できません。

The following example shows how to send an SMS message using the output binding as defined in the following function.json.

    {
      "type": "twilioSms",
      "name": "twilioMessage",
      "accountSidSetting": "TwilioAccountSID",
      "authTokenSetting": "TwilioAuthToken",
      "from": "+1XXXXXXXXXX",
      "direction": "out",
      "body": "Azure Functions Testing"
    }

シリアル化された JSON オブジェクトを func.Out パラメーターに渡して、SMS メッセージを送信できます。

import logging
import json
import azure.functions as func

def main(req: func.HttpRequest, twilioMessage: func.Out[str]) -> func.HttpResponse:

    message = req.params.get('message')
    to = req.params.get('to')

    value = {
      "body": message,
      "to": to
    }

    twilioMessage.set(json.dumps(value))

    return func.HttpResponse(f"Message sent")

The following example shows how to use the TwilioSmsOutput annotation to send an SMS message. tofrom、および body の値は、プログラムによってオーバーライドされた場合でも、属性定義に必要です。

package com.function;

import java.util.*;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;

public class TwilioOutput {

    @FunctionName("TwilioOutput")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", methods = { HttpMethod.GET, HttpMethod.POST },
                authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<Optional<String>> request,
            @TwilioSmsOutput(
                name = "twilioMessage",
                accountSid = "AzureWebJobsTwilioAccountSID",
                authToken = "AzureWebJobsTwilioAuthToken",
                to = "+1XXXXXXXXXX",
                body = "From Azure Functions",
                from = "+1XXXXXXXXXX") OutputBinding<String> twilioMessage,
            final ExecutionContext context) {

        String message = request.getQueryParameters().get("message");
        String to = request.getQueryParameters().get("to");

        StringBuilder builder = new StringBuilder()
            .append("{")
            .append("\"body\": \"%s\",")
            .append("\"to\": \"%s\"")
            .append("}");

        final String body = String.format(builder.toString(), message, to);

        twilioMessage.setValue(body);

        return request.createResponseBuilder(HttpStatus.OK).body("Message sent").build();
    }
}

Attributes

Both in-process and isolated worker process C# libraries use attributes to define the output binding. C# スクリプトでは、代わりに function.json 構成ファイルを使います。

現在、Twilio バインドは、分離ワーカー プロセスで実行されている関数アプリについてはサポートされていません。

Annotations

The TwilioSmsOutput annotation allows you to declaratively configure the Twilio output binding by providing the following configuration values:

+

Place the TwilioSmsOutput annotation on an OutputBinding<T> parameter, where T may be any native Java type such as int, String, byte[], or a POJO type.

Configuration

The following table explains the binding configuration properties that you set in the function.json file, which differs by runtime version:

function.json property Description
type twilioSms に設定する必要があります。
direction out に設定する必要があります。
name Twilio SMS テキスト メッセージの関数コードで使用される変数名です。
accountSidSetting この値には、Twilio Account Sid (TwilioAccountSid) を保持するアプリ設定の名前を指定する必要があります。 設定されていない場合、既定のアプリの設定名は AzureWebJobsTwilioAccountSid です。
authTokenSetting この値には、Twilio 認証トークン (TwilioAccountAuthToken) を保持するアプリ設定の名前を指定する必要があります。 設定されていない場合、既定のアプリの設定名は AzureWebJobsTwilioAuthToken です。
from この値は、SMS テキストの送信元の電話番号に設定されます。
body この値は、SMS テキスト メッセージを関数のコードで動的に設定する必要がない場合に、メッセージをハード コーディングするために使用できます。

バージョン 2.x では、値 to をコードで設定します。

When you're developing locally, add your application settings in the local.settings.json file in the Values collection.

Next steps