Azure Functions 的 Twilio 繫結Twilio binding for Azure Functions

本文說明如何在 Azure Functions 中使用 Twilio 繫結傳送文字簡訊。This article explains how to send text messages by using Twilio bindings in Azure Functions. Azure Functions 支援 Twilio 的輸出繫結。Azure Functions supports output bindings for Twilio.

這是 Azure Functions 開發人員的參考資訊。This is reference information for Azure Functions developers. 如果您不熟悉 Azure Functions,請從下列資源開始︰If you're new to Azure Functions, start with the following resources:

套件 - Functions 1.xPackages - Functions 1.x

Microsoft.Azure.WebJobs.Extensions.Twilio NuGet 套件 1.x 版中提供了 Twilio 繫結。The Twilio bindings are provided in the Microsoft.Azure.WebJobs.Extensions.Twilio NuGet package, version 1.x. 套件的原始程式碼位於 azure-webjobs-sdk GitHub 存放庫中。Source code for the package is in the azure-webjobs-sdk GitHub repository.

下表說明如何在每個開發環境中為此繫結新增支援。The following table tells how to add support for this binding in each development environment.

開發環境Development environment 若要新增支援To add support in
Functions 1.xFunctions 1.x
本機開發 - C# 類別庫Local development - C# class library 安裝套件Install the package
本機開發 - C# 指令碼、JavaScript、F#Local development - C# script, JavaScript, F# 自動Automatic
入口網站開發Portal development 自動Automatic

套件 - Functions 2.xPackages - Functions 2.x

Microsoft.Azure.WebJobs.Extensions.Twilio NuGet 套件 3.x 版中提供了 Twilio 繫結。The Twilio bindings are provided in the Microsoft.Azure.WebJobs.Extensions.Twilio NuGet package, version 3.x. 套件的原始程式碼位於 azure-webjobs-sdk GitHub 存放庫中。Source code for the package is in the azure-webjobs-sdk GitHub repository.

下表說明如何在每個開發環境中為此繫結新增支援。The following table tells how to add support for this binding in each development environment.

開發環境Development environment 若要新增支援To add support in
Functions 2.xFunctions 2.x
本機開發 - C# 類別庫Local development - C# class library 安裝套件Install the package
本機開發 - C# 指令碼、JavaScript、F#、Java 和 PythonLocal development - C# script, JavaScript, F#, Java and Python 註冊擴充功能Register the extension
入口網站開發Portal development 在新增輸出繫結時安裝Install when adding output binding

若要了解如何在不重新發行您的函數應用程式專案的情況下在入口網站中更新現有的繫結延伸模組,請參閱更新您的延伸模組To learn how to update existing binding extensions in the portal without having to republish your function app project, see Update your extensions.

範例 - Functions 1.xExample - Functions 1.x

請參閱特定語言的範例:See the language-specific example:

C# 範例C# example

下列範例顯示可在受到佇列訊息觸發時傳送文字簡訊的 C# 函式The following example shows a C# function that sends a text message when triggered by a queue message.

[FunctionName("QueueTwilio")]
[return: TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "+1425XXXXXXX" )]
public static SMSMessage Run(
    [QueueTrigger("myqueue-items", Connection = "AzureWebJobsStorage")] JObject order,
    TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {order}");

    var message = new SMSMessage()
    {
        Body = $"Hello {order["name"]}, thanks for your order!",
        To = order["mobileNumber"].ToString()
    };

    return message;
}

本範例會使用含有方法傳回值的 TwilioSms 屬性。This example uses the TwilioSms attribute with the method return value. 替代方式是使用具有 out SMSMessage 參數或 ICollector<SMSMessage>IAsyncCollector<SMSMessage> 參數的屬性。An alternative is to use the attribute with an out SMSMessage parameter or an ICollector<SMSMessage> or IAsyncCollector<SMSMessage> parameter.

C# 指令碼範例C# script example

下列範例說明 function.json 檔案中的 Twilio 輸出繫結,以及使用此繫結的 C# 指令碼函式The following example shows a Twilio output binding in a function.json file and a C# script function that uses the binding. 此函式會使用 out 參數來傳送文字簡訊。The function uses an out parameter to send a text message.

以下是 function.json 檔案中的繫結資料:Here's binding data in the function.json file:

function.json 範例:Example function.json:

{
  "type": "twilioSms",
  "name": "message",
  "accountSid": "TwilioAccountSid",
  "authToken": "TwilioAuthToken",
  "to": "+1704XXXXXXX",
  "from": "+1425XXXXXXX",
  "direction": "out",
  "body": "Azure Functions Testing"
}

以下是 C# 指令碼:Here's C# script code:

#r "Newtonsoft.Json"
#r "Twilio.Api"

using System;
using Newtonsoft.Json;
using Twilio;

public static void Run(string myQueueItem, out SMSMessage message,  TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {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.
    dynamic order = JsonConvert.DeserializeObject(myQueueItem);
    string msg = "Hello " + order.name + ", thank you for your order.";

    // Even if you want to use a hard coded message and number in the binding, you must at least 
    // initialize the SMSMessage variable.
    message = new SMSMessage();

    // A dynamic message can be set instead of the body in the output binding. In this example, we use 
    // the order information to personalize a text message to the mobile number provided for
    // order status updates.
    message.Body = msg;
    message.To = order.mobileNumber;
}

您無法使用非同步程式碼中的 out 參數。You can't use out parameters in asynchronous code. 以下是非同步的 C# 指令碼範例:Here's an asynchronous C# script code example:

#r "Newtonsoft.Json"
#r "Twilio.Api"

using System;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Twilio;

public static async Task Run(string myQueueItem, IAsyncCollector<SMSMessage> message,  ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {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.
    dynamic order = JsonConvert.DeserializeObject(myQueueItem);
    string msg = "Hello " + order.name + ", thank you for your order.";

    // Even if you want to use a hard coded message and number in the binding, you must at least 
    // initialize the SMSMessage variable.
    SMSMessage smsText = new SMSMessage();

    // A dynamic message can be set instead of the body in the output binding. In this example, we use 
    // the order information to personalize a text message to the mobile number provided for
    // order status updates.
    smsText.Body = msg;
    smsText.To = order.mobileNumber;

    await message.AddAsync(smsText);
}

JavaScript 範例JavaScript example

下列範例說明 function.json 檔案中的 Twilio 輸出繫結,以及使用此繫結的 JavaScript 函式The following example shows a Twilio output binding in a function.json file and a JavaScript function that uses the binding.

以下是 function.json 檔案中的繫結資料:Here's binding data in the function.json file:

function.json 範例:Example function.json:

{
  "type": "twilioSms",
  "name": "message",
  "accountSid": "TwilioAccountSid",
  "authToken": "TwilioAuthToken",
  "to": "+1704XXXXXXX",
  "from": "+1425XXXXXXX",
  "direction": "out",
  "body": "Azure Functions Testing"
}

以下是 JavaScript 程式碼:Here's the JavaScript code:

module.exports = 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 and number 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. In this example, we use 
    // the order information to personalize a text message to the mobile number provided for
    // order status updates.
    context.bindings.message = {
        body : msg,
        to : myQueueItem.mobileNumber
    };

    context.done();
};

範例 - Functions 2.xExample - Functions 2.x

請參閱特定語言的範例:See the language-specific example:

2.x C# 範例2.x C# example

下列範例顯示可在受到佇列訊息觸發時傳送文字簡訊的 C# 函式The following example shows a C# function that sends a text message when triggered by a queue message.

using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace TwilioQueueOutput
{
    public static class QueueTwilio
    {
        [FunctionName("QueueTwilio")]
        [return: TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "+1425XXXXXXX")]
        public static CreateMessageOptions Run(
        [QueueTrigger("myqueue-items", Connection = "AzureWebJobsStorage")] JObject order,
        ILogger log)
        {
            log.LogInformation($"C# Queue trigger function processed: {order}");

            var message = new CreateMessageOptions(new PhoneNumber(order["mobileNumber"].ToString()))
            {
                Body = $"Hello {order["name"]}, thanks for your order!"
            };

            return message;
        }
    }
}

本範例會使用含有方法傳回值的 TwilioSms 屬性。This example uses the TwilioSms attribute with the method return value. 替代方式是使用具有 out CreateMessageOptions 參數或 ICollector<CreateMessageOptions>IAsyncCollector<CreateMessageOptions> 參數的屬性。An alternative is to use the attribute with an out CreateMessageOptions parameter or an ICollector<CreateMessageOptions> or IAsyncCollector<CreateMessageOptions> parameter.

2.x C# 指令碼範例2.x C# script example

下列範例說明 function.json 檔案中的 Twilio 輸出繫結,以及使用此繫結的 C# 指令碼函式The following example shows a Twilio output binding in a function.json file and a C# script function that uses the binding. 此函式會使用 out 參數來傳送文字簡訊。The function uses an out parameter to send a text message.

以下是 function.json 檔案中的繫結資料:Here's binding data in the function.json file:

function.json 範例:Example function.json:

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

以下是 C# 指令碼:Here's C# script code:

#r "Newtonsoft.Json"
#r "Twilio"
#r "Microsoft.Azure.WebJobs.Extensions.Twilio"

using System;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.WebJobs.Extensions.Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;

public static void Run(string myQueueItem, out CreateMessageOptions message,  ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {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.
    dynamic order = JsonConvert.DeserializeObject(myQueueItem);
    string msg = "Hello " + order.name + ", thank you for your order.";

    // You must initialize the CreateMessageOptions variable with the "To" phone number.
    message = new CreateMessageOptions(new PhoneNumber("+1704XXXXXXX"));

    // A dynamic message can be set instead of the body in the output binding. In this example, we use
    // the order information to personalize a text message.
    message.Body = msg;
}

您無法使用非同步程式碼中的 out 參數。You can't use out parameters in asynchronous code. 以下是非同步的 C# 指令碼範例:Here's an asynchronous C# script code example:

#r "Newtonsoft.Json"
#r "Twilio"
#r "Microsoft.Azure.WebJobs.Extensions.Twilio"

using System;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.WebJobs.Extensions.Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;

public static async Task Run(string myQueueItem, IAsyncCollector<CreateMessageOptions> message,  ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {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.
    dynamic order = JsonConvert.DeserializeObject(myQueueItem);
    string msg = "Hello " + order.name + ", thank you for your order.";

    // You must initialize the CreateMessageOptions variable with the "To" phone number.
    CreateMessageOptions smsText = new CreateMessageOptions(new PhoneNumber("+1704XXXXXXX"));

    // A dynamic message can be set instead of the body in the output binding. In this example, we use
    // the order information to personalize a text message.
    smsText.Body = msg;

    await message.AddAsync(smsText);
}

2.x JavaScript 範例2.x JavaScript example

下列範例說明 function.json 檔案中的 Twilio 輸出繫結,以及使用此繫結的 JavaScript 函式The following example shows a Twilio output binding in a function.json file and a JavaScript function that uses the binding.

以下是 function.json 檔案中的繫結資料:Here's binding data in the function.json file:

function.json 範例:Example function.json:

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

以下是 JavaScript 程式碼:Here's the JavaScript code:

module.exports = 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
    };

    context.done();
};

屬性Attributes

C# 類別庫中,使用 TwilioSms 屬性。In C# class libraries, use the TwilioSms attribute.

如需可設定的屬性內容相關資訊,請參閱設定For information about attribute properties that you can configure, see Configuration. 以下是方法簽章中的 TwilioSms 屬性範例:Here's a TwilioSms attribute example in a method signature:

[FunctionName("QueueTwilio")]
[return: TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "+1425XXXXXXX")]
public static CreateMessageOptions Run(
[QueueTrigger("myqueue-items", Connection = "AzureWebJobsStorage")] JObject order, ILogger log)
{
    ...
}

如需完整範例,請參閱 C# 範例For a complete example, see C# example.

組態Configuration

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 TwilioSms 屬性。The following table explains the binding configuration properties that you set in the function.json file and the TwilioSms attribute.

v1 function.json 屬性v1 function.json property v2 function.json 屬性v2 function.json property 屬性內容Attribute property 描述Description
typetype typetype 必須設為 twilioSmsmust be set to twilioSms.
directiondirection directiondirection 必須設為 outmust be set to out.
namename namename 用於 Twilio 簡訊文字訊息之函式程式碼中的變數名稱。Variable name used in function code for the Twilio SMS text message.
accountSidaccountSid accountSidSettingaccountSidSetting AccountSidSettingAccountSidSetting 此值必須設定為保留您 Twilio 帳戶 Sid 的應用程式設定名稱,例如 TwilioAccountSid。This value must be set to the name of an app setting that holds your Twilio Account Sid e.g. TwilioAccountSid. 若未設定,預設的應用程式設定名稱是 "AzureWebJobsTwilioAccountSid"。If not set, the default app setting name is "AzureWebJobsTwilioAccountSid".
authTokenauthToken authTokenSettingauthTokenSetting AuthTokenSettingAuthTokenSetting 此值必須設定為保留您 Twilio 驗證權杖的應用程式設定名稱,例如 TwilioAccountAuthToken。This value must be set to the name of an app setting that holds your Twilio authentication token e.g. TwilioAccountAuthToken. 若未設定,預設的應用程式設定名稱是 "AzureWebJobsTwilioAuthToken"。If not set, the default app setting name is "AzureWebJobsTwilioAuthToken".
toto N/A - 在程式碼中指定N/A - specify in code ToTo 此值設定為簡訊文字傳送至的電話號碼。This value is set to the phone number that the SMS text is sent to.
fromfrom fromfrom FromFrom 此值設定為從中傳送簡訊文字的電話號碼。This value is set to the phone number that the SMS text is sent from.
bodybody bodybody 內文Body 如果您不需要在函式程式碼中動態設定 SMS 文字訊息,則此值可以用來硬式編碼 SMS 文字訊息。This value can be used to hard code the SMS text message if you don't need to set it dynamically in the code for your function.

當您要在本機開發時,應用程式設定會進入 local.settings.json 檔案When you're developing locally, app settings go into the local.settings.json file.

後續步驟Next steps