Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Azure Communication Services enables you to send and receive WhatsApp messages. In this quickstart, get started integrating your app with Azure Communication Advanced Messages SDK and start sending/receiving WhatsApp interactive messages. Completing this quickstart incurs a small cost of a few USD cents or less in your Azure account.
Prerequisites
- WhatsApp Business Account registered with your Azure Communication Services resource.
- Active WhatsApp phone number to receive messages.
- .NET development environment, such as Visual Studio, Visual Studio Code, or .NET CLI.
Set up the environment
Create the .NET project
To create your project, follow the tutorial at Create a .NET console application using Visual Studio.
To compile your code, press Ctrl+F7.
Install the package
Install the Azure.Communication.Messages NuGet package to your C# project.
- Open the NuGet Package Manager at
Project>Manage NuGet Packages.... - Search for the package
Azure.Communication.Messages. - Install the latest release.
Set up the app framework
Open the Program.cs file in a text editor.
Replace the contents of your Program.cs with the following code:
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
}
}
}
To use the Advanced Messaging features, add a using directive to include the Azure.Communication.Messages namespace.
using Azure.Communication.Messages;
Object model
The following classes and interfaces handle some of the major features of the Azure Communication Services Messages SDK for .NET.
| Class Name | Description |
|---|---|
NotificationMessagesClient |
Connects to your Azure Communication Services resource. It sends the messages. |
InteractiveNotificationContent |
Defines the interactive message business can send to user. |
InteractiveMessage |
Defines interactive message content. |
WhatsAppListActionBindings |
Defines WhatsApp List interactive message properties binding. |
WhatsAppButtonActionBindings |
Defines WhatsApp Button interactive message properties binding. |
WhatsAppUrlActionBindings |
Defines WhatsApp Url interactive message properties binding. |
TextMessageContent |
Defines the text content for Interactive message body, footer, header. |
VideoMessageContent |
Defines the video content for Interactive message header. |
DocumentMessageContent |
Defines the document content for Interactive message header. |
ImageMessageContent |
Defines the image content for Interactive message header. |
ActionGroupContent |
Defines the ActionGroup or ListOptions content for Interactive message. |
ButtonSetContent |
Defines the Reply Buttons content for Interactive message. |
LinkContent |
Defines the Url or Click-To-Action content for Interactive message. |
Common configuration
Follow these steps to add required code snippets to your .NET program.
Authenticate the client
The Messages SDK uses the NotificationMessagesClient to send messages. The NotificationMessagesClient method authenticates using your connection string acquired from Azure Communication Services resource in the Azure portal. For more information about connection strings, see access-your-connection-strings-and-service-endpoints.
For simplicity, this article uses a connection string to authenticate. In production environments, we recommend using service principals.
Get the connection string from your Azure Communication Services resource in the Azure portal. On the left, navigate to the Keys tab. Copy the Connection string field for the primary key. The connection string is in the format endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key}.
Set the environment variable COMMUNICATION_SERVICES_CONNECTION_STRING to the value of your connection string.
Open a console window and enter the following command:
setx COMMUNICATION_SERVICES_CONNECTION_STRING "<your connection string>"
After you add the environment variable, you might need to restart any running programs that will need to read the environment variable, including the console window. For example, if you're using Visual Studio as your editor, restart Visual Studio before running the example.
For more information on how to set an environment variable for your system, follow the steps at Store your connection string in an environment variable.
To instantiate a NotificationMessagesClient, add the following code to the Main method:
// Retrieve connection string from environment variable
string connectionString =
Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING");
// Instantiate the client
var notificationMessagesClient = new NotificationMessagesClient(connectionString);
Set channel registration ID
You created the Channel Registration ID GUID during channel registration. Find it in the portal on the Channels tab of your Azure Communication Services resource.
Assign it to a variable called channelRegistrationId.
var channelRegistrationId = new Guid("<your channel registration ID GUID>");
Set recipient list
You need to supply an active phone number associated with a WhatsApp account, or a business-scoped user ID (BSUID). This WhatsApp account receives the template, text, and media messages sent in this quickstart.
For this example, you can use your personal phone number.
The recipient phone number can't be the business phone number (Sender ID) associated with the WhatsApp channel registration. The Sender ID appears as the sender of the text and media messages sent to the recipient.
The phone number must include the country code. For more information about phone number formatting, see WhatsApp documentation for Phone Number Formats.
Note
Only one phone number or BSUID is currently supported in the recipient list.
Create the recipient list like this:
var recipientList = new List<string> { "<to WhatsApp phone number or BSUID>" };
Example using a phone number:
// Example only
var recipientList = new List<string> { "+14255550199" };
Example using a BSUID:
// Example only
var recipientList = new List<string> { "US.13491208655302741918" };
Note
Sending messages to BSUIDs will be available starting in June 2026. Until then, use phone numbers as recipients.
For more information about BSUIDs, see WhatsApp usernames and BSUIDs.
Start sending messages between a business and a WhatsApp user
Conversations between a WhatsApp Business Account and a WhatsApp user can be initiated in one of two ways:
- The business sends a template message to the WhatsApp user.
- The WhatsApp user sends any message to the business number.
A business can't initiate an interactive conversation. A business can only send an interactive message after receiving a message from the user. The business can only send interactive messages to the user during the active conversation. Once the 24 hour conversation window expires, only the user can restart the interactive conversation. For more information about conversations, see the definition at WhatsApp Business Platform.
To initiate an interactive conversation from your personal WhatsApp account, send a message to your business number (Sender ID).
Code examples
The Messages SDK supports the following WhatsApp Interactive messages:
- Send an Interactive List options message to a WhatsApp user.
- Send an Interactive Reply Button message to a WhatsApp user.
- Send an Interactive Click-to-action URL-based message to a WhatsApp user.
Send an Interactive List options message to a WhatsApp user
The Messages SDK enables Contoso to send interactive WhatsApp messages when initiated by WhatsApp users. To send list messages:
List Message can be created using the given properties:
Action type Description ActionGroupContentThis class defines the title of the group content and array of the group. ActionGroupThis class defines the title of the group and array of the group items. ActionGroupItemThis class defines ID, Title, and description of the group Item. WhatsAppListActionBindingsThis class defines the ActionGroupContentbinding with the interactive message.
Important
To send an interactive message to a WhatsApp user, the WhatsApp user must first send a message to the WhatsApp Business Account. For more information, see Start sending messages between business and WhatsApp user.
In this example, the business sends an interactive shipping options message to the user:
using Azure.Communication.Messages;
using Azure.Communication.Messages.Models;
public async Task SendWhatsAppListMessage()
{
var actionItemsList1 = new List<ActionGroupItem>
{
new ActionGroupItem("priority_express", "Priority Mail Express", "Next Day to 2 Days"),
new ActionGroupItem("priority_mail", "Priority Mail", "1–3 Days")
};
var actionItemsList2 = new List<ActionGroupItem>
{
new ActionGroupItem("usps_ground_advantage", "USPS Ground Advantage", "2-5 Days"),
new ActionGroupItem("media_mail", "Media Mail", "2-8 Days")
};
var groups = new List<ActionGroup>
{
new ActionGroup("I want it ASAP!", actionItemsList1),
new ActionGroup("I can wait a bit", actionItemsList2)
};
var actionGroupContent = new ActionGroupContent("Shipping Options", groups);
var interactionMessage = new InteractiveMessage(
new TextMessageContent("Test Body"),
new WhatsAppListActionBindings(actionGroupContent)
);
interactionMessage.Header = new TextMessageContent("Test Header");
interactionMessage.Footer = new TextMessageContent("Test Footer");
var interactiveMessageContent = new InteractiveNotificationContent(
channelRegistrationId,
recipientList,
interactionMessage
);
SendMessageResult response = await notificationMessagesClient.SendAsync(interactiveMessageContent);
Console.WriteLine($"Message with ID {response.Receipts[0].MessageId} was successfully sent.");
}
Send an interactive reply button message to a WhatsApp user
To send reply button messages:
Create reply button messages using the following properties:
| Action type | Description |
|---|---|
ButtonSetContent |
This class defines button set content for reply button messages. |
ButtonContent |
This class defines ID and title of the reply buttons. |
WhatsAppButtonActionBindings |
This class defines the ButtonSetContent binding with the interactive message. |
public async Task SendWhatsAppReplyButtonMessage()
{
var replyButtonActionList = new List<ButtonContent>
{
new ButtonContent("cancel", "Cancel"),
new ButtonContent("agree", "Agree")
};
var buttonSet = new ButtonSetContent(replyButtonActionList);
var interactionMessage = new InteractiveMessage(
new TextMessageContent("Test Body"),
new WhatsAppButtonActionBindings(buttonSet)
);
interactionMessage.Header = new TextMessageContent("Test Header");
interactionMessage.Footer = new TextMessageContent("Test Footer");
var interactiveMessageContent = new InteractiveNotificationContent(
channelRegistrationId,
recipientList,
interactionMessage
);
SendMessageResult response = await notificationMessagesClient.SendAsync(interactiveMessageContent);
Console.WriteLine($"Message with ID {response.Receipts[0].MessageId} was successfully sent.");
}
Send an interactive call-to-action URL-based message to a WhatsApp user
To send click-to-action or URL-based messages:
- WhatsApp Channel ID.
- Recipient Phone Number in E.164 format.
- Call-To-Action Messages can be created using the following properties:
| Action type | Description |
|---|---|
LinkContent |
This class defines URL or link content for a message. |
WhatsAppUrlActionBindings |
This class defines the LinkContent binding with the interactive message. |
public async Task SendWhatsAppClickToActionMessage()
{
var urlAction = new LinkContent("Test Url", new Uri("https://example.com/audio.mp3"));
var interactionMessage = new InteractiveMessage(
new TextMessageContent("Test Body"),
new WhatsAppUrlActionBindings(urlAction)
);
interactionMessage.Header = new TextMessageContent("Test Header");
interactionMessage.Footer = new TextMessageContent("Test Footer");
var interactiveMessageContent = new InteractiveNotificationContent(
channelRegistrationId,
recipientList,
interactionMessage
);
SendMessageResult response = await notificationMessagesClient.SendAsync(interactiveMessageContent);
Console.WriteLine($"WhatsApp CTA Message with ID {response.Receipts[0].MessageId} was successfully sent.");
}
Run the code
To run the code:
- Build your solution by pressing Ctrl+Shift+B.
- Run the program by pressing Ctrl+F5.
Full sample code
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure.Communication.Messages;
using Azure.Communication.Messages.Models;
namespace InteractiveMessagesQuickstart
{
public class Program
{
private static Guid channelRegistrationId = new Guid("<Your Channel ID>");
private static List<string> recipientList = new List<string> { "<Recipient's WhatsApp Phone Number>" };
private static NotificationMessagesClient notificationMessagesClient = new NotificationMessagesClient("<Your Connection String>");
public static async Task Main(string[] args)
{
Console.WriteLine("Azure Communication Services - Send WhatsApp Interactive Messages");
var program = new Program();
await program.SendWhatsAppListMessage();
await program.SendWhatsAppReplyButtonMessage();
await program.SendWhatsAppClickToActionMessage();
Console.WriteLine("All messages sent. Press any key to exit.");
Console.ReadKey();
}
public async Task SendWhatsAppListMessage()
{
var actionItemsList1 = new List<ActionGroupItem>
{
new ActionGroupItem("priority_express", "Priority Mail Express", "Next Day to 2 Days"),
new ActionGroupItem("priority_mail", "Priority Mail", "1–3 Days")
};
var actionItemsList2 = new List<ActionGroupItem>
{
new ActionGroupItem("usps_ground_advantage", "USPS Ground Advantage", "2-5 Days"),
new ActionGroupItem("media_mail", "Media Mail", "2-8 Days")
};
var groups = new List<ActionGroup>
{
new ActionGroup("I want it ASAP!", actionItemsList1),
new ActionGroup("I can wait a bit", actionItemsList2)
};
var actionGroupContent = new ActionGroupContent("Shipping Options", groups);
var interactionMessage = new InteractiveMessage(
new TextMessageContent("Test Body"),
new WhatsAppListActionBindings(actionGroupContent)
);
interactionMessage.Header = new TextMessageContent("Test Header");
interactionMessage.Footer = new TextMessageContent("Test Footer");
var interactiveMessageContent = new InteractiveNotificationContent(
channelRegistrationId,
recipientList,
interactionMessage
);
SendMessageResult response = await notificationMessagesClient.SendAsync(interactiveMessageContent);
Console.WriteLine($"Message with ID {response.Receipts[0].MessageId} was successfully sent.");
}
public async Task SendWhatsAppReplyButtonMessage()
{
var replyButtonActionList = new List<ButtonContent>
{
new ButtonContent("cancel", "Cancel"),
new ButtonContent("agree", "Agree")
};
var buttonSet = new ButtonSetContent(replyButtonActionList);
var interactionMessage = new InteractiveMessage(
new TextMessageContent("Test Body"),
new WhatsAppButtonActionBindings(buttonSet)
);
interactionMessage.Header = new TextMessageContent("Test Header");
interactionMessage.Footer = new TextMessageContent("Test Footer");
var interactiveMessageContent = new InteractiveNotificationContent(
channelRegistrationId,
recipientList,
interactionMessage
);
SendMessageResult response = await notificationMessagesClient.SendAsync(interactiveMessageContent);
Console.WriteLine($"Message with ID {response.Receipts[0].MessageId} was successfully sent.");
}
public async Task SendWhatsAppClickToActionMessage()
{
var urlAction = new LinkContent("Test Url", new Uri("https://example.com/audio.mp3"));
var interactionMessage = new InteractiveMessage(
new TextMessageContent("Test Body"),
new WhatsAppUrlActionBindings(urlAction)
);
interactionMessage.Header = new TextMessageContent("Test Header");
interactionMessage.Footer = new TextMessageContent("Test Footer");
var interactiveMessageContent = new InteractiveNotificationContent(
channelRegistrationId,
recipientList,
interactionMessage
);
SendMessageResult response = await notificationMessagesClient.SendAsync(interactiveMessageContent);
Console.WriteLine($"WhatsApp CTA Message with ID {response.Receipts[0].MessageId} was successfully sent.");
}
}
}
Prerequisites
- WhatsApp Business Account registered with your Azure Communication Services resource.
- Active WhatsApp phone number to receive messages.
- Java Development Kit (JDK) version 8 or later.
- Apache Maven.
Set up environment
To set up an environment for sending messages, complete the steps in the following sections.
Create a new Java application
Open a terminal or command window and navigate to the directory where you want to create your Java application. Run the following command to generate the Java project from the maven-archetype-quickstart template.
mvn archetype:generate -DgroupId="com.communication.quickstart" -DartifactId="communication-quickstart" -DarchetypeArtifactId="maven-archetype-quickstart" -DarchetypeVersion="1.4" -DinteractiveMode="false"
The generate goal creates a directory with the same name as the artifactId value. Under this directory, the src/main/java directory contains the project source code, the src/test/java directory contains the test source, and the pom.xml file is the project's Project Object Model (POM).
Install the package
Open the pom.xml file in your text editor. Add the following dependency element to the group of dependencies.
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-communication-messages</artifactId>
</dependency>
Set up the app framework
Open /src/main/java/com/communication/quickstart/App.java in a text editor, add import directives, and remove the System.out.println("Hello world!"); statement:
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.
}
}
Object model
The following classes and interfaces handle some of the major features of the Azure Communication Services Messages SDK.
| Class Name | Description |
|---|---|
NotificationMessagesClient |
Connects to your Azure Communication Services resource. It sends the messages. |
InteractiveNotificationContent |
Defines the interactive message business can send to user. |
InteractiveMessage |
Defines interactive message content. |
WhatsAppListActionBindings |
Defines WhatsApp List interactive message properties binding. |
WhatsAppButtonActionBindings |
Defines WhatsApp Button interactive message properties binding. |
WhatsAppUrlActionBindings |
Defines WhatsApp Url interactive message properties binding. |
TextMessageContent |
Defines the text content for Interactive message body, footer, header. |
VideoMessageContent |
Defines the video content for Interactive message header. |
DocumentMessageContent |
Defines the document content for Interactive message header. |
ImageMessageContent |
Defines the image content for Interactive message header. |
ActionGroupContent |
Defines the ActionGroup or ListOptions content for Interactive message. |
ButtonSetContent |
Defines the Reply Buttons content for Interactive message. |
LinkContent |
Defines the Url or Click-To-Action content for Interactive message. |
Note
For more information, see the Azure SDK for Java reference at com.azure.communication.messages Package.
Common configuration
Follow these steps to add required code snippets to the main function of your App.java file.
- Start sending messages between a business and a WhatsApp user.
- Authenticate the client.
- Set channel registration ID.
- Set recipient list.
Start sending messages between a business and a WhatsApp user
Conversations between a WhatsApp Business Account and a WhatsApp user can be initiated in one of two ways:
- The business sends a template message to the WhatsApp user.
- The WhatsApp user sends any message to the business number.
Regardless of how the conversation was started, a business can only send template messages until the user sends a message to the business. Only after the user sends a message to the business, the business is allowed to send text or media messages to the user during the active conversation. Once the 24 hour conversation window expires, the conversation must be reinitiated. To learn more about conversations, see the definition at WhatsApp Business Platform.
Authenticate the client
There are a few different options available for authenticating a Message client:
To authenticate a client, you instantiate an NotificationMessagesClient or MessageTemplateClient with your connection string. You can also initialize the client with any custom HTTP client that implements the com.azure.core.http.HttpClient interface.
For simplicity, this article uses a connection string to authenticate. In production environments, we recommend using service principals.
Get the connection string from your Azure Communication Services resource in the Azure portal. On the left, navigate to the Keys tab. Copy the Connection string field for the Primary key. The connection string is in the format endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key}.
Set the environment variable COMMUNICATION_SERVICES_CONNECTION_STRING to the value of your connection string.
Open a console window and enter the following command:
setx COMMUNICATION_SERVICES_CONNECTION_STRING "<your connection string>"
For more information on how to set an environment variable for your system, follow the steps at Store your connection string in an environment variable.
To instantiate a NotificationMessagesClient, add the following code to the main method:
// 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();
Set channel registration ID
The Channel Registration ID GUID was created during channel registration. You can look it up in the portal on the Channels tab of your Azure Communication Services resource.
Assign it to a variable called channelRegistrationId.
String channelRegistrationId = "<your channel registration id GUID>";
Set recipient list
You need to supply a real phone number that has a WhatsApp account associated with it, or a business-scoped user ID (BSUID). This WhatsApp account receives the text and media messages sent in this article. For this article, this phone number can be your personal phone number.
The recipient phone number can't be the business phone number (Sender ID) associated with the WhatsApp channel registration. The Sender ID appears as the sender of the text and media messages sent to the recipient.
The phone number should include the country code. For more information on phone number formatting, see WhatsApp documentation for Phone Number Formats.
Note
Only one phone number or BSUID is currently supported in the recipient list.
Create the recipient list like this:
List<String> recipientList = new ArrayList<>();
recipientList.add("<to WhatsApp phone number or BSUID>");
Example using a phone number:
// Example only
List<String> recipientList = new ArrayList<>();
recipientList.add("+14255550199");
Example using a BSUID:
// Example only
List<String> recipientList = new ArrayList<>();
recipientList.add("US.13491208655302741918");
Note
Sending messages to BSUIDs will be available starting in June 2026. Until then, use phone numbers as recipients.
For more information about BSUIDs, see WhatsApp usernames and BSUIDs.
Code examples
Follow these steps to add required code snippets to the main function of your App.java file.
- Send an Interactive List options message to a WhatsApp user.
- Send an Interactive Reply Button message to a WhatsApp user.
- Send an Interactive Click-to-action Url based message to a WhatsApp user.
Send an interactive list options message to a WhatsApp user
The Messages SDK enables Contoso to send interactive WhatsApp messages, when initiated by a WhatsApp users. To send interactive messages:
- WhatsApp Channel ID.
- Recipient Phone Number in E16 format.
- Interactive message to be sent.
Important
To send an interactive message to a WhatsApp user, the WhatsApp user must first send a message to the WhatsApp Business Account. For more information, see Start sending messages between business and WhatsApp user.
In this example, the business sends an interactive shipping options message to the user.
// Create Express Shipping options group
List<ActionGroupItem> group1 = new ArrayList<>();
group1.add(new ActionGroupItem("priority_express", "Priority Mail Express", "Delivered on same day!"));
group1.add(new ActionGroupItem("priority_mail", "Priority Mail", "Delivered in 1-2 days"));
// Create Normal Shipping options group
List<ActionGroupItem> group2 = new ArrayList<>();
group2.add(new ActionGroupItem("usps_ground_advantage", "USPS Ground Advantage", "Delivered in 2-5 days"));
group2.add(new ActionGroupItem("normal_mail", "Normal Mail", "Delivered in 5-8 days"));
// Add Shipping options
List<ActionGroup> options = new ArrayList<>();
options.add(new ActionGroup("Express Delivery", group1));
options.add(new ActionGroup("Normal Delivery", group2));
ActionGroupContent actionGroupContent = new ActionGroupContent("Shipping Options", options);
// Build interactive message with body, header (optional), footer (optional)
InteractiveMessage interactiveMessage = new InteractiveMessage(
new TextMessageContent("Which shipping option do you want?"), new WhatsAppListActionBindings(actionGroupContent));
interactiveMessage.setFooter(new TextMessageContent("Logistic Ltd"));
interactiveMessage.setHeader(new TextMessageContent("Shipping Options"));
InteractiveNotificationContent interactiveMessageContent = new InteractiveNotificationContent("<CHANNEL_ID>", recipients, interactiveMessage);
// Send an interactive message
SendMessageResult textMessageResult = notificationClient.send(interactiveMessageContent);
// Process result
for (MessageReceipt messageReceipt : textMessageResult.getReceipts()) {
System.out.println("Message sent to:" + messageReceipt.getTo() + " and message id:" + messageReceipt.getMessageId());
}
Send an interactive reply button message to a WhatsApp user
The Messages SDK enables Contoso to send interactive WhatsApp messages, when initiated by a WhatsApp users. To send interactive messages:
- WhatsApp Channel ID.
- Recipient Phone Number in E16 format.
- Interactive message to be sent.
Important
To send an interactive message to a WhatsApp user, the WhatsApp user must first send a message to the WhatsApp Business Account. For more information, see Start sending messages between business and WhatsApp user.
In this example, the business sends an interactive reply button message to the user.
// Assemble interactive reply button
List<ButtonContent> buttonActions = new ArrayList<>();
buttonActions.add(new ButtonContent("no", "No"));
buttonActions.add(new ButtonContent("yes", "Yes"));
ButtonSetContent buttonSet = new ButtonSetContent(buttonActions);
InteractiveMessage interactiveMessage = new InteractiveMessage(new TextMessageContent("Do you want to proceed?"), new WhatsAppButtonActionBindings(buttonSet));
InteractiveNotificationContent interactiveMessageContent = new InteractiveNotificationContent("<CHANNEL_ID>", recipients, interactiveMessage);
// Send an interactive message
SendMessageResult textMessageResult = notificationClient.send(interactiveMessageContent);
// Process result
for (MessageReceipt messageReceipt : textMessageResult.getReceipts()) {
System.out.println("Message sent to:" + messageReceipt.getTo() + " and message id:" + messageReceipt.getMessageId());
}
Send an interactive call-to-action URL based message to a WhatsApp user
The Messages SDK enables Contoso to send interactive WhatsApp messages, when initiated by a WhatsApp users. To send interactive messages:
- WhatsApp Channel ID.
- Recipient Phone Number in E16 format.
- Interactive message to be sent.
Important
To send an interactive message to a WhatsApp user, the WhatsApp user must first send a message to the WhatsApp Business Account. For more information, see Start sending messages between business and WhatsApp user.
In this example, the business sends a click to a link message to the user.
LinkContent urlAction = new LinkContent("Find out more", "https://wallpapercave.com/wp/wp2163723.jpg");
InteractiveMessage interactiveMessage = new InteractiveMessage(
new TextMessageContent("The best Guardian of Galaxy"), new WhatsAppUrlActionBindings(urlAction));
interactiveMessage.setFooter(new TextMessageContent("Intergalactic New Ltd"));
InteractiveNotificationContent interactiveMessageContent = new InteractiveNotificationContent("<CHANNEL_ID>", recipients, interactiveMessage);
// Send an interactive message
SendMessageResult textMessageResult = notificationClient.send(interactiveMessageContent);
// Process result
for (MessageReceipt messageReceipt : textMessageResult.getReceipts()) {
System.out.println("Message sent to:" + messageReceipt.getTo() + " and message id:" + messageReceipt.getMessageId());
}
Run the code
Open to the directory that contains the
pom.xmlfile and compile the project using themvncommand.mvn compileRun the app by executing the following
mvncommand.mvn exec:java -D"exec.mainClass"="com.communication.quickstart.App" -D"exec.cleanupDaemonThreads"="false"
Full sample code
Find the finalized code for this sample on GitHub at Azure Messages client library for Java.
Prerequisites
- WhatsApp Business Account registered with your Azure Communication Services resource.
- Active WhatsApp phone number to receive messages.
- Node.js Active LTS and Maintenance LTS versions (8.11.1 and 10.14.1 are recommended)
- In a terminal or command window, run
node --versionto check that Node.js is installed
- In a terminal or command window, run
Setting up
Create a new Node.js application
Create a new directory for your app and open it in a terminal or command window.
Run the following command.
mkdir advance-messages-quickstart && cd advance-messages-quickstartRun the following command to create a
package.jsonfile with default settings.npm init -yUse a text editor to create a file called
send-messages.jsin the project root directory.Add the following code snippet to the file
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); });
Complete the following section to add your source code for this example to the send-messages.js file that you created.
Install the package
Use the npm install command to install the Azure Communication Services Advance Messaging SDK for JavaScript.
npm install @azure-rest/communication-messages --save
The --save option lists the library as a dependency in your package.json file.
Object model
The following classes and interfaces handle some of the major features of the Azure Communication Services Advance Messaging SDK for JavaScript.
| Class Name | Description |
|---|---|
NotificationMessagesClient |
Connects to your Azure Communication Services resource. It sends the messages. |
InteractiveNotificationContent |
Defines the interactive message business can send to user. |
InteractiveMessage |
Defines interactive message content. |
WhatsAppListActionBindings |
Defines WhatsApp List interactive message properties binding. |
WhatsAppButtonActionBindings |
Defines WhatsApp Button interactive message properties binding. |
WhatsAppUrlActionBindings |
Defines WhatsApp Url interactive message properties binding. |
TextMessageContent |
Defines the text content for Interactive message body, footer, header. |
VideoMessageContent |
Defines the video content for Interactive message header. |
DocumentMessageContent |
Defines the document content for Interactive message header. |
ImageMessageContent |
Defines the image content for Interactive message header. |
ActionGroupContent |
Defines the ActionGroup or ListOptions content for Interactive message. |
ButtonSetContent |
Defines the Reply Buttons content for Interactive message. |
LinkContent |
Defines the Url or Click-To-Action content for Interactive message. |
Note
For more information, see the Azure SDK for JavaScript reference @azure-rest/communication-messages package
Common configuration
Follow these steps to add required code snippets to your send-messages.js file.
- Start sending messages between a business and a WhatsApp user.
- Authenticate the client.
- Set channel registration ID.
- Set recipient list.
Start sending messages between a business and a WhatsApp user
Conversations between a WhatsApp Business Account and a WhatsApp user can be initiated in one of two ways:
- The business sends a template message to the WhatsApp user.
- The WhatsApp user sends any message to the business number.
Regardless of how the conversation was started, a business can only send template messages until the user sends a message to the business. Only after the user sends a message to the business, the business is allowed to send text or media messages to the user during the active conversation. Once the 24 hour conversation window expires, the conversation must be reinitiated. To learn more about conversations, see the definition at WhatsApp Business Platform.
Authenticate the client
The following code retrieves the connection string for the resource from an environment variable named COMMUNICATION_SERVICES_CONNECTION_STRING using the dotenv package.
For simplicity, this article uses a connection string to authenticate. In production environments, we recommend using service principals.
Get the connection string from your Azure Communication Services resource in the Azure portal. On the left, navigate to the Keys tab. Copy the Connection string field for the Primary key. The connection string is in the format endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key}.
Set the environment variable COMMUNICATION_SERVICES_CONNECTION_STRING to the value of your connection string.
Open a console window and enter the following command:
setx COMMUNICATION_SERVICES_CONNECTION_STRING "<your connection string>"
For more information on how to set an environment variable for your system, follow the steps at Store your connection string in an environment variable.
To instantiate a NotificationClient, add the following code to the Main method:
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);
Set channel registration ID
The Channel Registration ID GUID was created during channel registration. You can look it up in the portal on the Channels tab of your Azure Communication Services resource.
Assign it to a variable called channelRegistrationId.
const channelRegistrationId = "<your channel registration id GUID>";
Set recipient list
You need to supply a real phone number that has a WhatsApp account associated with it, or a business-scoped user ID (BSUID). This WhatsApp account receives the template, text, and media messages sent in this article. For this article, this phone number can be your personal phone number.
The recipient phone number can't be the business phone number (Sender ID) associated with the WhatsApp channel registration. The Sender ID appears as the sender of the text and media messages sent to the recipient.
The phone number should include the country code. For more information on phone number formatting, see WhatsApp documentation for Phone Number Formats.
Note
Only one phone number or BSUID is currently supported in the recipient list.
Create the recipient list like this:
const recipientList = ["<to WhatsApp phone number or BSUID>"];
Example using a phone number:
// Example only
const recipientList = ["+14255550199"];
Example using a BSUID:
// Example only
const recipientList = ["US.13491208655302741918"];
Note
Sending messages to BSUIDs will be available starting in June 2026. Until then, use phone numbers as recipients.
For more information about BSUIDs, see WhatsApp usernames and BSUIDs.
Code examples
Follow these steps to add required code snippets to your send-messages.js file.
- Send an Interactive List options message to a WhatsApp user.
- Send an Interactive Reply Button message to a WhatsApp user.
- Send an Interactive Click-to-action Url based message to a WhatsApp user
Send an Interactive List options message to a WhatsApp user
The Messages SDK enables Contoso to send interactive WhatsApp messages, when initiated by a WhatsApp users. To send interactive messages:
- WhatsApp Channel ID.
- Recipient Phone Number in E16 format.
- Interactive message to be sent.
Important
To send an interactive message to a WhatsApp user, the WhatsApp user must first send a message to the WhatsApp Business Account. For more information, see Start sending messages between business and WhatsApp user.
In this example, the business sends an interactive shipping options message to the user.
/**
* @summary Send an interactive message
*/
const { AzureKeyCredential } = require("@azure/core-auth");
const NotificationClient = require("@azure-rest/communication-messages").default,
{ isUnexpected } = require("@azure-rest/communication-messages");
// Load the .env file if it exists
require("dotenv").config();
async function main() {
const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || "");
const endpoint = process.env.ACS_URL || "";
const client = NotificationClient(endpoint, credential);
const interactiveMessage = {
body: {
kind: "text",
text: "Which shipping option do you want?",
},
action: {
kind: "whatsAppListAction",
content: {
kind: "group",
title: "Shipping Options",
groups: [
{
title: "Express Delivery",
items: [
{
id: "priority_mail_express",
title: "Priority Mail Express",
description: "Delivered on same day!",
},
{
id: "priority_mail",
title: "Priority Mail",
description: "Delivered in 1-2 days",
},
],
},
{
title: "Normal Delivery",
items: [
{
id: "usps_ground_advantage",
title: "USPS Ground Advantage",
description: "Delivered in 2-5 days",
},
{
id: "usps_mail",
title: "Normal Mail",
description: "Delivered in 5-8 days",
},
],
},
],
},
},
};
console.log("Sending message...");
const result = await client.path("/messages/notifications:send").post({
contentType: "application/json",
body: {
channelRegistrationId: process.env.CHANNEL_ID || "",
to: [process.env.RECIPIENT_PHONE_NUMBER || ""],
kind: "interactive",
interactiveMessage: interactiveMessage,
},
});
console.log("Response: " + JSON.stringify(result, null, 2));
if (isUnexpected(result)) {
throw new Error("Failed to send message");
}
const response = result;
response.body.receipts.forEach((receipt) => {
console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId);
});
}
main().catch((error) => {
console.error("Encountered an error while sending message: ", error);
throw error;
});
Send an Interactive Reply Button message to a WhatsApp user
The Messages SDK enables Contoso to send interactive WhatsApp messages, when initiated by a WhatsApp users. To send interactive messages:
- WhatsApp Channel ID.
- Recipient Phone Number in E16 format.
- Interactive message to be sent.
Important
To send an interactive message to a WhatsApp user, the WhatsApp user must first send a message to the WhatsApp Business Account. For more information, see Start sending messages between business and WhatsApp user.
In this example, the business sends a reply button message to the user.
/**
* @summary Send an interactive message
*/
const { AzureKeyCredential } = require("@azure/core-auth");
const NotificationClient = require("@azure-rest/communication-messages").default,
{ isUnexpected } = require("@azure-rest/communication-messages");
// Load the .env file if it exists
require("dotenv").config();
async function main() {
const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || "");
const endpoint = process.env.ACS_URL || "";
const client = NotificationClient(endpoint, credential);
const interactiveMessage = {
body: {
kind: "text",
text: "Do you want to proceed?",
},
action: {
kind: "whatsAppButtonAction",
content: {
kind: "buttonSet",
buttons: [
{
id: "yes",
title: "Yes",
},
{
id: "no",
title: "No",
},
],
},
},
};
console.log("Sending message...");
const result = await client.path("/messages/notifications:send").post({
contentType: "application/json",
body: {
channelRegistrationId: process.env.CHANNEL_ID || "",
to: [process.env.RECIPIENT_PHONE_NUMBER || ""],
kind: "interactive",
interactiveMessage: interactiveMessage,
},
});
console.log("Response: " + JSON.stringify(result, null, 2));
if (isUnexpected(result)) {
throw new Error("Failed to send message");
}
const response = result;
response.body.receipts.forEach((receipt) => {
console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId);
});
}
main().catch((error) => {
console.error("Encountered an error while sending message: ", error);
throw error;
});
Send an Interactive Call-To-Action Url based message to a WhatsApp user
The Messages SDK enables Contoso to send interactive WhatsApp messages, when initiated by a WhatsApp users. To send interactive messages:
- WhatsApp Channel ID.
- Recipient Phone Number in E16 format.
- Interactive message to be sent.
Important
To send an interactive message to a WhatsApp user, the WhatsApp user must first send a message to the WhatsApp Business Account. For more information, see Start sending messages between business and WhatsApp user.
In this example, the business sends a click to a link message to the user.
/**
* @summary Send an interactive message
*/
const { AzureKeyCredential } = require("@azure/core-auth");
const NotificationClient = require("@azure-rest/communication-messages").default,
{ isUnexpected } = require("@azure-rest/communication-messages");
// Load the .env file if it exists
require("dotenv").config();
async function main() {
const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || "");
const endpoint = process.env.ACS_URL || "";
const client = NotificationClient(endpoint, credential);
const interactiveMessage = {
body: {
kind: "text",
text: "The best Guardian of Galaxy",
},
action: {
kind: "whatsAppUrlAction",
content: {
kind: "url",
title: "Rocket is the best!",
url: "https://wallpapercave.com/wp/wp2163723.jpg",
},
},
footer: {
kind: "text",
text: "Intergalactic News Ltd",
},
};
console.log("Sending message...");
const result = await client.path("/messages/notifications:send").post({
contentType: "application/json",
body: {
channelRegistrationId: process.env.CHANNEL_ID || "",
to: [process.env.RECIPIENT_PHONE_NUMBER || ""],
kind: "interactive",
interactiveMessage: interactiveMessage,
},
});
console.log("Response: " + JSON.stringify(result, null, 2));
if (isUnexpected(result)) {
throw new Error("Failed to send message");
}
const response = result;
response.body.receipts.forEach((receipt) => {
console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId);
});
}
main().catch((error) => {
console.error("Encountered an error while sending message: ", error);
throw error;
});
Run the code
Use the node command to run the code you added to the send-messages.js file.
node ./send-messages.js
Full sample code
Find the finalized code for this sample on GitHub at JavaScript Messages SDK.
Prerequisites
- WhatsApp Business Account registered with your Azure Communication Services resource.
- Active WhatsApp phone number to receive messages.
- Python 3.7+ for your operating system.
Set up the environment
Create a new Python application
In a terminal or console window, create a new folder for your application and open it.
mkdir messages-quickstart && cd messages-quickstart
Install the package
Use the Azure Communication Messages client library for Python 1.1.0 or above.
From a console prompt, run the following command:
pip install azure-communication-messages
For InteractiveMessages, Reactions and Stickers, please use below Beta version:
pip install azure-communication-messages==1.2.0b1
Set up the app framework
Create a new file called messages-quickstart.py and add the basic program structure.
type nul > messages-quickstart.py
Basic program structure
import os
class MessagesQuickstart(object):
print("Azure Communication Services - Advanced Messages SDK Quickstart")
if __name__ == '__main__':
messages = MessagesQuickstart()
Object model
The following classes and interfaces handle some of the major features of the Azure Communication Services Messages SDK for Python.
| Class Name | Description |
|---|---|
NotificationMessagesClient |
Connects to your Azure Communication Services resource. It sends the messages. |
InteractiveNotificationContent |
Defines the interactive message business can send to user. |
InteractiveMessage |
Defines interactive message content. |
WhatsAppListActionBindings |
Defines WhatsApp List interactive message properties binding. |
WhatsAppButtonActionBindings |
Defines WhatsApp Button interactive message properties binding. |
WhatsAppUrlActionBindings |
Defines WhatsApp Url interactive message properties binding. |
TextMessageContent |
Defines the text content for Interactive message body, footer, header. |
VideoMessageContent |
Defines the video content for Interactive message header. |
DocumentMessageContent |
Defines the document content for Interactive message header. |
ImageMessageContent |
Defines the image content for Interactive message header. |
ActionGroupContent |
Defines the ActionGroup or ListOptions content for Interactive message. |
ButtonSetContent |
Defines the Reply Buttons content for Interactive message. |
LinkContent |
Defines the Url or Click-To-Action content for Interactive message. |
Note
For more information, see the Azure SDK for Python reference messages Package.
Common configuration
Follow these steps to add required code snippets to the messages-quickstart.py python program.
Authenticate the client
Messages sending uses NotificationMessagesClient. NotificationMessagesClient authenticates using your connection string acquired from Azure Communication Services resource in the Azure portal.F
For more information on connection strings, see access-your-connection-strings-and-service-endpoints.
Get Azure Communication Resource connection string from Azure portal as given in screenshot. On the left, navigate to the Keys tab. Copy the Connection string field for the primary key. The connection string is in the format endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key}.
Set the environment variable COMMUNICATION_SERVICES_CONNECTION_STRING to the value of your connection string.
Open a console window and enter the following command:
setx COMMUNICATION_SERVICES_CONNECTION_STRING "<your connection string>"
After you add the environment variable, you might need to restart any running programs that will need to read the environment variable, including the console window. For example, if you're using Visual Studio as your editor, restart Visual Studio before running the example.
For more information on how to set an environment variable for your system, follow the steps at Store your connection string in an environment variable.
# 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)
Set channel registration ID
You created the Channel Registration ID GUID during channel registration. Find it in the portal on the Channels tab of your Azure Communication Services resource.
Assign it to a variable called channelRegistrationId.
channelRegistrationId = os.getenv("WHATSAPP_CHANNEL_ID_GUID")
Set recipient list
You need to supply an active phone number associated with a WhatsApp account, or a business-scoped user ID (BSUID). This WhatsApp account receives the template, text, and media messages sent in this article.
For this example, you can use your personal phone number.
The recipient phone number can't be the business phone number (Sender ID) associated with the WhatsApp channel registration. The Sender ID appears as the sender of the text and media messages sent to the recipient.
The phone number must include the country code. For more information about phone number formatting, see WhatsApp documentation for Phone Number Formats.
Note
Only one phone number or BSUID is currently supported in the recipient list.
Set the recipient list like this:
phone_number = os.getenv("RECIPIENT_WHATSAPP_PHONE_NUMBER")
Usage example with a phone number:
# Example only
to=[self.phone_number],
Usage example with a BSUID:
# Example only
to=["US.13491208655302741918"],
Note
Sending messages to BSUIDs will be available starting in June 2026. Until then, use phone numbers as recipients.
For more information about BSUIDs, see WhatsApp usernames and BSUIDs.
Start sending messages between a business and a WhatsApp user
Conversations between a WhatsApp Business Account and a WhatsApp user can be initiated in one of two ways:
- The business sends a template message to the WhatsApp user.
- The WhatsApp user sends any message to the business number.
A business can't initiate an interactive conversation. A business can only send an interactive message after receiving a message from the user. The business can only send interactive messages to the user during the active conversation. Once the 24 hour conversation window expires, only the user can restart the interactive conversation. For more information about conversations, see the definition at WhatsApp Business Platform.
To initiate an interactive conversation from your personal WhatsApp account, send a message to your business number (Sender ID).
Code examples
The Messages SDK supports the following WhatsApp Interactive messages:
- Send an Interactive List options message to a WhatsApp user.
- Send an Interactive Reply Button message to a WhatsApp user.
- Send an Interactive Click-to-action Url based message to a WhatsApp user.
Send an Interactive List options message to a WhatsApp user
The Messages SDK enables Contoso to send interactive WhatsApp messages, when initiated by a WhatsApp users. To send text messages:
List Message can be created using the given properties:
Action type Description ActionGroupContentThis class defines title of the group content and array of the group. ActionGroupThis class defines title of the group and array of the group Items. ActionGroupItemThis class defines ID, Title, and description of the group Item. WhatsAppListActionBindingsThis class defines the ActionGroupContentbinding with the interactive message.
Important
To send a text message to a WhatsApp user, the WhatsApp user must first send a message to the WhatsApp Business Account. For more information, see Start sending messages between business and WhatsApp user.
In this example, the business sends an interactive shipping options message to the user.
def send_whatsapplist_message(self):
from azure.communication.messages import NotificationMessagesClient
from azure.communication.messages.models import (
ActionGroupContent,
ActionGroup,
ActionGroupItem,
InteractiveMessage,
TextMessageContent,
WhatsAppListActionBindings,
InteractiveNotificationContent,
)
messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
action_items_list1 = [
ActionGroupItem(id="priority_express", title="Priority Mail Express", description="Next Day to 2 Days"),
ActionGroupItem(id="priority_mail", title="Priority Mail", description="1–3 Days"),
]
action_items_list2 = [
ActionGroupItem(id="usps_ground_advantage", title="USPS Ground Advantage", description="2-5 Days"),
ActionGroupItem(id="media_mail", title="Media Mail", description="2-8 Days"),
]
groups = [
ActionGroup(title="I want it ASAP!", items_property=action_items_list1),
ActionGroup(title="I can wait a bit", items_property=action_items_list2),
]
action_group_content = ActionGroupContent(title="Shipping Options", groups=groups)
interactionMessage = InteractiveMessage(
body=TextMessageContent(text="Test Body"),
footer=TextMessageContent(text="Test Footer"),
header=TextMessageContent(text="Test Header"),
action=WhatsAppListActionBindings(content=action_group_content),
)
interactiveMessageContent = InteractiveNotificationContent(
channel_registration_id=self.channel_id,
to=[self.phone_number],
interactive_message=interactionMessage,
)
# calling send() with whatsapp message details
message_responses = messaging_client.send(interactiveMessageContent)
response = message_responses.receipts[0]
print("Message with message id {} was successful sent to {}".format(response.message_id, response.to))
To run send_text_message(), update the main method:
#Calling send_whatsapplist_message()
messages.send_whatsapplist_message()
Send an Interactive Reply Button message to a WhatsApp user
The Messages SDK enables Contoso to send image WhatsApp messages to WhatsApp users. To send image embedded messages:
Reply Button Messages can be created using given properties:
Action type Description ButtonSetContentThis class defines button set content for reply button messages. ButtonContentThis class defines ID and title of the reply buttons. WhatsAppButtonActionBindingsThis class defines the ButtonSetContentbinding with the interactive message.
Important
To send a text message to a WhatsApp user, the WhatsApp user must first send a message to the WhatsApp Business Account. For more information, see Start sending messages between business and WhatsApp user.
In this example, the business sends a reply button message to the user.
def send_whatsappreplybutton_message(self):
from azure.communication.messages import NotificationMessagesClient
from azure.communication.messages.models import (
ButtonSetContent,
ButtonContent,
InteractiveMessage,
TextMessageContent,
WhatsAppButtonActionBindings,
InteractiveNotificationContent,
)
messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
reply_button_action_list = [
ButtonContent(title="Cancel", id="cancel"),
ButtonContent(title="Agree", id="agree"),
]
button_set = ButtonSetContent(buttons=reply_button_action_list)
interactionMessage = InteractiveMessage(
body=TextMessageContent(text="Test Body"),
footer=TextMessageContent(text="Test Footer"),
header=TextMessageContent(text="Test Header"),
action=WhatsAppButtonActionBindings(content=button_set),
)
interactiveMessageContent = InteractiveNotificationContent(
channel_registration_id=self.channel_id,
to=[self.phone_number],
interactive_message=interactionMessage,
)
# calling send() with whatsapp message details
message_responses = messaging_client.send(interactiveMessageContent)
response = message_responses.receipts[0]
print("Message with message id {} was successful sent to {}".format(response.message_id, response.to))
To run send_whatsappreplybutton_message(), update the main method:
# Calling send_imagesend_whatsappreplybutton_message_message()
messages.send_whatsappreplybutton_message()
Send an Interactive Call-To-Action Url based message to a WhatsApp user
The Messages SDK enables Contoso to send image WhatsApp messages to WhatsApp users. To send image embedded messages:
- WhatsApp Channel ID
- Recipient Phone Number in E16 format
- Call-To-Action or Link content can be created using given properties:
| Action type | Description |
|---|---|
LinkContent |
This class defines url or link content for message. |
WhatsAppUrlActionBindings |
This class defines the LinkContent binding with the interactive message. |
Important
To send a document message to a WhatsApp user, the WhatsApp user must first send a message to the WhatsApp Business Account. For more information, see Start sending messages between business and WhatsApp user.
In this example, the business sends a click to a link message to the user.
def send_whatapp_click_to_action_message(self):
from azure.communication.messages import NotificationMessagesClient
from azure.communication.messages.models import (
LinkContent,
InteractiveMessage,
TextMessageContent,
WhatsAppUrlActionBindings,
InteractiveNotificationContent,
)
messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
urlAction = LinkContent(
title="Test Url",
url="https://example.com/audio.mp3",
)
interactionMessage = InteractiveMessage(
body=TextMessageContent(text="Test Body"),
footer=TextMessageContent(text="Test Footer"),
header=TextMessageContent(text="Test Header"),
action=WhatsAppUrlActionBindings(content=urlAction),
)
interactiveMessageContent = InteractiveNotificationContent(
channel_registration_id=self.channel_id,
to=[self.phone_number],
interactive_message=interactionMessage,
)
# calling send() with whatsapp message details
message_responses = messaging_client.send(interactiveMessageContent)
response = message_responses.receipts[0]
print("WhatsApp CTA containing Message with message ID {} was successfully sent to {}".format(response.message_id, response.to))
To run send_whatapp_click_to_action_message(), update the main method:
# Calling send_whatapp_click_to_action_message()
messages.send_whatapp_click_to_action_message()
Run the code
To run the code, open the directory where your messages-quickstart.py file is located.
python interactive-messages-quickstart.py
Azure Communication Services - Advanced Messages Quickstart
WhatsApp List Message with message ID <<GUID>> was successfully sent to <<ToRecipient>>
WhatsApp Button Message with message ID <<GUID>> was successfully sent to <<ToRecipient>>
WhatsApp CTA containing Message with message ID <<GUID>> was successfully sent to <<ToRecipient>>
Full sample code
Note
Replace all placeholder variables in the code with your values.
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_whatsapplist_message(self):
from azure.communication.messages import NotificationMessagesClient
from azure.communication.messages.models import (
ActionGroupContent,
ActionGroup,
ActionGroupItem,
InteractiveMessage,
TextMessageContent,
WhatsAppListActionBindings,
InteractiveNotificationContent,
)
messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
action_items_list1 = [
ActionGroupItem(id="priority_express", title="Priority Mail Express", description="Next Day to 2 Days"),
ActionGroupItem(id="priority_mail", title="Priority Mail", description="1–3 Days"),
]
action_items_list2 = [
ActionGroupItem(id="usps_ground_advantage", title="USPS Ground Advantage", description="2-5 Days"),
ActionGroupItem(id="media_mail", title="Media Mail", description="2-8 Days"),
]
groups = [
ActionGroup(title="I want it ASAP!", items_property=action_items_list1),
ActionGroup(title="I can wait a bit", items_property=action_items_list2),
]
action_group_content = ActionGroupContent(title="Shipping Options", groups=groups)
interactionMessage = InteractiveMessage(
body=TextMessageContent(text="Test Body"),
footer=TextMessageContent(text="Test Footer"),
header=TextMessageContent(text="Test Header"),
action=WhatsAppListActionBindings(content=action_group_content),
)
interactiveMessageContent = InteractiveNotificationContent(
channel_registration_id=self.channel_id,
to=[self.phone_number],
interactive_message=interactionMessage,
)
# calling send() with whatsapp message details
message_responses = messaging_client.send(interactiveMessageContent)
response = message_responses.receipts[0]
print("WhatsApp List Message with message id {} was successful sent to {}".format(response.message_id, response.to))
def send_whatsappreplybutton_message(self):
from azure.communication.messages import NotificationMessagesClient
from azure.communication.messages.models import (
ButtonSetContent,
ButtonContent,
InteractiveMessage,
TextMessageContent,
WhatsAppButtonActionBindings,
InteractiveNotificationContent,
)
messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
reply_button_action_list = [
ButtonContent(title="Cancel", id="cancel"),
ButtonContent(title="Agree", id="agree"),
]
button_set = ButtonSetContent(buttons=reply_button_action_list)
interactionMessage = InteractiveMessage(
body=TextMessageContent(text="Test Body"),
footer=TextMessageContent(text="Test Footer"),
header=TextMessageContent(text="Test Header"),
action=WhatsAppButtonActionBindings(content=button_set),
)
interactiveMessageContent = InteractiveNotificationContent(
channel_registration_id=self.channel_id,
to=[self.phone_number],
interactive_message=interactionMessage,
)
# calling send() with whatsapp message details
message_responses = messaging_client.send(interactiveMessageContent)
response = message_responses.receipts[0]
print("WhatsApp Button Message with message id {} was successful sent to {}".format(response.message_id, response.to))
def send_whatapp_click_to_action_message(self):
from azure.communication.messages import NotificationMessagesClient
from azure.communication.messages.models import (
LinkContent,
InteractiveMessage,
TextMessageContent,
WhatsAppUrlActionBindings,
InteractiveNotificationContent,
)
messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
urlAction = LinkContent(
title="Test Url",
url="https://example.com/audio.mp3",
)
interactionMessage = InteractiveMessage(
body=TextMessageContent(text="Test Body"),
footer=TextMessageContent(text="Test Footer"),
header=TextMessageContent(text="Test Header"),
action=WhatsAppUrlActionBindings(content=urlAction),
)
interactiveMessageContent = InteractiveNotificationContent(
channel_registration_id=self.channel_id,
to=[self.phone_number],
interactive_message=interactionMessage,
)
# calling send() with whatsapp message details
message_responses = messaging_client.send(interactiveMessageContent)
response = message_responses.receipts[0]
print("WhatsApp CTA containing Message with message id {} was successful sent to {}".format(response.message_id, response.to))
if __name__ == '__main__':
messages = MessagesQuickstart()
messages.send_whatsapplist_message()
messages.send_whatsappreplybutton_message()
messages.send_whatapp_click_to_action_message()
Other samples
You can review and download other sample codes from GitHub Python Messages SDK.
Next steps
For more information, see: