使用進階傳訊傳送文字和媒體 WhatsApp 訊息
Azure 通訊服務可讓您傳送和接收 WhatsApp 訊息。 本文說明如何將您的應用程式與 Azure 通訊進階訊息 SDK 整合,以開始傳送和接收 WhatsApp 訊息。 完成本文會產生 Azure 帳戶中幾美分或更少的成本。
必要條件
- 向 Azure 通訊服務資源註冊的 WhatsApp Business 帳戶。
- 要接收訊息的作用中 WhatsApp 電話號碼。
- .NET 開發環境,例如 Visual Studio、 Visual Studio Code 或 .NET CLI。
設定環境
建立 .NET 專案
若要建立專案,請遵循使用 Visual Studio 建立 .NET 主控台應用程式的教學課程。
若要編譯程式碼,請按 Ctrl+F7。
Install the package
將 Azure.Communication.Messages NuGet 套件安裝至 C# 專案。
- 在
Project
>Manage NuGet Packages...
開啟 NuGet 套件管理員。 - 搜尋套件
Azure.Communication.Messages
。 - 安裝最新版本。
設定應用程式架構
在文字編輯器中開啟 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;
物件模型
下列類別和介面會處理適用於 .NET 的 Azure 通訊服務進階傳訊 SDK 的一些主要功能。
類別名稱 | 描述 |
---|---|
NotificationMessagesClient |
線上到您的 Azure 通訊服務 資源。 它會傳送訊息。 |
MessageTemplate |
定義您使用的範本,以及訊息範本屬性的內容。 |
TemplateNotificationContent |
定義您想要傳送之範本訊息的「誰」和「內容」。 |
TextNotificationContent |
定義您想要傳送之文字訊息的「誰」和「內容」。 |
ImageNotificationContent |
定義您想要傳送之影像媒體訊息的「誰」和「內容」。 |
DocumentNotificationContent |
定義您要傳送之文件媒體訊息的「誰」和「內容」。 |
VideoNotificationContent |
定義您想要傳送之視訊媒體訊息的「誰」和「內容」。 |
AudioNotificationContent |
定義您想要傳送之音訊媒體訊息的「誰」和「內容」。 |
注意
如需詳細資訊,請參閱適用於 .NET 的 Azure SDK 參考 Azure.Communication.Messages 命名空間。
一般設定
請遵循下列步驟,將必要的代碼段新增至 messages-quickstart.py python 程式。
- 驗證用戶端。
- 設定通道註冊標識碼。
- 設定收件者清單。
- 開始在企業與 WhatsApp 用戶之間傳送訊息。
驗證用戶端
訊息 SDK 會使用 NotificationMessagesClient
來傳送訊息。 方法NotificationMessagesClient
會使用從 Azure 入口網站 中 Azure 通訊服務 資源取得的 連接字串 進行驗證。 如需 連接字串 的詳細資訊,請參閱 access-your-connection-strings-and-service-endpoints。
為了簡單起見,本快速入門會使用連接字串進行驗證。 在實際執行環境中,我們建議服務主體。
在 Azure 入口網站中從 Azure 通訊服務資源取得連接字串。 在左側瀏覽至 Keys
索引標籤。複製主索引鍵的 Connection string
欄位。 連接字串格式如下:endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key}
。
將環境變數 COMMUNICATION_SERVICES_CONNECTION_STRING
設定為連接字串的值。
開啟主控台視窗並輸入下列命令:
setx COMMUNICATION_SERVICES_CONNECTION_STRING "<your connection string>"
新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 例如,如果您使用 Visual Studio 作為編輯器,請在執行範例前重新啟動 Visual Studio。
如需如何為系統設定環境變數的詳細資訊,請遵循將連接字串儲存在環境變數中的步驟。
若要具現化 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 通訊服務 資源的 [通道] 索引標籤上,在入口網站中尋找它。
將其指派給名為 channelRegistrationId 的變數。
var channelRegistrationId = new Guid("<your channel registration ID GUID>");
設定收件者清單
您必須提供與 WhatsApp 帳戶相關聯的使用中電話號碼。 此 WhatsApp 帳戶會接收本快速入門中傳送的範本、文字和媒體訊息。
在此範例中,您可以使用個人電話號碼。
收件者電話號碼不能是與 WhatsApp 頻道註冊相關聯的商務電話號碼 (傳送者識別碼)。 傳送者識別碼會顯示為傳送給收件者之文字和媒體訊息的傳送者。
電話號碼必須包含國家/地區代碼。 如需電話號碼格式的詳細資訊,請參閱 WhatsApp 檔中的 電話號碼格式。
注意
收件者清單中目前僅支援一個電話號碼。
建立如下的收件者清單:
var recipientList = new List<string> { "<to WhatsApp phone number>" };
範例:
// Example only
var recipientList = new List<string> { "+14255550199" };
開始在企業與 WhatsApp 使用者之間傳送訊息
WhatsApp Business 帳戶與 WhatsApp 使用者之間的交談可以透過下列兩種方式來開始:
- 企業將範本訊息傳送給 WhatsApp 使用者。
- WhatsApp 使用者將任何訊息傳送給企業號碼。
企業無法起始互動式交談。 企業只能在收到來自使用者的訊息之後傳送互動式訊息。 企業只能在作用中的交談期間傳送互動式訊息給使用者。 一旦 24 小時交談視窗到期,只有使用者可以重新啟動互動式交談。 如需交談的詳細資訊,請參閱 WhatsApp Business Platform 的定義。
若要從您的個人 WhatsApp 帳戶起始互動式交談,請將訊息傳送至您的商務號碼(寄件人標識符)。
程式碼範例
請遵循下列步驟,將必要的代碼段新增至檔案 Program.cs
的 Main 函式。
- 將簡訊傳送給 WhatsApp 使用者。
- 將影像媒體訊息傳送給 WhatsApp 使用者。
- 將文件媒體訊息傳送給 WhatsApp 使用者。
- 將音訊媒體訊息傳送給 WhatsApp 使用者。
- 將視訊媒體訊息傳送給 WhatsApp 使用者。
重要
若要將文字或媒體訊息傳送至 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 使用者。 若要傳送內嵌媒體訊息,您需要:
- 已驗證的 NotificationMessagesClient。
- WhatsApp 通道標識碼。
- E16 格式的收件者電話號碼。
- 影像媒體的 URI。
重要
從 SDK 1.1.0 版起, MediaNotificationContent
映射即將淘汰。 我們鼓勵您用來 ImageNotificationContent
傳送影像。 探索其他媒體類型的其他內容特定類別,例如 DocumentNotificationContent
、 VideoNotificationContent
和 AudioNotificationContent
。
組合映像訊息:
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 使用者。 若要傳送內嵌媒體訊息,您需要:
- 已驗證的 NotificationMessagesClient。
- WhatsApp 通道標識碼。
- E16 格式的收件者電話號碼。
- 媒體檔 URI。
組合檔案內容:
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 使用者。 若要傳送內嵌媒體訊息,您需要:
- 已驗證的 NotificationMessagesClient。
- WhatsApp 通道標識碼。
- E16 格式的收件者電話號碼。
- 視訊媒體的 URI。
組合影片訊息:
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 使用者。 若要傳送內嵌媒體訊息,您需要:
- 已驗證的 NotificationMessagesClient。
- WhatsApp 通道標識碼。
- E16 格式的收件者電話號碼。
- 音訊媒體的 URI。
組合音訊訊息:
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 帳戶上收到三則訊息。
- 若要編譯程式碼,請按 Ctrl+F7。
- 若要在不偵錯的情況下執行程式,請按 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");
}
}
}
必要條件
- 向 Azure 通訊服務資源註冊的 WhatsApp Business 帳戶。
- 要接收訊息的作用中 WhatsApp 電話號碼。
- Java 開發套件 (JDK) 第 8 版或更新版本。
- Apache Maven。
設定環境
若要設定傳送訊息的環境,請完成下列各節中的步驟。
建立新的 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
目錄包含專案原始碼、 src/test/java
目錄包含測試來源,而 pom.xml
檔案是專案的 Project 物件模型 (POM)。
Install the package
在文字編輯器中開啟 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 使用者
- 將影像媒體訊息傳送至 WhatsApp 使用者
- 將文件媒體訊息傳送至 WhatsApp 使用者
- 將音訊媒體訊息傳送至 WhatsApp 使用者
- 將視訊媒體訊息傳送至 WhatsApp 使用者
開始在企業與 WhatsApp 使用者之間傳送訊息
WhatsApp Business 帳戶與 WhatsApp 使用者之間的交談可以透過下列兩種方式來開始:
- 企業將範本訊息傳送給 WhatsApp 使用者。
- WhatsApp 使用者將任何訊息傳送給企業號碼。
不論交談如何開始,企業只能傳送範本訊息,直到使用者傳送訊息給企業為止。只有在使用者傳送訊息給企業之後,企業才能在作用中交談期間將文字或媒體訊息傳送給使用者。 一旦 24 小時交談視窗過期,就必須重新開始交談。 若要深入了解交談,請參閱 WhatsApp Business Platform 中的定義。
驗證用戶端
有一些不同的選項可用來驗證訊息用戶端:
若要驗證用戶端,您可以使用連接字串具現化 NotificationMessagesClient
或 MessageTemplateClient
。 您也可以使用會實作 com.azure.core.http.HttpClient
介面的任何自訂 HTTP 用戶端來初始化用戶端。
為了簡單起見,本快速入門會使用連接字串進行驗證。 在實際執行環境中,我們建議服務主體。
在 Azure 入口網站中從 Azure 通訊服務資源取得連接字串。 在左側瀏覽至 Keys
索引標籤。複製 Connection string
的 Primary key
欄位。 連接字串格式如下:endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key}
。
將環境變數 COMMUNICATION_SERVICES_CONNECTION_STRING
設定為連接字串的值。
開啟主控台視窗並輸入下列命令:
setx COMMUNICATION_SERVICES_CONNECTION_STRING "<your 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 通訊服務資源 [頻道] 索引標籤上查閱。
將其指派給名為 channelRegistrationId 的變數。
String channelRegistrationId = "<your channel registration id GUID>";
設定收件者清單
您必須提供與 WhatsApp 帳戶相關聯的真實電話號碼。 此 WhatsApp 帳戶會接收本快速入門中傳送的文字和媒體訊息。 針對本快速入門,此電話號碼可能是您的個人電話號碼。
收件者電話號碼不能是與 WhatsApp 頻道註冊相關聯的商務電話號碼 (傳送者識別碼)。 傳送者識別碼會顯示為傳送給收件者之文字和媒體訊息的傳送者。
電話號碼應包含國碼 (地區碼)。 如需電話號碼格式的詳細資訊,請參閱 whatsApp 文件中的電話號碼格式。
注意
收件者清單中目前僅支援一個電話號碼。
建立如下的收件者清單:
List<String> recipientList = new ArrayList<>();
recipientList.add("<to WhatsApp phone number>");
範例:
// Example only
List<String> recipientList = new ArrayList<>();
recipientList.add("+14255550199");
將文字訊息傳送給 WhatsApp 使用者
訊息 SDK 可讓 Contoso 傳送文字 WhatsApp 訊息,該訊息會起始 WhatsApp 使用者起始的項目。 若要傳送文字訊息,需要以下詳細資料:
- WhatsApp 頻道識別碼
- E16 格式的收件者電話號碼
- 要傳送的郵件內文/文字
在此範例中,我們會以文字回復 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 使用者。 若要傳送內嵌媒體訊息,您需要:
- WhatsApp 頻道識別碼
- E16 格式的收件者電話號碼
- 影像媒體的 URL
重要
從 SDK 1.1.0 版起, MediaNotificationContent
映射即將淘汰。 我們鼓勵您使用 ImageNotificationContent
來傳送影像。 探索其他媒體類型的其他內容特定類別,例如 DocumentNotificationContent
、 VideoNotificationContent
和 AudioNotificationContent
。
重要
若要將影像訊息傳送至 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 通道標識碼。
- E16 格式的收件者電話號碼。
- 視訊媒體的 URL。
重要
若要將影片訊息傳送至 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 通道標識碼。
- E16 格式的收件者電話號碼。
- 音訊媒體的 URL。
重要
若要將音訊訊息傳送至 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 通道標識碼。
- E16 格式的收件者電話號碼。
- 文件媒體的 URL。
重要
若要將文件訊息傳送至 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());
}
執行程式碼
開啟包含檔案的
pom.xml
目錄,並使用mvn
命令編譯專案。mvn compile
藉由執行下列
mvn
命令來執行應用程式。mvn exec:java -D"exec.mainClass"="com.communication.quickstart.App" -D"exec.cleanupDaemonThreads"="false"
完整範例程式碼
在 GitHub 上尋找本快速入門的最終程式碼。
必要條件
- 向 Azure 通訊服務資源註冊的 WhatsApp Business 帳戶。
- 要接收訊息的作用中 WhatsApp 電話號碼。
- Node.js Active LTS 和維護 LTS 版本(我們建議使用 8.11.1 和 10.14.1)。
-
Node.js建議使用中 LTS 和維護 LTS 版本(建議使用 8.11.1 和 10.14.1)
- 在終端機或命令視窗中執行
node --version
,確認已安裝 Node.js
- 在終端機或命令視窗中執行
設定
建立新的 Node.js 應用程式
為您的應用程式建立新的目錄,並在終端機或命令視窗中開啟它。
執行下列命令。
mkdir advance-messages-quickstart && cd advance-messages-quickstart
執行下列命令以建立
package.json
具有預設設定的檔案。npm init -y
使用文字編輯器在專案根目錄中建立名為
send-messages.js
的檔案。將下列代碼段新增至 檔案
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
檔案。
Install the package
使用 npm install
命令,以安裝適用於 JavaScript 的 Azure 通訊服務進階傳訊 SDK。
npm install @azure-rest/communication-messages --save
--save
選項會在您的 package.json 檔案中,將程式庫列為相依性。
程式碼範例
請遵循下列步驟,將必要的代碼段新增至檔案 send-messages.js
的主要函式。
- 開始在企業與 WhatsApp 用戶之間傳送訊息。
- 驗證用戶端。
- 設定通道註冊標識碼。
- 設定收件者清單。
- 將簡訊傳送給 WhatsApp 使用者。
- 將影像媒體訊息傳送給 WhatsApp 使用者。
- 將文件媒體訊息傳送給 WhatsApp 使用者。
- 將音訊媒體訊息傳送給 WhatsApp 使用者。
- 將視訊媒體訊息傳送給 WhatsApp 使用者。
開始在企業與 WhatsApp 使用者之間傳送訊息
WhatsApp Business 帳戶與 WhatsApp 使用者之間的交談可以透過下列兩種方式來開始:
- 企業將範本訊息傳送給 WhatsApp 使用者。
- WhatsApp 使用者將任何訊息傳送給企業號碼。
不論交談如何開始,企業只能傳送範本訊息,直到使用者傳送訊息給企業為止。只有在使用者傳送訊息給企業之後,企業才能在作用中交談期間將文字或媒體訊息傳送給使用者。 一旦 24 小時交談視窗過期,就必須重新開始交談。 若要深入了解交談,請參閱 WhatsApp Business Platform 中的定義。
驗證用戶端
以下程式碼會使用 dotenv 套件從名為 COMMUNICATION_SERVICES_CONNECTION_STRING
的環境變數中,擷取資源的連接字串。
為了簡單起見,本快速入門會使用連接字串進行驗證。 在實際執行環境中,我們建議服務主體。
在 Azure 入口網站中從 Azure 通訊服務資源取得連接字串。 在左側瀏覽至 Keys
索引標籤。複製 Connection string
的 Primary key
欄位。 連接字串格式如下:endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key}
。
將環境變數 COMMUNICATION_SERVICES_CONNECTION_STRING
設定為連接字串的值。
開啟主控台視窗並輸入下列命令:
setx COMMUNICATION_SERVICES_CONNECTION_STRING "<your 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 通訊服務資源 [頻道] 索引標籤上查閱。
將其指派給名為 channelRegistrationId 的變數。
const channelRegistrationId = "<your channel registration id GUID>";
設定收件者清單
您必須提供與 WhatsApp 帳戶相關聯的真實電話號碼。 此 WhatsApp 帳戶會接收本快速入門中傳送的範本、文字和媒體訊息。 針對本快速入門,此電話號碼可能是您的個人電話號碼。
收件者電話號碼不能是與 WhatsApp 頻道註冊相關聯的商務電話號碼 (傳送者識別碼)。 傳送者識別碼會顯示為傳送給收件者之文字和媒體訊息的傳送者。
電話號碼應包含國碼 (地區碼)。 如需電話號碼格式的詳細資訊,請參閱 whatsApp 文件中的電話號碼格式。
注意
收件者清單中目前僅支援一個電話號碼。
建立如下的收件者清單:
const recipientList = ["<to WhatsApp phone number>"];
範例:
// Example only
const recipientList = ["+14255550199"];
重要
若要將訊息傳送至 WhatsApp 使用者,WhatsApp 用戶必須先將訊息傳送至 WhatsApp 商務帳戶。 如需詳細資訊,請參閱開始在企業與 WhatsApp 使用者之間傳送訊息。
將文字訊息傳送給 WhatsApp 使用者
訊息 SDK 可讓 Contoso 在 WhatsApp 使用者起始時傳送文字 WhatsApp 訊息。 若要傳送簡訊:
- WhatsApp 通道標識碼。
- E16 格式的收件者電話號碼。
- 要傳送的訊息本文/文字。
在此範例中,我們會以文字回復 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 使用者。 若要傳送內嵌媒體訊息,您需要:
- WhatsApp 通道標識碼。
- E16 格式的收件者電話號碼。
- 影像媒體的 URL。
重要
從 SDK 2.0.0 版起, MediaNotificationContent
映射即將淘汰。 我們鼓勵您使用 ImageNotificationContent
來傳送影像。 探索其他媒體類型的其他內容特定類別,例如 DocumentNotificationContent
、 VideoNotificationContent
和 AudioNotificationContent
。
若要傳送影像訊息,請提供影像的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 使用者。 若要傳送內嵌媒體訊息,您需要:
- WhatsApp 通道標識碼。
- E16 格式的收件者電話號碼。
- 影片的 URL。
若要傳送影片訊息,請提供影片的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 使用者。 若要傳送內嵌媒體訊息,您需要:
- WhatsApp 通道標識碼。
- E16 格式的收件者電話號碼。
- 音訊媒體的 URL。
若要傳送音訊訊息,請提供音訊檔案的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 使用者。 若要傳送內嵌媒體訊息,您需要:
- WhatsApp 通道標識碼。
- E16 格式的收件者電話號碼。
- 文件媒體的 URL。
若要傳送文件訊息,請提供檔的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 上尋找本快速入門的最終程式碼。
必要條件
要接收訊息的作用中 WhatsApp 電話號碼。
適用於您作業系統的 Python (英文) 3.7+。
設定
建立新的 Python 應用程式
在終端機或主控台視窗中,為您的應用程式建立新資料夾並加以開啟。
mkdir messages-quickstart && cd messages-quickstart
Install the package
使用適用於 Python 1.1.0 或更新版本之 Azure 通訊訊息用戶端連結庫。
從主控台提示字元中,執行下列命令:
pip install azure-communication-messages
針對 InteractiveMessages、反應和貼紙,請使用下列 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()
物件模型
下列類別和介面會處理適用於 Python 的 Azure 通訊服務訊息 SDK 的一些主要功能。
類別名稱 | 描述 |
---|---|
NotificationMessagesClient |
線上到您的 Azure 通訊服務 資源。 它會傳送訊息。 |
MessageTemplate |
定義您使用的範本,以及訊息範本屬性的內容。 |
TemplateNotificationContent |
定義您想要傳送之範本訊息的「誰」和「內容」。 |
TextNotificationContent |
定義您想要傳送之文字訊息的「誰」和「內容」。 |
ImageNotificationContent |
定義您想要傳送之影像媒體訊息的「誰」和「內容」。 |
DocumentNotificationContent |
定義您要傳送之文件媒體訊息的「誰」和「內容」。 |
VideoNotificationContent |
定義您想要傳送之視訊媒體訊息的「誰」和「內容」。 |
AudioNotificationContent |
定義您想要傳送之音訊媒體訊息的「誰」和「內容」。 |
注意
如需詳細資訊,請參閱適用於 Python 的 Azure SDK 參考 訊息套件。
一般設定
請遵循下列步驟,將必要的代碼段新增至 messages-quickstart.py
Python 程式。
- 驗證用戶端。
- 設定通道註冊標識碼。
- 設定收件者清單。
- 開始在企業與 WhatsApp 用戶之間傳送訊息。
驗證用戶端
訊息傳送是使用 NotificationMessagesClient 完成。 NotificationMessagesClient 是使用在 Azure 入口網站中從 Azure 通訊服務資源取得的連接字串進行驗證。 如需連接字串的詳細資訊,請參閱存取您的連接字串和服務端點 (部分機器翻譯)。
如螢幕快照所示,從 Azure 入口網站 取得 Azure 通訊資源 連接字串。 在左側瀏覽至 Keys
索引標籤。複製主索引鍵的 Connection string
欄位。 連接字串格式如下:endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key}
。
將環境變數 COMMUNICATION_SERVICES_CONNECTION_STRING
設定為連接字串的值。
開啟主控台視窗並輸入下列命令:
setx COMMUNICATION_SERVICES_CONNECTION_STRING "<your connection string>"
新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 例如,如果您使用 Visual Studio 作為編輯器,請在執行範例前重新啟動 Visual Studio。
如需如何為系統設定環境變數的詳細資訊,請遵循將連接字串儲存在環境變數中的步驟。
# 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 通訊服務 資源的 [通道] 索引標籤。
將其指派給名為 channelRegistrationId 的變數。
channelRegistrationId = os.getenv("WHATSAPP_CHANNEL_ID_GUID")
設定收件者清單
您必須提供與 WhatsApp 帳戶相關聯的使用中電話號碼。 此 WhatsApp 帳戶會接收本快速入門中傳送的範本、文字和媒體訊息。
在此範例中,您可以使用個人電話號碼。
收件者電話號碼不能是與 WhatsApp 頻道註冊相關聯的商務電話號碼 (傳送者識別碼)。 傳送者識別碼會顯示為傳送給收件者之文字和媒體訊息的傳送者。
電話號碼必須包含國家/地區代碼。 如需電話號碼格式的詳細資訊,請參閱 WhatsApp 檔中的 電話號碼格式。
注意
收件者清單中目前僅支援一個電話號碼。
設定如下的收件者清單:
phone_number = os.getenv("RECIPIENT_WHATSAPP_PHONE_NUMBER")
使用範例:
# Example only
to=[self.phone_number],
開始在企業與 WhatsApp 使用者之間傳送訊息
WhatsApp Business 帳戶與 WhatsApp 使用者之間的交談可以透過下列兩種方式來開始:
- 企業將範本訊息傳送給 WhatsApp 使用者。
- WhatsApp 使用者將任何訊息傳送給企業號碼。
企業無法起始互動式交談。 企業只能在收到來自使用者的訊息之後傳送互動式訊息。 企業只能在作用中的交談期間傳送互動式訊息給使用者。 一旦 24 小時交談視窗到期,只有使用者可以重新啟動互動式交談。 如需交談的詳細資訊,請參閱 WhatsApp Business Platform 的定義。
若要從您的個人 WhatsApp 帳戶起始互動式交談,請將訊息傳送至您的商務號碼(寄件人標識符)。
程式碼範例
請遵循下列步驟,將必要的代碼段新增至 messages-quickstart.py python 程式。
- 將簡訊傳送給 WhatsApp 使用者。
- 將影像媒體訊息傳送給 WhatsApp 使用者。
- 將文件媒體訊息傳送給 WhatsApp 使用者。
- 將音訊媒體訊息傳送給 WhatsApp 使用者。
- 將視訊媒體訊息傳送給 WhatsApp 使用者。
將文字訊息傳送給 WhatsApp 使用者
Messages SDK 可讓 Contoso 在 WhatsApp 使用者起始時傳送文字 WhatsApp 訊息。 若要傳送簡訊:
- WhatsApp 通道標識碼。
- E16 格式的收件者電話號碼。
- 要傳送的訊息本文/文字。
重要
若要將文字訊息傳送給 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 通道標識碼。
- E16 格式的收件者電話號碼。
- 影像的 MediaUri。
重要
若要將文字訊息傳送給 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 通道標識碼。
- E16 格式的收件者電話號碼。
- 檔的 MediaUri。
重要
若要將文件訊息傳送至 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 通道標識碼。
- E16 格式的收件者電話號碼。
- 音訊的 MediaUri。
重要
若要將音訊訊息傳送至 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 通道標識碼。
- E16 格式的收件者電話號碼。
- 影片的 MediaUri。
重要
若要將影片訊息傳送至 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 訊息 SDK 的其他範例程式碼。
下一步
本文說明 WhatsApp SDK 的進階傳訊。 如需詳細資訊,請參閱下列文章: