傳送 WhatsApp 文字和媒體訊息

Azure Communication Services 讓你能夠發送和接收 WhatsApp 訊息。 本文說明如何將您的應用程式與 Azure Communication Advanced Messages SDK 整合,開始發送與接收 WhatsApp 訊息。 完成本文章後,Azure 帳戶中會產生幾美分或更少的少許費用。

必要條件

設定環境

建立 .NET 專案

要建立你的專案,請依照 使用 Visual Studio 建立一個.NET控制台應用程式。

若要編譯程式碼,請按 Ctrl+F7

安裝套件

安裝 Azure。Communication.Messages NuGet 套件到你的 C# 專案。

  1. 將 NuGet Package Manager 開啟,座標為 Project>Manage NuGet Packages...
  2. 搜尋套件 Azure.Communication.Messages
  3. 安裝最新版本。

設定應用程式架構

在文字編輯器中開啟 Program.cs 檔案。

以下列程式碼取代您 Program.cs 的內容:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure;
using Azure.Communication.Messages;

namespace AdvancedMessagingQuickstart
{
    class Program
    {
        public static async Task Main(string[] args)
        {
            Console.WriteLine("Azure Communication Services - Advanced Messages quickstart samples.");

            // Quickstart code goes here
        }
    }
}

要使用進階訊息功能,請新增 using 指令,包含 Azure.Communication.Messages 命名空間。

using Azure.Communication.Messages;

物件模型

以下類別與介面處理 Azure Communication Services Advance Messaging SDK for .NET 的一些主要功能。

類別名稱 描述
NotificationMessagesClient 連接你的 Azure Communication Services 資源。 它會傳送訊息。
MessageTemplate 定義您使用的範本,以及訊息範本屬性的內容。
TemplateNotificationContent 定義您想要傳送之範本訊息的「誰」和「內容」。
TextNotificationContent 定義您想要傳送之文字訊息的「誰」和「內容」。
ImageNotificationContent 定義您想要傳送之影像媒體訊息的「誰」和「內容」。
DocumentNotificationContent 定義您要傳送之文件媒體訊息的「誰」和「內容」。
VideoNotificationContent 定義您想要傳送之視訊媒體訊息的「誰」和「內容」。
AudioNotificationContent 定義您想要傳送之音訊媒體訊息的「誰」和「內容」。

注意

欲了解更多資訊,請參閱 Azure SDK 的 .NET 參考 Azure.Communication.Messages 命名空間

一般設定

請遵循下列步驟,將必要的代碼段新增至 messages-quickstart.py python 程式。

驗證用戶端

訊息 SDK 會使用 NotificationMessagesClient 來傳送訊息。 NotificationMessagesClient 方法使用你從 Azure 入口網站的 Azure Communication Services 資源中取得的 connection string 進行驗證。 欲了解更多關於連接字串的資訊,請參閱 access-your-connection-strings-and-service-endpoints

為了簡化起見,本文使用connection string來進行認證。 在生產環境中,我們建議使用服務主體

從 Azure 入口網站中的 Azure 通訊服務資源取得連接字串。 在左側瀏覽至 Keys 索引標籤。複製主索引鍵的 Connection string 欄位。 connection string格式為endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key}

截圖,顯示Azure入口網站中的一個Azure Communication Services資源,在「主鍵」區塊中查看「連線字串」欄位。

將環境變數 COMMUNICATION_SERVICES_CONNECTION_STRING 設為你的connection string值。
開啟主控台視窗並輸入下列命令:

setx COMMUNICATION_SERVICES_CONNECTION_STRING "<your connection string>"

新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 舉例來說,如果你用 Visual Studio 當編輯器,執行範例前先重新啟動 Visual Studio。

想了解如何為系統設定環境變數,請依照 將你的connection string存於環境變數的步驟。

若要具現化 NotificationMessagesClient,請將下列程式碼新增至 Main 方法:

// Retrieve connection string from environment variable
string connectionString = 
    Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING");

// Instantiate the client
var notificationMessagesClient = new NotificationMessagesClient(connectionString);

設定頻道註冊識別碼

您在通道註冊期間建立了通道註冊標識碼 GUID。 在您的 Azure Communication Services 資源的 Channels 分頁中,您可以找到它。

顯示 Azure入口網站中的 Azure 通訊服務資源,及查看「管道」索引標籤的螢幕截圖。請注意「管道識別碼」欄位的複製動作。

將其指派給名為 channelRegistrationId 的變數。

var channelRegistrationId = new Guid("<your channel registration ID GUID>");

設定收件者清單

您需要提供一個與 WhatsApp 帳戶相關的有效電話號碼,或是商務範圍使用者識別碼 (BSUID)。 此 WhatsApp 帳戶會接收本快速入門中傳送的範本、文字和媒體訊息。

在此範例中,您可以使用個人電話號碼。

收件者電話號碼不能是與 WhatsApp 頻道註冊相關聯的商務電話號碼 (傳送者識別碼)。 傳送者識別碼會顯示為傳送給收件者之文字和媒體訊息的傳送者。

電話號碼必須包含國家/地區代碼。 如需電話號碼格式的詳細資訊,請參閱 WhatsApp 檔中的 電話號碼格式

注意

目前收件人名單中只支援一個電話號碼或 BSUID。

建立如下的收件者清單:

var recipientList = new List<string> { "<to WhatsApp phone number or BSUID>" };

使用電話號碼的範例:

// Example only
var recipientList = new List<string> { "+14255550199" };

使用BSUID的範例:

// Example only
var recipientList = new List<string> { "US.13491208655302741918" };

注意

自 2026 年 6 月起,將可向 BSUID 發送訊息。 在那之前,請用電話號碼作為收件人。

欲了解更多關於 BSUID 的資訊,請參閱 WhatsApp 使用者名稱與 BSUID

開始在企業與 WhatsApp 使用者之間傳送訊息

WhatsApp Business 帳戶與 WhatsApp 使用者之間的交談可以透過下列兩種方式來開始:

  • 企業將範本訊息傳送給 WhatsApp 使用者。
  • WhatsApp 使用者可以將任何訊息發送至商業號碼。

企業無法起始互動式交談。 企業只能在收到來自使用者的訊息之後傳送互動式訊息。 企業只能在進行中對話期間,向使用者傳送互動訊息。 一旦 24 小時交談視窗到期,只有使用者可以重新啟動互動式交談。 如需交談的詳細資訊,請參閱 WhatsApp Business Platform 的定義

若要從您的個人 WhatsApp 帳戶起始互動式交談,請將訊息傳送至您的商務號碼(寄件人標識符)。

Web 上檢視的 WhatsApp 交談,其中顯示傳送至 WhatsApp Business 帳戶號碼的使用者訊息。

程式碼範例

請遵循下列步驟,將必要的代碼段新增至檔案 Program.cs 的 Main 函式。

重要

若要將文字或媒體訊息傳送至 WhatsApp 使用者,WhatsApp 用戶必須先將訊息傳送至 WhatsApp 商務帳戶。 如需詳細資訊,請參閱開始在企業與 WhatsApp 使用者之間傳送訊息

將文字訊息傳送給 WhatsApp 使用者

訊息 SDK 允許 Contoso 傳送由 WhatsApp 使用者發起的 WhatsApp 文字訊息。 若要傳送文字訊息,您需要:

在此範例中,我們會以文字回復 WhatsApp 使用者: "Thanks for your feedback.\n From Notification Messaging SDK."

組合並傳送簡訊:

// Assemble text message
var textContent = 
    new TextNotificationContent(channelRegistrationId, recipientList, "Thanks for your feedback.\n From Notification Messaging SDK");

// Send text message
Response<SendMessageResult> sendTextMessageResult = 
    await notificationMessagesClient.SendAsync(textContent);

將影像媒體訊息傳送至 WhatsApp 使用者

Messages SDK 可讓 Contoso 將 WhatsApp 媒體訊息傳送給 WhatsApp 使用者。 若要傳送內嵌媒體訊息,您需要:

重要

從 SDK 1.1.0 版起,MediaNotificationContent 將被淘汰,不再用於圖像。 我們鼓勵您使用 ImageNotificationContent 來傳送影像。 探索其他媒體類型的其他內容特定類別,例如 DocumentNotificationContentVideoNotificationContentAudioNotificationContent

組合映像訊息:

var imageLink = new Uri("https://example.com/image.jpg");
var imageNotificationContent = new ImageNotificationContent(channelRegistrationId, recipientList, imageLink)  
{  
    Caption = "Check out this image."  
};

傳送影像訊息:

var imageResponse = await notificationMessagesClient.SendAsync(imageNotificationContent);

將文件媒體訊息傳送至 WhatsApp 使用者

Messages SDK 可讓 Contoso 將 WhatsApp 媒體訊息傳送給 WhatsApp 使用者。 若要傳送內嵌媒體訊息,您需要:

組合檔案內容:

var documentLink = new Uri("https://example.com/document.pdf");
var documentNotificationContent = new DocumentNotificationContent(channelRegistrationId, recipientList, documentLink)  
{  
    Caption = "Check out this document.",  
    FileName = "document.pdf"  
};

傳送檔案訊息:

var documentResponse = await notificationMessagesClient.SendAsync(documentNotificationContent);

將視訊媒體訊息傳送至 WhatsApp 使用者

Messages SDK 可讓 Contoso 將 WhatsApp 媒體訊息傳送給 WhatsApp 使用者。 若要傳送內嵌媒體訊息,您需要:

組合影片訊息:

var videoLink = new Uri("https://example.com/video.mp4");
var videoNotificationContent = new VideoNotificationContent(channelRegistrationId, recipientList, videoLink)  
{  
    Caption = "Check out this video."  
};

傳送影片訊息:

var videoResponse = await notificationMessagesClient.SendAsync(videoNotificationContent);

將音訊媒體訊息傳送至 WhatsApp 使用者

Messages SDK 可讓 Contoso 將 WhatsApp 媒體訊息傳送給 WhatsApp 使用者。 若要傳送內嵌媒體訊息,您需要:

組合音訊訊息:

var audioLink = new Uri("https://example.com/audio.mp3");
var audioNotificationContent = new AudioNotificationContent(channelRegistrationId, recipientList, audioLink);

傳送音訊訊息:

var audioResponse = await notificationMessagesClient.SendAsync(audioNotificationContent);

執行程式碼

建立並執行您的程式。

要傳送文字或媒體訊息給 WhatsApp 用戶,WhatsApp Business 帳戶和 WhatsApp 用戶之間必須有活躍對話。

如果您沒有進行中的對話,在本範例中,請在發送範本訊息和發送文字訊息之間加入一段等待時間。 這個新增的延遲可讓您有足夠的時間對使用者的 WhatsApp 帳戶進行回覆。 作為參考,範例程式碼的完整範例會在傳送下一則訊息之前,提示手動使用者輸入。

如果成功,您會在使用者的 WhatsApp 帳戶上收到三則訊息。

  1. 若要編譯程式碼,請按 Ctrl+F7
  2. 若要在不偵錯的情況下執行程式,請按 Ctrl+F5

完整範例程式碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Azure;
using Azure.Communication.Messages;

namespace AdvancedMessagingQuickstart
{
    class Program
    {
        public static async Task Main(string[] args)
        {
            Console.WriteLine("Azure Communication Services - Send WhatsApp Messages\n");

            string connectionString = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING");
            NotificationMessagesClient notificationMessagesClient = 
                new NotificationMessagesClient(connectionString);

            var channelRegistrationId = new Guid("<Your Channel ID>");
            var recipientList = new List<string> { "<Recipient's WhatsApp Phone Number>" };

            // Send sample template sample_template
            string templateName = "sample_template";
            string templateLanguage = "en_us";
            MessageTemplate sampleTemplate = new MessageTemplate(templateName, templateLanguage);
            TemplateNotificationContent templateContent = 
                new TemplateNotificationContent(channelRegistrationId, recipientList, sampleTemplate);
            Response<SendMessageResult> sendTemplateMessageResult = 
                await notificationMessagesClient.SendAsync(templateContent);

            PrintResult(sendTemplateMessageResult);
            Console.WriteLine("Template message sent.\nWait until the WhatsApp user responds " +
                "to the template message, then press any key to continue.\n");
            Console.ReadKey();

            // Send a text message
            string messageText = "Thanks for your feedback.";
            TextNotificationContent textContent =
                new TextNotificationContent(channelRegistrationId, recipientList, messageText);
            Response<SendMessageResult> sendTextMessageResult =
                await notificationMessagesClient.SendAsync(textContent);

            PrintResult(sendTextMessageResult);
            Console.WriteLine($"Text message sent to my phoneNumber.\nPress any key to continue.\n");
            Console.ReadKey();

            // Send a media message
            Uri uri = new Uri("https://aka.ms/acsicon1");
            ImageNotificationContent imageContent =
                new ImageNotificationContent(channelRegistrationId, recipientList, uri);
            Response<SendMessageResult> sendMediaMessageResult =
                await notificationMessagesClient.SendAsync(imageContent);

            PrintResult(sendMediaMessageResult);
            Console.WriteLine("Media message sent.\nPress any key to exit.\n");
            Console.ReadKey();
        }

        public static void PrintResult(Response<SendMessageResult> result)
        {
            Console.WriteLine($"Response: {result.GetRawResponse().Status} " +
                $"({result.GetRawResponse().ReasonPhrase})");
            Console.WriteLine($"Date: " +
                $"{result.GetRawResponse().Headers.First(header => header.Name == "Date").Value}");
            Console.WriteLine($"ClientRequestId: {result.GetRawResponse().ClientRequestId}");
            Console.WriteLine($"MS-CV: " +
                $"{result.GetRawResponse().Headers.First(header => header.Name == "MS-CV").Value}");
            foreach (var receipts in result.Value.Receipts)
            {
                Console.WriteLine($"MessageId: {receipts.MessageId}");
            }
            Console.WriteLine($"\n");
        }
    }
}

必要條件

設定環境

若要設定傳送訊息的環境,請完成下列各節中的步驟。

建立一個新的 Java 應用程式

打開終端機或指令視窗,然後導覽到你想建立 Java 應用程式的目錄。 執行以下指令,從 maven-archetype-quickstart 範本產生 Java 專案。

mvn archetype:generate -DgroupId="com.communication.quickstart" -DartifactId="communication-quickstart" -DarchetypeArtifactId="maven-archetype-quickstart" -DarchetypeVersion="1.4" -DinteractiveMode="false"

generate 目標會建立具有與 artifactId 值相同名稱的目錄。 在此目錄下,src/main/java 目錄包含 project 原始碼,src/test/java 目錄包含測試原始碼,pom.xml 檔案則是project的Project物件模型(POM)。

安裝套件

在文字編輯器中開啟 pom.xml 檔案。 將下列相依性元素加入至相依性群組。

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-messages</artifactId>
</dependency>

設定應用程式架構

在文字編輯器中開啟 /src/main/java/com/communication/quickstart/App.java ,新增 import 指示詞,然後移除 System.out.println("Hello world!"); 語句:

package com.communication.quickstart;

import com.azure.communication.messages.*;
import com.azure.communication.messages.models.*;

import java.util.ArrayList;
import java.util.List;
public class App
{
    public static void main( String[] args )
    {
        // Quickstart code goes here.
    }
}

程式碼範例

請遵循下列步驟,將必要的代碼段新增至檔案 App.java 的主要函式。

開始在企業與 WhatsApp 使用者之間傳送訊息

WhatsApp Business 帳戶與 WhatsApp 使用者之間的交談可以透過下列兩種方式來開始:

  • 企業將範本訊息傳送給 WhatsApp 使用者。
  • WhatsApp 使用者可以將任何訊息發送至商業號碼。

不論交談如何開始,企業只能傳送範本訊息,直到使用者傳送訊息給企業為止。只有在使用者傳送訊息給企業之後,企業才能在作用中交談期間將文字或媒體訊息傳送給使用者。 一旦 24 小時交談視窗過期,就必須重新開始交談。 若要深入了解交談,請參閱 WhatsApp Business Platform 中的定義。

驗證用戶端

有一些不同的選項可用來驗證訊息用戶端:

要驗證客戶端,您會用連接字串實例化NotificationMessagesClientMessageTemplateClient。 您也可以使用會實作 com.azure.core.http.HttpClient 介面的任何自訂 HTTP 用戶端來初始化用戶端。

為了簡化起見,本文使用connection string來進行認證。 在生產環境中,我們建議使用服務主體

從 Azure 入口網站中的 Azure 通訊服務資源取得連接字串。 在左側瀏覽至 Keys 索引標籤。複製 Connection stringPrimary key 欄位。 connection string格式為endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key}

截圖,顯示Azure入口網站中的一個Azure Communication Services資源,在「主鍵」區塊中查看「連線字串」欄位。

將環境變數 COMMUNICATION_SERVICES_CONNECTION_STRING 設為你的connection string值。
開啟主控台視窗並輸入下列命令:

setx COMMUNICATION_SERVICES_CONNECTION_STRING "<your connection string>"

想了解如何為系統設定環境變數,請依照 將你的connection string存於環境變數的步驟。

若要具現化 NotificationMessagesClient,請將下列程式碼新增至 main 方法:

// You can get your connection string from your resource in the Azure portal.
String connectionString = System.getenv("COMMUNICATION_SERVICES_CONNECTION_STRING");

NotificationMessagesClient notificationClient = new NotificationMessagesClientBuilder()
    .connectionString(connectionString)
    .buildClient();

設定頻道註冊識別碼

頻道註冊識別碼 GUID 是在頻道註冊期間建立。 你可以在 Azure Communication Services 資源的 Channels 標籤下的入口網站查詢。

顯示 Azure入口網站中的 Azure 通訊服務資源,及查看「管道」索引標籤的螢幕截圖。請注意「管道識別碼」欄位的複製動作。

將其指派給名為 channelRegistrationId 的變數。

String channelRegistrationId = "<your channel registration id GUID>";

設定收件者清單

您需要提供一個與 WhatsApp 帳戶相關的真實電話號碼,或是商務範圍使用者識別碼 (BSUID)。 此 WhatsApp 帳戶會接收本文中傳送的文字和媒體訊息。 在本文中,此電話號碼可以是您的個人電話號碼。

收件者電話號碼不能是與 WhatsApp 頻道註冊相關聯的商務電話號碼 (傳送者識別碼)。 傳送者識別碼會顯示為傳送給收件者之文字和媒體訊息的傳送者。

電話號碼應包含國碼 (地區碼)。 如需電話號碼格式的詳細資訊,請參閱 whatsApp 文件中的電話號碼格式

注意

目前收件人名單中只支援一個電話號碼或 BSUID。

建立如下的收件者清單:

List<String> recipientList = new ArrayList<>();
recipientList.add("<to WhatsApp phone number or BSUID>");

使用電話號碼的範例:

// Example only
List<String> recipientList = new ArrayList<>();
recipientList.add("+14255550199");

使用BSUID的範例:

// Example only
List<String> recipientList = new ArrayList<>();
recipientList.add("US.13491208655302741918");

注意

自 2026 年 6 月起,將可向 BSUID 發送訊息。 在那之前,請用電話號碼作為收件人。

欲了解更多關於 BSUID 的資訊,請參閱 WhatsApp 使用者名稱與 BSUID

將文字訊息傳送給 WhatsApp 使用者

訊息 SDK 允許 Contoso 傳送 WhatsApp 文字訊息,這些訊息是由 WhatsApp 使用者起始的。 若要傳送文字訊息,需要以下詳細資料:

在此範例中,我們會以文字回復 WhatsApp 使用者 "Thanks for your feedback.\n From Notification Messaging SDK."

重要

若要將文字訊息傳送給 WhatsApp 使用者,WhatsApp 使用者必須先將訊息傳送至 WhatsApp Business 帳戶。 如需詳細資訊,請參閱開始在企業與 WhatsApp 使用者之間傳送訊息

組合並傳送簡訊:

// Assemble text message
TextNotificationContent textContent = new TextNotificationContent(channelRegistrationId, recipientList, "“Thanks for your feedback.\n From Notification Messaging SDK");

// Send text message
SendMessageResult textMessageResult = notificationClient.send(textContent);

// Process result
for (MessageReceipt messageReceipt : textMessageResult.getReceipts()) {
    System.out.println("Message sent to:" + messageReceipt.getTo() + " and message id:" + messageReceipt.getMessageId());
}

將影像媒體訊息傳送至 WhatsApp 使用者

訊息 SDK 可讓 Contoso 將媒體(影像、視訊、音訊或檔)訊息傳送給 WhatsApp 使用者。 若要傳送內嵌媒體訊息,您需要:

重要

從 SDK 1.1.0 版起,MediaNotificationContent 將被淘汰,不再用於圖像。 我們鼓勵您使用 ImageNotificationContent 來傳送影像。 探索其他媒體類型的其他內容特定類別,例如 DocumentNotificationContentVideoNotificationContentAudioNotificationContent

重要

若要將影像訊息傳送至 WhatsApp 使用者,WhatsApp 用戶必須先將訊息傳送至 WhatsApp 商務帳戶。 如需詳細資訊,請參閱開始在企業與 WhatsApp 使用者之間傳送訊息

組合並傳送影像訊息:

// Assemble image message
String imageUrl = "https://example.com/image.jpg";
ImageNotificationContent imageContent = new ImageNotificationContent(channelRegistrationId, recipientList, imageUrl);

// Send image message
SendMessageResult imageMessageResult = notificationClient.send(imageContent);

// Process result
for (MessageReceipt messageReceipt : imageMessageResult.getReceipts()) {
    System.out.println("Message sent to:" + messageReceipt.getTo() + " and message id:" + messageReceipt.getMessageId());
}

將視訊媒體訊息傳送至 WhatsApp 使用者

訊息 SDK 可讓 Contoso 將媒體(影像、視訊、音訊或檔)訊息傳送給 WhatsApp 使用者。 若要傳送內嵌媒體訊息,您需要:

重要

若要將影片訊息傳送至 WhatsApp 使用者,WhatsApp 用戶必須先將訊息傳送至 WhatsApp 商務帳戶。 如需詳細資訊,請參閱開始在企業與 WhatsApp 使用者之間傳送訊息

組合並傳送影片訊息:

// Assemble video message
String videoUrl = "https://example.com/video.mp4";
VideoNotificationContent videoContent = new VideoNotificationContent(channelRegistrationId, recipientList, videoUrl);

// Send video message
SendMessageResult videoMessageResult = notificationClient.send(videoContent);

// Process result
for (MessageReceipt messageReceipt : videoMessageResult.getReceipts()) {
    System.out.println("Message sent to:" + messageReceipt.getTo() + " and message id:" + messageReceipt.getMessageId());
}

將音訊媒體訊息傳送至 WhatsApp 使用者

訊息 SDK 可讓 Contoso 將媒體(影像、視訊、音訊或檔)訊息傳送給 WhatsApp 使用者。 若要傳送內嵌媒體訊息,您需要:

重要

若要將音訊訊息傳送至 WhatsApp 使用者,WhatsApp 用戶必須先將訊息傳送至 WhatsApp 商務帳戶。 如需詳細資訊,請參閱開始在企業與 WhatsApp 使用者之間傳送訊息

組合並傳送音訊訊息:

// Assemble audio message
String audioUrl = "https://example.com/audio.mp3";
AudioNotificationContent audioContent = new AudioNotificationContent(channelRegistrationId, recipientList, audioUrl);

// Send audio message
SendMessageResult audioMessageResult = notificationClient.send(audioContent);

// Process result
for (MessageReceipt messageReceipt : audioMessageResult.getReceipts()) {
    System.out.println("Message sent to:" + messageReceipt.getTo() + " and message id:" + messageReceipt.getMessageId());
}

將文件媒體訊息傳送至 WhatsApp 使用者

訊息 SDK 可讓 Contoso 將媒體(影像、視訊、音訊或檔)訊息傳送給 WhatsApp 使用者。 若要傳送內嵌媒體訊息,您需要:

重要

若要將文件訊息傳送至 WhatsApp 使用者,WhatsApp 用戶必須先將訊息傳送至 WhatsApp 商務帳戶。 如需詳細資訊,請參閱開始在企業與 WhatsApp 使用者之間傳送訊息

組合並傳送檔案訊息:

// Assemble document message
String docUrl = "https://example.com/document.pdf";
DocumentNotificationContent docContent = new DocumentNotificationContent(channelRegistrationId, recipientList, docUrl);

// Send document message
SendMessageResult docMessageResult = notificationClient.send(docContent);

// Process result
for (MessageReceipt messageReceipt : docMessageResult.getReceipts()) {
    System.out.println("Message sent to:" + messageReceipt.getTo() + " and message id:" + messageReceipt.getMessageId());
}

執行程式碼

  1. 開啟包含檔案的 pom.xml 目錄,並使用 mvn 命令編譯專案。

    mvn compile
    
  2. 藉由執行下列 mvn 命令來執行應用程式。

    mvn exec:java -D"exec.mainClass"="com.communication.quickstart.App" -D"exec.cleanupDaemonThreads"="false"
    

完整範例程式碼

您可在 GitHub 中找到 Azure 訊息用戶端程式庫的 Java 最終版本

必要條件

設置中

建立新的 Node.js 應用程式

  1. 為您的應用程式建立新的目錄,並在終端機或命令視窗中開啟它。

  2. 執行下列命令。

    mkdir advance-messages-quickstart && cd advance-messages-quickstart
    
  3. 執行下列命令以建立 package.json 具有預設設定的檔案。

    npm init -y
    
  4. 使用文字編輯器在專案根目錄中建立名為 send-messages.js 的檔案。

  5. 將下列代碼段新增至 檔案 send-messages.js

    async function main() {
        // Quickstart code goes here.
    }
    
    main().catch((error) => {
        console.error("Encountered an error while sending message: ", error);
        process.exit(1);
    });
    

完成下一節,將此範例的原始程式碼新增至您所建立的 send-messages.js 檔案。

安裝套件

請使用 npm install 指令安裝 Azure Communication Services Advance Messaging SDK for JavaScript。

npm install @azure-rest/communication-messages --save

--save 選項會在您的 package.json 檔案中,將程式庫列為相依性。

程式碼範例

請遵循下列步驟,將必要的代碼段新增至檔案 send-messages.js 的主要函式。

開始在企業與 WhatsApp 使用者之間傳送訊息

WhatsApp Business 帳戶與 WhatsApp 使用者之間的交談可以透過下列兩種方式來開始:

  • 企業將範本訊息傳送給 WhatsApp 使用者。
  • WhatsApp 使用者可以將任何訊息發送至商業號碼。

不論交談如何開始,企業只能傳送範本訊息,直到使用者傳送訊息給企業為止。只有在使用者傳送訊息給企業之後,企業才能在作用中交談期間將文字或媒體訊息傳送給使用者。 一旦 24 小時交談視窗過期,就必須重新開始交談。 若要深入了解交談,請參閱 WhatsApp Business Platform 中的定義。

驗證用戶端

以下程式碼使用 dotenv 套件,從名為 COMMUNICATION_SERVICES_CONNECTION_STRING 的環境變數取得該資源的connection string。

為了簡化起見,本文使用connection string來進行認證。 在生產環境中,我們建議使用服務主體

從 Azure 入口網站中的 Azure 通訊服務資源取得連接字串。 在左側瀏覽至 Keys 索引標籤。複製 Connection stringPrimary key 欄位。 connection string格式為endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key}

截圖,顯示Azure入口網站中的一個Azure Communication Services資源,在「主鍵」區塊中查看「連線字串」欄位。

將環境變數 COMMUNICATION_SERVICES_CONNECTION_STRING 設為你的connection string值。
開啟主控台視窗並輸入下列命令:

setx COMMUNICATION_SERVICES_CONNECTION_STRING "<your connection string>"

想了解如何為系統設定環境變數,請依照 將你的connection string存於環境變數的步驟。

若要具現化 NotificationClient,請將下列程式代碼新增至 Main 方法:

const NotificationClient = require("@azure-rest/communication-messages").default;

// Set Connection string
const connectionString = process.env["COMMUNICATION_SERVICES_CONNECTION_STRING"];

// Instantiate the client
const client = NotificationClient(connectionString);

設定頻道註冊識別碼

頻道註冊識別碼 GUID 是在頻道註冊期間建立。 你可以在 Azure Communication Services 資源的 Channels 標籤下的入口網站查詢。

顯示 Azure入口網站中的 Azure 通訊服務資源,及查看「管道」索引標籤的螢幕截圖。請注意「管道識別碼」欄位的複製動作。

將其指派給名為 channelRegistrationId 的變數。

const channelRegistrationId = "<your channel registration id GUID>";

設定收件者清單

您需要提供一個與 WhatsApp 帳戶相關的真實電話號碼,或是商務範圍使用者識別碼 (BSUID)。 此 WhatsApp 帳戶會接收本文中所傳送的範本、文字和媒體訊息。 在本文中,此電話號碼可以是您的個人電話號碼。

收件者電話號碼不能是與 WhatsApp 頻道註冊相關聯的商務電話號碼 (傳送者識別碼)。 傳送者識別碼會顯示為傳送給收件者之文字和媒體訊息的傳送者。

電話號碼應包含國碼 (地區碼)。 如需電話號碼格式的詳細資訊,請參閱 whatsApp 文件中的電話號碼格式

注意

目前收件人名單中只支援一個電話號碼或 BSUID。

建立如下的收件者清單:

const recipientList = ["<to WhatsApp phone number or BSUID>"];

使用電話號碼的範例:

// Example only
const recipientList = ["+14255550199"];

使用BSUID的範例:

// Example only
const recipientList = ["US.13491208655302741918"];

注意

自 2026 年 6 月起,將可向 BSUID 發送訊息。 在那之前,請用電話號碼作為收件人。

欲了解更多關於 BSUID 的資訊,請參閱 WhatsApp 使用者名稱與 BSUID

重要

若要將訊息傳送至 WhatsApp 使用者,WhatsApp 用戶必須先將訊息傳送至 WhatsApp 商務帳戶。 如需詳細資訊,請參閱開始在企業與 WhatsApp 使用者之間傳送訊息

將文字訊息傳送給 WhatsApp 使用者

訊息 SDK 可讓 Contoso 在 WhatsApp 使用者起始時傳送文字 WhatsApp 訊息。 若要傳送簡訊:

在此範例中,我們會以文字回復 WhatsApp 使用者 "Thanks for your feedback.\n From Notification Messaging SDK."

組合並傳送簡訊:

// Send text message
const textMessageResult = await client.path("/messages/notifications:send").post({
    contentType: "application/json",
    body: {
        channelRegistrationId: channelRegistrationId,
        to: recipientList,
        kind: "text",
        content: "Thanks for your feedback.\n From Notification Messaging SDK"
    }
});

// Process result
if (textMessageResult.status === "202") {
    textMessageResult.body.receipts.forEach((receipt) => {
        console.log("Message sent to:"+receipt.to+" with message id:"+receipt.messageId);
    });
} else {
    throw new Error("Failed to send message");
}

將影像媒體訊息傳送至 WhatsApp 使用者

訊息 SDK 可讓 Contoso 將媒體(影像、視訊、音訊或檔)訊息傳送給 WhatsApp 使用者。 若要傳送內嵌媒體訊息,您需要:

重要

從 SDK 版本 2.0.0 開始,MediaNotificationContent 將不再推薦用於影像。 我們鼓勵您使用 ImageNotificationContent 來傳送影像。 探索其他媒體類型的其他內容特定類別,例如 DocumentNotificationContentVideoNotificationContentAudioNotificationContent

若要傳送影像訊息,請提供影像的URL。 例如:

const url = "https://example.com/image.jpg";

將媒體訊息組合並傳送:

// Send image message
const mediaMessageResult = await client.path("/messages/notifications:send").post({
    contentType: "application/json",
    body: {
        channelRegistrationId: channelRegistrationId,
        to: recipientList,
        kind: "image",
        mediaUri: url
    }
});

// Process result
if (mediaMessageResult.status === "202") {
    mediaMessageResult.body.receipts.forEach((receipt) => {
        console.log("Message sent to:"+receipt.to+" with message id:"+receipt.messageId);
    });
} else {
    throw new Error("Failed to send message");
}

將視訊媒體訊息傳送至 WhatsApp 使用者

訊息 SDK 可讓 Contoso 將媒體(影像、視訊、音訊或檔)訊息傳送給 WhatsApp 使用者。 若要傳送內嵌媒體訊息,您需要:

若要傳送影片訊息,請提供影片的URL。 例如,

const url = "https://example.com/video.mp4";

組合並傳送影片訊息:

// Send video message
const mediaMessageResult = await client.path("/messages/notifications:send").post({
    contentType: "application/json",
    body: {
        channelRegistrationId: channelRegistrationId,
        to: recipientList,
        kind: "video",
        mediaUri: url
    }
});

// Process result
if (mediaMessageResult.status === "202") {
    mediaMessageResult.body.receipts.forEach((receipt) => {
        console.log("Message sent to:"+receipt.to+" with message id:"+receipt.messageId);
    });
} else {
    throw new Error("Failed to send message");
}

將音訊媒體訊息傳送至 WhatsApp 使用者

訊息 SDK 可讓 Contoso 將媒體(影像、視訊、音訊或檔)訊息傳送給 WhatsApp 使用者。 若要傳送內嵌媒體訊息,您需要:

若要傳送音訊訊息,請提供音訊檔案的URL。 例如:

const url = "https://example.com/audio.mp3";

組合並傳送音訊訊息:

// Send audio message
const mediaMessageResult = await client.path("/messages/notifications:send").post({
    contentType: "application/json",
    body: {
        channelRegistrationId: channelRegistrationId,
        to: recipientList,
        kind: "audio",
        mediaUri: url
    }
});

// Process result
if (mediaMessageResult.status === "202") {
    mediaMessageResult.body.receipts.forEach((receipt) => {
        console.log("Message sent to:"+receipt.to+" with message id:"+receipt.messageId);
    });
} else {
    throw new Error("Failed to send message");
}

將文件媒體訊息傳送至 WhatsApp 使用者

訊息 SDK 可讓 Contoso 將媒體(影像、視訊、音訊或檔)訊息傳送給 WhatsApp 使用者。 若要傳送內嵌媒體訊息,您需要:

若要傳送文件訊息,請提供檔的URL。 例如,

const url = "https://example.com/document.pdf";

組合並傳送檔案訊息:

// Send document message
const mediaMessageResult = await client.path("/messages/notifications:send").post({
    contentType: "application/json",
    body: {
        channelRegistrationId: channelRegistrationId,
        to: recipientList,
        kind: "document",
        mediaUri: url
    }
});

// Process result
if (mediaMessageResult.status === "202") {
    mediaMessageResult.body.receipts.forEach((receipt) => {
        console.log("Message sent to:"+receipt.to+" with message id:"+receipt.messageId);
    });
} else {
    throw new Error("Failed to send message");
}

執行程式碼

使用 node 命令來執行您新增至 send-messages.js 檔案的程式碼。

node ./send-messages.js

完整範例程式碼

在 GitHub Messages Services 用戶端函式庫範例中取得 JavaScript 的最終程式碼。

必要條件

設置中

建立一個新的 Python 應用程式

在終端機或主控台視窗中,為您的應用程式建立新資料夾並加以開啟。

mkdir messages-quickstart && cd messages-quickstart

安裝套件

請使用 Python 的 Azure Communication Messages 用戶端函式庫版本 1.1.0 或以上。

從主控台提示字元中,執行下列命令:

pip install azure-communication-messages

針對 互動消息、反應和貼圖,請使用下列 Beta 版本:

pip install azure-communication-messages==1.2.0b1

設定應用程式架構

建立名為 messages-quickstart.py 的新檔案,並新增基本程式結構。

type nul > messages-quickstart.py   

基本程式結構

import os

class MessagesQuickstart(object):
    print("Azure Communication Services - Advanced Messages SDK Quickstart")

if __name__ == '__main__':
    messages = MessagesQuickstart()

物件模型

以下類別與介面處理 Azure Communication Services Messages SDK for Python 的一些主要功能。

類別名稱 描述
NotificationMessagesClient 連接你的 Azure Communication Services 資源。 它會傳送訊息。
MessageTemplate 定義您使用的範本,以及訊息範本屬性的內容。
TemplateNotificationContent 定義您想要傳送之範本訊息的「誰」和「內容」。
TextNotificationContent 定義您想要傳送之文字訊息的「誰」和「內容」。
ImageNotificationContent 定義您想要傳送之影像媒體訊息的「誰」和「內容」。
DocumentNotificationContent 定義您要傳送之文件媒體訊息的「誰」和「內容」。
VideoNotificationContent 定義您想要傳送之視訊媒體訊息的「誰」和「內容」。
AudioNotificationContent 定義您想要傳送之音訊媒體訊息的「誰」和「內容」。

注意

欲了解更多資訊,請參閱Python參考Azure SDKmessages Package

一般設定

請遵循下列步驟,將必要的代碼段新增至 messages-quickstart.py Python 程式。

驗證用戶端

傳送的訊息會使用 NotificationMessagesClient。 NotificationMessagesClient 驗證會使用您從 Azure portal.F 中 Azure 通訊服務資源取得的連接字串進行驗證。

如需有關連接字串的更多資訊,請參閱存取連接字串和服務端點

從 Azure 入口網站取得 Azure 通訊資源連接字串,如同截圖所顯示。 在左側瀏覽至 Keys 索引標籤。複製主索引鍵的 Connection string 欄位。 connection string格式為endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key}

顯示 Azure 入口網站中的 Azure 通訊服務資源,及查看「金鑰」區段中「主要金鑰」欄位的螢幕截圖。

將環境變數 COMMUNICATION_SERVICES_CONNECTION_STRING 設為你的connection string值。
開啟主控台視窗並輸入下列命令:

setx COMMUNICATION_SERVICES_CONNECTION_STRING "<your connection string>"

新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 舉例來說,如果你用 Visual Studio 當編輯器,執行範例前先重新啟動 Visual Studio。

想了解如何為系統設定環境變數,請依照 將你的connection string存於環境變數的步驟。

    # Get a connection string to our Azure Communication Services resource.
    connection_string = os.getenv("COMMUNICATION_SERVICES_CONNECTION_STRING")
    
    def send_template_message(self):
        from azure.communication.messages import NotificationMessagesClient

        # Create NotificationMessagesClient Client
        messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)

設定頻道註冊識別碼

您在通道註冊期間建立了通道註冊標識碼 GUID。 在您的 Azure Communication Services 資源的 Channels 分頁中,您可以找到它。

顯示 Azure入口網站中的 Azure 通訊服務資源,及查看「管道」索引標籤的螢幕截圖。請注意「管道識別碼」欄位的複製動作。

將其指派給名為 channelRegistrationId 的變數。

    channelRegistrationId = os.getenv("WHATSAPP_CHANNEL_ID_GUID")

設定收件者清單

您需要提供一個與 WhatsApp 帳戶相關的有效電話號碼,或是商務範圍使用者識別碼 (BSUID)。 此 WhatsApp 帳戶會接收本文中所傳送的範本、文字和媒體訊息。

在此範例中,您可以使用個人電話號碼。

收件者電話號碼不能是與 WhatsApp 頻道註冊相關聯的商務電話號碼 (傳送者識別碼)。 傳送者識別碼會顯示為傳送給收件者之文字和媒體訊息的傳送者。

電話號碼必須包含國家/地區代碼。 如需電話號碼格式的詳細資訊,請參閱 WhatsApp 檔中的 電話號碼格式

注意

目前收件人名單中只支援一個電話號碼或 BSUID。

設定如下的收件者清單:

    phone_number = os.getenv("RECIPIENT_WHATSAPP_PHONE_NUMBER")

電話號碼使用範例:

    # Example only
    to=[self.phone_number],

BSUID 的使用範例:

    # Example only
    to=["US.13491208655302741918"],

注意

自 2026 年 6 月起,將可向 BSUID 發送訊息。 在那之前,請用電話號碼作為收件人。

欲了解更多關於 BSUID 的資訊,請參閱 WhatsApp 使用者名稱與 BSUID

開始在企業與 WhatsApp 使用者之間傳送訊息

WhatsApp Business 帳戶與 WhatsApp 使用者之間的交談可以透過下列兩種方式來開始:

  • 企業將範本訊息傳送給 WhatsApp 使用者。
  • WhatsApp 使用者可以將任何訊息發送至商業號碼。

企業無法起始互動式交談。 企業只能在收到來自使用者的訊息之後傳送互動式訊息。 企業只能在進行中對話期間,向使用者傳送互動訊息。 一旦 24 小時交談視窗到期,只有使用者可以重新啟動互動式交談。 如需交談的詳細資訊,請參閱 WhatsApp Business Platform 的定義

若要從您的個人 WhatsApp 帳戶起始互動式交談,請將訊息傳送至您的商務號碼(寄件人標識符)。

Web 上檢視的 WhatsApp 交談,其中顯示傳送至 WhatsApp Business 帳戶號碼的使用者訊息。

程式碼範例

請遵循下列步驟,將必要的代碼段新增至 messages-quickstart.py python 程式。

將文字訊息傳送給 WhatsApp 使用者

Messages SDK 可讓 Contoso 在 WhatsApp 使用者起始時傳送文字 WhatsApp 訊息。 若要傳送簡訊:

重要

若要將文字訊息傳送給 WhatsApp 使用者,WhatsApp 使用者必須先將訊息傳送至 WhatsApp Business 帳戶。 如需詳細資訊,請參閱開始在企業與 WhatsApp 使用者之間傳送訊息

在此範例中,我們會以文字回復 WhatsApp 使用者 "Thanks for your feedback.\n From Notification Messaging SDK."

    def send_text_message(self):
        from azure.communication.messages import NotificationMessagesClient
        from azure.communication.messages.models import ( TextNotificationContent)

        # Create NotificationMessagesClient Client
        messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
        text_options = TextNotificationContent (
            channel_registration_id=self.channelRegistrationId,
            to= [self.phone_number],
            content="Thanks for your feedback.\n From Notification Messaging SDK",
        )
        
        # calling send() with whatsapp message details
        message_responses = messaging_client.send(text_options)
        response = message_responses.receipts[0]
        
        if (response is not None):
            print("WhatsApp Text Message with message id {} was successfully sent to {}."
            .format(response.message_id, response.to))
        else:
            print("Message failed to send")

若要執行 send_text_message(),請更新 main 方法

    #Calling send_text_message()
    messages.send_text_message()

將影像媒體訊息傳送至 WhatsApp 使用者

Messages SDK 可讓 Contoso 將影像 WhatsApp 訊息傳送給 WhatsApp 使用者。 若要傳送影像內嵌訊息:

重要

若要將文字訊息傳送給 WhatsApp 使用者,WhatsApp 使用者必須先將訊息傳送至 WhatsApp Business 帳戶。 如需詳細資訊,請參閱開始在企業與 WhatsApp 使用者之間傳送訊息

傳送媒體 WhatsApp 訊息時所使用的範例 media_uri

input_media_uri: str = "https://aka.ms/acsicon1"

    def send_image_message(self):
        from azure.communication.messages import NotificationMessagesClient
        from azure.communication.messages.models import ( ImageNotificationContent)

        # Create NotificationMessagesClient Client
        messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
        input_media_uri: str = "https://aka.ms/acsicon1"
        image_message_options = ImageNotificationContent(
            channel_registration_id=self.channelRegistrationId,
            to=[self.phone_number],
            media_uri=input_media_uri
        )

        # calling send() with whatsapp image message
        message_responses = messaging_client.send(image_message_options)
        response = message_responses.receipts[0]
        
        if (response is not None):
            print("WhatsApp Image containing Message with message id {} was successfully sent to {}"
            .format(response.message_id, response.to))
        else:
            print("Message failed to send")

若要執行 send_text_message(),請更新 main 方法

    # Calling send_image_message()
    messages.send_image_message()

將文件媒體訊息傳送至 WhatsApp 使用者

訊息 SDK 可讓 Contoso 將檔 WhatsApp 訊息傳送給 WhatsApp 使用者。 若要傳送檔內嵌訊息:

重要

若要將文件訊息傳送至 WhatsApp 使用者,WhatsApp 用戶必須先將訊息傳送至 WhatsApp 商務帳戶。 如需詳細資訊,請參閱開始在企業與 WhatsApp 使用者之間傳送訊息

傳送媒體 WhatsApp 訊息時所使用的範例 media_uri

input_media_uri: str = "##DocumentLinkPlaceholder##"

    def send_document_message(self):
        from azure.communication.messages import NotificationMessagesClient
        from azure.communication.messages.models import ( DocumentNotificationContent)

        # Create NotificationMessagesClient Client
        messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
        input_media_uri: str = "##DocumentLinkPlaceholder##"
        documents_options = DocumentNotificationContent(
            channel_registration_id=self.channelRegistrationId,
            to=[self.phone_number],
            caption="Hello World via Advanced Messaging SDK.This is document message",
            file_name="Product roadmap timeline.pptx",
            media_uri=input_media_uri,
        )

        # calling send() with whatsapp image message
        message_responses = messaging_client.send(documents_options)
        response = message_responses.receipts[0]
        
        if (response is not None):
            print("WhatsApp Document containing Message with message id {} was successfully sent to {}"
            .format(response.message_id, response.to))
        else:
            print("Message failed to send")

若要執行 send_text_message(),請更新 main 方法

    # Calling send_image_message()
    messages.send_image_message()

將音訊媒體訊息傳送至 WhatsApp 使用者

Messages SDK 可讓 Contoso 將影像 WhatsApp 訊息傳送給 WhatsApp 使用者。 若要傳送音訊內嵌訊息:

重要

若要將音訊訊息傳送至 WhatsApp 使用者,WhatsApp 用戶必須先將訊息傳送至 WhatsApp 商務帳戶。 如需詳細資訊,請參閱開始在企業與 WhatsApp 使用者之間傳送訊息

傳送媒體 WhatsApp 訊息時所使用的範例 media_uri

input_media_uri: str = "##AudioLinkPlaceholder##"

    def send_audio_message(self):
        from azure.communication.messages import NotificationMessagesClient
        from azure.communication.messages.models import ( AudioNotificationContent)

        # Create NotificationMessagesClient Client
        messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
        input_media_uri: str = "##AudioLinkPlaceholder##"
        audio_options = AudioNotificationContent(
            channel_registration_id=self.channelRegistrationId,
            to=[self.phone_number],
            media_uri=input_media_uri,
        )

        # calling send() with whatsapp image message
        message_responses = messaging_client.send(audio_options)
        response = message_responses.receipts[0]
        
        if (response is not None):
            print("WhatsApp Audio containing Message with message id {} was successfully sent to {}"
            .format(response.message_id, response.to))
        else:
            print("Message failed to send")

若要執行 send_text_message(),請更新 main 方法

    # Calling send_image_message()
    messages.send_image_message()

將視訊媒體訊息傳送至 WhatsApp 使用者

訊息 SDK 可讓 Contoso 將影片 WhatsApp 訊息傳送給 WhatsApp 使用者。 若要傳送影片內嵌訊息:

重要

若要將影片訊息傳送至 WhatsApp 使用者,WhatsApp 用戶必須先將訊息傳送至 WhatsApp 商務帳戶。 如需詳細資訊,請參閱開始在企業與 WhatsApp 使用者之間傳送訊息

傳送媒體 WhatsApp 訊息時所使用的範例 media_uri

input_media_uri: str = "##VideoLinkPlaceholder##"

    def send_video_message(self):
        from azure.communication.messages import NotificationMessagesClient
        from azure.communication.messages.models import ( VideoNotificationContent)

        # Create NotificationMessagesClient Client
        messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
        input_media_uri: str = "##VideoLinkPlaceholder##"
        video_options = VideoNotificationContent(
            channel_registration_id=self.channelRegistrationId,
            to=[self.phone_number],
            media_uri=input_media_uri,
        )

        # calling send() with whatsapp image message
        message_responses = messaging_client.send(image_message_options)
        response = message_responses.receipts[0]
        
        if (response is not None):
            print("WhatsApp Video containing Message with message id {} was successfully sent to {}"
            .format(response.message_id, response.to))
        else:
            print("Message failed to send")

若要執行 send_text_message(),請更新 main 方法

    # Calling send_image_message()
    messages.send_image_message()

執行程式碼

若要執行程式代碼,請確定您位於檔案 messages-quickstart.py 所在的目錄。

python messages-quickstart.py
Azure Communication Services - Advanced Messages Quickstart
WhatsApp Templated Message with message id <<GUID>> was successfully sent to <<ToRecipient>>
WhatsApp Text Message with message id <<GUID>> was successfully sent to <<ToRecipient>>
WhatsApp Image containing Message with message id <<GUID>> was successfully sent to <<ToRecipient>>

完整範例程式碼

注意

將範例程式代碼中的所有佔位符變數取代為您的值。

import os

class MessagesQuickstart(object):
    print("Azure Communication Services - Advanced Messages SDK Quickstart using connection string.")
    # Advanced Messages SDK implementations goes in this section.
   
    connection_string = os.getenv("COMMUNICATION_SERVICES_CONNECTION_STRING")
    phone_number = os.getenv("RECIPIENT_PHONE_NUMBER")
    channelRegistrationId = os.getenv("WHATSAPP_CHANNEL_ID")

    def send_template_message(self):
        from azure.communication.messages import NotificationMessagesClient
        from azure.communication.messages.models import ( TemplateNotificationContent , MessageTemplate )

        # client creation
        messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
        input_template: MessageTemplate = MessageTemplate(
            name="<<TEMPLATE_NAME>>",
            language="<<LANGUAGE>>")
        template_options = TemplateNotificationContent(
            channel_registration_id=self.channelRegistrationId,
            to=[self.phone_number],
            template=input_template
        )

        # calling send() with WhatsApp template details.
        message_responses = messaging_client.send(template_options)
        response = message_responses.receipts[0]
        
        if (response is not None):
            print("WhatsApp Templated Message with message id {} was successfully sent to {}"
            .format(response.message_id, response.to))
        else:
            print("Message failed to send")

    def send_text_message(self):
        from azure.communication.messages import NotificationMessagesClient
        from azure.communication.messages.models import ( TextNotificationContent )

        # client creation
        messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)

        text_options = TextNotificationContent (
            channel_registration_id=self.channelRegistrationId,
            to= [self.phone_number],
            content="Hello World via ACS Advanced Messaging SDK.",
        )
        
        # calling send() with WhatsApp message details
        message_responses = messaging_client.send(text_options)
        response = message_responses.receipts[0]
        
        if (response is not None):
            print("WhatsApp Text Message with message id {} was successfully sent to {}"
            .format(response.message_id, response.to))
        else:
            print("Message failed to send")

    def send_image_message(self):
        from azure.communication.messages import NotificationMessagesClient
        from azure.communication.messages.models import ( ImageNotificationContent)

        # Create NotificationMessagesClient Client
        messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
        input_media_uri: str = "https://aka.ms/acsicon1"
        image_message_options = ImageNotificationContent(
            channel_registration_id=self.channelRegistrationId,
            to=[self.phone_number],
            media_uri=input_media_uri
        )

        # calling send() with whatsapp image message
        message_responses = messaging_client.send(image_message_options)
        response = message_responses.receipts[0]
        
        if (response is not None):
            print("WhatsApp Image containing Message with message id {} was successfully sent to {}"
            .format(response.message_id, response.to))
        else:
            print("Message failed to send")
    
    def send_document_message(self):
        from azure.communication.messages import NotificationMessagesClient
        from azure.communication.messages.models import ( DocumentNotificationContent)

        # Create NotificationMessagesClient Client
        messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
        input_media_uri: str = "##DocumentLinkPlaceholder##"
        documents_options = DocumentNotificationContent(
            channel_registration_id=self.channelRegistrationId,
            to=[self.phone_number],
            caption="Hello World via Advanced Messaging SDK.This is document message",
            file_name="Product roadmap timeline.pptx",
            media_uri=input_media_uri,
        )

        # calling send() with whatsapp image message
        message_responses = messaging_client.send(documents_options)
        response = message_responses.receipts[0]
        
        if (response is not None):
            print("WhatsApp Document containing Message with message id {} was successfully sent to {}"
            .format(response.message_id, response.to))
        else:
            print("Message failed to send")

    def send_audio_message(self):
        from azure.communication.messages import NotificationMessagesClient
        from azure.communication.messages.models import ( AudioNotificationContent)

        # Create NotificationMessagesClient Client
        messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
        input_media_uri: str = "##AudioLinkPlaceholder##"
        audio_options = AudioNotificationContent(
            channel_registration_id=self.channelRegistrationId,
            to=[self.phone_number],
            media_uri=input_media_uri,
        )

        # calling send() with whatsapp image message
        message_responses = messaging_client.send(audio_options)
        response = message_responses.receipts[0]
        
        if (response is not None):
            print("WhatsApp Audio containing Message with message id {} was successfully sent to {}"
            .format(response.message_id, response.to))
        else:
            print("Message failed to send")

    def send_video_message(self):
        from azure.communication.messages import NotificationMessagesClient
        from azure.communication.messages.models import ( VideoNotificationContent)

        # Create NotificationMessagesClient Client
        messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
        input_media_uri: str = "##VideoLinkPlaceholder##"
        video_options = VideoNotificationContent(
            channel_registration_id=self.channelRegistrationId,
            to=[self.phone_number],
            media_uri=input_media_uri,
        )

        # calling send() with whatsapp image message
        message_responses = messaging_client.send(image_message_options)
        response = message_responses.receipts[0]
        
        if (response is not None):
            print("WhatsApp Video containing Message with message id {} was successfully sent to {}"
            .format(response.message_id, response.to))
        else:
            print("Message failed to send")

if __name__ == '__main__':
    messages = MessagesQuickstart()
    messages.send_template_message()
    messages.send_text_message()
    messages.send_image_message()
    messages.send_document_message()
    messages.send_audio_message()
    messages.send_video_message()

其他範例

你可以在GitHub上查看並下載其他範例代碼,Python Messages SDK

下一步