你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

使用高级消息传递发送文本和媒体 WhatsApp 消息

Azure 通信服务让你能够发送和接收 WhatsApp 消息。 本文介绍如何将应用与 Azure 通信高级消息 SDK 集成,以开始发送和接收 WhatsApp 消息。 完成本文需要从你的 Azure 帐户中扣取最多几美分的费用。

先决条件

设置环境

创建 .NET 项目

若要创建项目,请按照使用 Visual Studio 创建 .NET 控制台应用程序的教程进行操作。

若要编译代码,请按 Ctrl+F7

安装包

将 Azure.Communication.Messages NuGet 包安装到你的 C# 项目。

  1. 打开 NuGet 包管理器: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;

对象模型

以下类和接口处理适用于 .NET 的 Azure 通信服务高级消息传送 SDK 的某些主要功能。

类名 说明
NotificationMessagesClient 连接到你的 Azure 通信服务资源。 它会发送消息。
MessageTemplate 定义你为消息使用哪个模板以及模板属性的内容。
TemplateNotificationContent 定义要发送的模板消息的“谁”和“什么”。
TextNotificationContent 定义要发送的文本消息的“谁”和“什么”。
ImageNotificationContent 定义要发送的图像媒体消息的“谁”和“什么”。
DocumentNotificationContent 定义要发送的文档媒体消息的“谁”和“什么”。
VideoNotificationContent 定义要发送的视频媒体消息的“谁”和“什么”。
AudioNotificationContent 定义要发送的音频媒体消息的“谁”和“什么”。

注意

有关详细信息,请参阅 Azure SDK for .NET 参考文章 Azure.Communication.Messages 命名空间

通用配置

按照以下步骤将所需的代码片段添加到 messages-quickstart.py python 程序。

对客户端进行身份验证

消息 SDK 使用 NotificationMessagesClient 发送消息。 NotificationMessagesClient 方法使用从 Microsoft Azure 门户中的 Azure 通信服务资源获取的连接字符串进行身份验证。 有关连接字符串的详细信息,请参阅访问连接字符串和服务终结点

为简单起见,本快速入门使用连接字符串进行身份验证。 在生产环境中,我们建议使用服务主体

从 Azure 门户中的 Azure 通信服务资源获取连接字符串。 在左侧,导航到“Keys”选项卡。复制主键的 Connection string 字段。 连接字符串采用 endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key} 格式。

显示 Microsoft Azure 门户中的 Azure 通信服务资源的屏幕截图,其中显示了“主键”部分中的“连接字符串”字段。

将环境变量 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);

设置频道注册 ID

你已在频道注册期间创建了频道注册 ID GUID。 在门户中 Azure 通信服务资源的“频道”选项卡中可以找到它

显示 Microsoft Azure 门户中的 Azure 通信服务资源的屏幕截图,其中显示了“频道”选项卡。将注意力放在“频道 ID”字段的复制操作上。

将它分配给名为 channelRegistrationId 的变量。

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

设置收件人列表

需要提供与 WhatsApp 帐户关联的有效电话号码。 此 WhatsApp 帐户会接收本快速入门中发送的模版、文本和媒体消息。

对于此示例,可以使用个人电话号码。

收件人电话号码不能是与 WhatsApp 频道注册关联的业务电话号码(发件人 ID)。 发件人 ID 显示为发送给收件人的文本和媒体消息的发件人。

电话号码必须包括国家/地区代码。 有关电话号码格式的详细信息,请查看 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 平台查看定义。

若要从个人 WhatsApp 帐户发起交互式对话,请向企业号码(发送方 ID)发送消息。

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 用户发送图像媒体消息

消息 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 用户发送文档媒体消息

消息 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 用户发送视频媒体消息

消息 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 用户发送音频媒体消息

消息 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 目录包含项目源代码,src/test/java 目录包含测试源,pom.xml 文件是项目的项目对象模型 (POM)。

安装包

在文本编辑器中打开 pom.xml 文件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 文件的 main 函数中。

开始在企业和 WhatsApp 用户之间发送消息

可通过下面两种方式之一发起 WhatsApp Business 帐户与 WhatsApp 用户之间的对话:

  • 企业向 WhatsApp 用户发送模板消息。
  • WhatsApp 用户向企业号码发送任何消息。

无论对话是如何启动的,在用户向企业发送消息之前,企业只能发送模板消息。只有在用户向企业发送消息后,企业才能在活动对话期间向用户发送文本或媒体消息。 24 小时对话窗口到期后,必须重新发起对话。 若要了解有关对话的详细信息,请访问 WhatsApp Business 平台查看定义。

对客户端进行身份验证

可使用几个不同的选项对消息客户端进行身份验证:

若要对客户端进行身份验证,请使用连接字符串实例化 NotificationMessagesClientMessageTemplateClient。 还可以使用任何实现 com.azure.core.http.HttpClient 接口的自定义 HTTP 客户端来初始化此客户端。

为简单起见,本快速入门使用连接字符串进行身份验证。 在生产环境中,我们建议使用服务主体

从 Azure 门户中的 Azure 通信服务资源获取连接字符串。 在左侧,导航到“Keys”选项卡。复制 Primary keyConnection string 字段。 连接字符串采用 endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key} 格式。

显示 Microsoft Azure 门户中的 Azure 通信服务资源的屏幕截图,其中显示了“主键”部分中的“连接字符串”字段。

将环境变量 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();

设置频道注册 ID

频道注册 ID GUID 是在频道注册期间创建的。 可在门户中,访问 Azure 通信服务资源的“频道”选项卡来查找它。

显示 Microsoft Azure 门户中的 Azure 通信服务资源的屏幕截图,其中显示了“频道”选项卡。将注意力放在“频道 ID”字段的复制操作上。

将它分配给名为 channelRegistrationId 的变量。

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

设置收件人列表

你需要提供一个与 WhatsApp 帐户关联的真实电话号码。 此 WhatsApp 帐户接收本快速入门中发送的文本和媒体消息。 在本快速入门中,此电话号码可能是你的个人电话号码。

收件人电话号码不能是与 WhatsApp 频道注册关联的业务电话号码(发件人 ID)。 发件人 ID 显示为发送给收件人的文本和媒体消息的发件人。

电话号码应包括国家/地区代码。 有关电话号码格式的详细信息,请查看 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 用户启动的会话。 若要发送文本消息,需要提供以下详细信息:

在此示例中,我们使用文本 "Thanks for your feedback.\n From Notification Messaging SDK." 回复 WhatsApp 用户

重要

若要向 WhatsApp 用户发送文本消息,WhatsApp 用户必须先向 WhatsApp 企业帐户发送消息。 有关详细信息,请参阅开始在企业和 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 用户发送图像媒体消息

Contoso 可以使用消息 SDK 向 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 用户发送视频媒体消息

Contoso 可以使用消息 SDK 向 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 用户发送音频媒体消息

Contoso 可以使用消息 SDK 向 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 用户发送文档媒体消息

Contoso 可以使用消息 SDK 向 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 上查找此快速入门的最终代码。

先决条件

设置

创建新的 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 命令安装适用于 JavaScript 的 Azure 通信服务高级消息传送 SDK。

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

--save 选项将该库作为 package.json 文件中的依赖项列出。

代码示例

按照以下步骤将所需的代码片段添加到 send-messages.js 文件的 main 函数中。

开始在企业和 WhatsApp 用户之间发送消息

可通过下面两种方式之一发起 WhatsApp Business 帐户与 WhatsApp 用户之间的对话:

  • 企业向 WhatsApp 用户发送模板消息。
  • WhatsApp 用户向企业号码发送任何消息。

无论对话是如何启动的,在用户向企业发送消息之前,企业只能发送模板消息。只有在用户向企业发送消息后,企业才能在活动对话期间向用户发送文本或媒体消息。 24 小时对话窗口到期后,必须重新发起对话。 若要了解有关对话的详细信息,请访问 WhatsApp Business 平台查看定义。

对客户端进行身份验证

以下代码使用 dotenv 包从名为 COMMUNICATION_SERVICES_CONNECTION_STRING 的环境变量中检索资源的连接字符串。

为简单起见,本快速入门使用连接字符串进行身份验证。 在生产环境中,我们建议使用服务主体

从 Azure 门户中的 Azure 通信服务资源获取连接字符串。 在左侧,导航到“Keys”选项卡。复制 Primary keyConnection string 字段。 连接字符串采用 endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key} 格式。

显示 Microsoft Azure 门户中的 Azure 通信服务资源的屏幕截图,其中显示了“主键”部分中的“连接字符串”字段。

将环境变量 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);

设置频道注册 ID

频道注册 ID GUID 是在频道注册期间创建的。 可在门户中,访问 Azure 通信服务资源的“频道”选项卡来查找它。

显示 Microsoft Azure 门户中的 Azure 通信服务资源的屏幕截图,其中显示了“频道”选项卡。将注意力放在“频道 ID”字段的复制操作上。

将它分配给名为 channelRegistrationId 的变量。

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

设置收件人列表

你需要提供一个与 WhatsApp 帐户关联的真实电话号码。 此 WhatsApp 帐户会接收本快速入门中发送的模版、文本和媒体消息。 在本快速入门中,此电话号码可能是你的个人电话号码。

收件人电话号码不能是与 WhatsApp 频道注册关联的业务电话号码(发件人 ID)。 发件人 ID 显示为发送给收件人的文本和媒体消息的发件人。

电话号码应包括国家/地区代码。 有关电话号码格式的详细信息,请查看 WhatsApp 文档中的电话号码格式

注意

收件人列表中当前仅支持一个电话号码。

创建如下所示的收件人列表:

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

示例:

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

重要

若要向 WhatsApp 用户发送消息,WhatsApp 用户必须首先向 WhatsApp 企业帐户发送消息。 有关详细信息,请参阅开始在企业和 WhatsApp 用户之间发送消息

向 WhatsApp 用户发送文本消息

Messages SDK 使 Contoso 能够在 WhatsApp 用户发起对话时发送 WhatsApp 文本消息。 发送文本消息:

在此示例中,我们使用文本 "Thanks for your feedback.\n From Notification Messaging SDK." 回复 WhatsApp 用户

编写然后发送文本消息:

// 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 用户发送图像媒体消息

Contoso 可以使用消息 SDK 向 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 用户发送视频媒体消息

Contoso 可以使用消息 SDK 向 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 用户发送音频媒体消息

Contoso 可以使用消息 SDK 向 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 用户发送文档媒体消息

Contoso 可以使用消息 SDK 向 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 上查找此快速入门的最终代码。

先决条件

设置

创建新的 Python 应用程序

在终端或控制台窗口中,为应用程序创建一个新文件夹并打开它。

mkdir messages-quickstart && cd messages-quickstart

安装包

使用适用于 Python 1.1.0 或更高版本的 Azure 通信消息客户端库。

在控制台提示中运行以下命令:

pip install azure-communication-messages

对于“InteractiveMessages、Reactions 和 Stickers”,请使用以下 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 定义要发送的音频媒体消息的“谁”和“什么”。

注意

有关详细信息,请参阅 Azure SDK for Python 参考文章消息包

通用配置

按照以下步骤将所需的代码片段添加到 messages-quickstart.py Python 程序。

对客户端进行身份验证

发送的消息是使用 NotificationMessagesClient 完成的。 NotificationMessagesClient 使用从 Microsoft Azure 门户中的 Azure 通信服务资源获取的连接字符串进行身份验证。 有关连接字符串的详细信息,请参阅访问连接字符串和服务终结点

从 Microsoft Azure 门户获取 Azure 通信资源连接字符串,如屏幕截图中所示。 在左侧,导航到“Keys”选项卡。复制主键的 Connection string 字段。 连接字符串采用 endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key} 格式。

显示 Microsoft Azure 门户中的 Azure 通信服务资源的屏幕截图,其中显示了“键”部分中的“主键”字段。

将环境变量 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)

设置频道注册 ID

你已在频道注册期间创建了频道注册 ID GUID。 在门户中 Azure 通信服务资源的“频道”选项卡中可以找到它

显示 Microsoft Azure 门户中的 Azure 通信服务资源的屏幕截图,其中显示了“频道”选项卡。将注意力放在“频道 ID”字段的复制操作上。

将它分配给名为 channelRegistrationId 的变量。

    channelRegistrationId = os.getenv("WHATSAPP_CHANNEL_ID_GUID")

设置收件人列表

需要提供与 WhatsApp 帐户关联的有效电话号码。 此 WhatsApp 帐户会接收本快速入门中发送的模版、文本和媒体消息。

对于此示例,可以使用个人电话号码。

收件人电话号码不能是与 WhatsApp 频道注册关联的业务电话号码(发件人 ID)。 发件人 ID 显示为发送给收件人的文本和媒体消息的发件人。

电话号码必须包括国家/地区代码。 有关电话号码格式的详细信息,请查看 WhatsApp 文档中的电话号码格式

注意

收件人列表中当前仅支持一个电话号码。

设置如下所示的收件人列表:

    phone_number = os.getenv("RECIPIENT_WHATSAPP_PHONE_NUMBER")

用例:

    # Example only
    to=[self.phone_number],

开始在企业和 WhatsApp 用户之间发送消息

可通过下面两种方式之一发起 WhatsApp Business 帐户与 WhatsApp 用户之间的对话:

  • 企业向 WhatsApp 用户发送模板消息。
  • WhatsApp 用户向企业号码发送任何消息。

企业无法发起交互式对话。 企业只能在收到用户的消息后发送交互式消息。 企业只能在活动对话过程中向用户发送交互式消息。 一旦 24 小时对话窗口过期,只有用户才能重新开始交互式对话。 有关对话的详细信息,请访问 WhatsApp Business 平台查看定义。

若要从个人 WhatsApp 帐户发起交互式对话,请向企业号码(发送方 ID)发送消息。

Web 上显示的 WhatsApp 对话,其中显示了发送到 WhatsApp Business 账号的用户消息。

代码示例

按照以下步骤将所需的代码片段添加到 messages-quickstart.py python 程序。

向 WhatsApp 用户发送文本消息

Messages SDK 使 Contoso 能够在 WhatsApp 用户发起对话时发送 WhatsApp 文本消息。 发送文本消息:

重要

若要向 WhatsApp 用户发送文本消息,WhatsApp 用户必须先向 WhatsApp 企业帐户发送消息。 有关详细信息,请参阅开始在企业和 WhatsApp 用户之间发送消息

在此示例中,我们使用文本 "Thanks for your feedback.\n From Notification Messaging SDK." 回复 WhatsApp 用户

    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 用户发送图像媒体消息

消息 SDK 使 Contoso 能够将 WhatsApp 图像消息发送给 WhatsApp 用户。 发送嵌入了图像的消息:

重要

若要向 WhatsApp 用户发送文本消息,WhatsApp 用户必须先向 WhatsApp 企业帐户发送消息。 有关详细信息,请参阅开始在企业和 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 用户发送音频媒体消息

消息 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 消息 SDK 的其他示例代码。

后续步骤

本文介绍了 WhatsApp SDK 的高级消息传递。 有关详细信息,请参阅以下文章: