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. This article describes how to integrate your app with Azure Communication Advanced Messages SDK to start sending and receiving WhatsApp reaction messages. Completing this article 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 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 Advanced Messaging SDK for .NET.
Class Name | Description |
---|---|
NotificationMessagesClient |
Connects to your Azure Communication Services resource. It sends the messages. |
ReactionNotificationContent |
Defines reaction message content. |
Note
For more information, see the Azure SDK for .NET reference Azure.Communication.Messages Namespace.
Common configuration
To configure your application, complete the following steps:
- Authenticate the client.
- Set channel registration ID.
- Set recipient list.
- Start sending messages between a business and a WhatsApp user.
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. 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 is currently supported in the recipient list.
Create the recipient list like this:
var recipientList = new List<string> { "<to WhatsApp phone number>" };
Example:
// Example only
var recipientList = new List<string> { "+14255550199" };
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
Follow these steps to add the required code snippets to the Main method in your Program.cs
file.
Send a reaction message to a WhatsApp user
The Azure Communication Services SDK enables Contoso to send reaction messages to WhatsApp users when initiated by the users. To send a reaction message, you need:
- Authenticated NotificationMessagesClient.
- WhatsApp channel ID.
- Recipient phone number in E.164 format.
- Emoji representing the reaction.
- Message ID of the original message being reacted to.
Action Type | Description |
---|---|
ReactionNotificationContent |
Class defining the reaction message content. |
Emoji |
Specifies the emoji reaction, such as 😄. |
MessageId |
ID of the message being replied to. |
In this example, the business sends a reaction message to the WhatsApp user:
Assemble the reaction content:
var reactionNotificationContent = new ReactionNotificationContent(channelRegistrationId, recipientList, "\uD83D\uDE00", "<ReplyMessageIdGuid>");
Send the reaction message:
var reactionResponse = await notificationMessagesClient.SendAsync(reactionNotificationContent);
Run the code
- To compile your code, press Ctrl+F7.
- To run the program without debugging, press Ctrl+F5.
Full sample code
Note
Replace all placeholder variables in the code with your values.
using Azure;
using Azure.Communication.Messages;
namespace AdvancedMessagingQuickstart
{
class Program
{
public static async Task Main(string[] args)
{
Console.WriteLine("Azure Communication Services - Send WhatsApp Reaction 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 a reaction message
var emojiReaction = "\uD83D\uDE00"; // 😄 emoji
var replyMessageId = "<ReplyMessageIdGuid>"; // Message ID of the original message
var reactionNotificationContent = new ReactionNotificationContent(channelRegistrationId, recipientList, emojiReaction, replyMessageId);
var reactionResponse = await notificationMessagesClient.SendAsync(reactionNotificationContent);
Console.WriteLine("Reaction message sent.\nPress any key to exit.\n");
Console.ReadKey();
}
}
}
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 for Java.
Class Name | Description |
---|---|
NotificationMessagesClient |
Connects to your Azure Communication Services resource. It sends the messages. |
ReactionNotificationContent |
Defines the reaction content of the messages with emoji and reply message ID. |
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. 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 is currently supported in the recipient list.
Create the recipient list like this:
List<String> recipientList = new ArrayList<>();
recipientList.add("<to WhatsApp phone number>");
Example:
// Example only
List<String> recipientList = new ArrayList<>();
recipientList.add("+14255550199");
Code examples
Follow these steps to add required code snippets to the main function of your App.java
file.
Send a Reaction messages to a WhatsApp user message
The Messages SDK enables Contoso to send reaction WhatsApp messages, when initiated by WhatsApp users. To send text messages:
- WhatsApp Channel ID.
- Recipient Phone Number in E16 format.
- Unicode escape sequence of the emoji.
- Message ID of message you want to apply the emoji to.
Important
To send a reaction to user message, 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.
Assemble and send the reaction to a message:
// Assemble reaction to a message
String emoji = "\uD83D\uDE00";
ReactionNotificationContent reaction = new ReactionNotificationContent("<CHANNEL_ID>", recipients, emoji, "<REPLY_MESSAGE_ID>");
// Send reaction to a message
SendMessageResult textMessageResult = notificationClient.send(reaction);
// 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.xml
file and compile the project using themvn
command.mvn compile
Run the app by executing the following
mvn
command.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 Java Messages SDK.
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 --version
to 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-quickstart
Run the following command to create a
package.json
file with default settings.npm init -y
Use a text editor to create a file called
send-messages.js
in 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 Messages SDK for JavaScript.
Class Name | Description |
---|---|
NotificationMessagesClient |
Connects to your Azure Communication Services resource. It sends the messages. |
ReactionNotificationContent |
Defines reaction message content. |
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.
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. 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 is currently supported in the recipient list.
Create the recipient list like this:
const recipientList = ["<to WhatsApp phone number>"];
Example:
// Example only
const recipientList = ["+14255550199"];
Code examples
Follow these steps to add required code snippets to your send-messages.js
file.
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. 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 is currently supported in the recipient list.
Create the recipient list like this:
const recipientList = ["<to WhatsApp phone number>"];
Example:
// Example only
const recipientList = ["+14255550199"];
Send a reaction messages to a WhatsApp user message
The Messages SDK enables Contoso to send reaction WhatsApp messages, when initiated by WhatsApp users. To send text messages:
- WhatsApp Channel ID.
- Recipient Phone Number in E16 format.
- Emoji.
- Message ID of message you want to apply the emoji to.
Important
To send a reaction to user message, 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 reaction to the user message:
/**
* @summary Send a reaction 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);
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: "reaction",
emoji: "😍",
messageId: "<incoming_message_id>",
},
});
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. |
ReactionNotificationContent |
Defines the reaction content of the messages with emoji and reply message ID. |
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. 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 is currently supported in the recipient list.
Set the recipient list like this:
phone_number = os.getenv("RECIPIENT_WHATSAPP_PHONE_NUMBER")
Usage Example:
# Example only
to=[self.phone_number],
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
Follow these steps to add required code snippets to the messages-quickstart.py
python program.
Send a reaction messages to a WhatsApp user message
The Messages SDK enables Contoso to send reaction WhatsApp messages, when initiated by WhatsApp users. To send text messages:
Reaction content can be created using given properties:
Action type Description ReactionNotificationContent This class defines title of the group content and array of the group. Emoji This property defines the unicode for emoji character. Reply Message ID This property defines ID of the message to be replied with emoji.
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 reaction to the user message:
def send_reaction_message(self):
from azure.communication.messages import NotificationMessagesClient
from azure.communication.messages.models import ReactionNotificationContent
messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
video_options = ReactionNotificationContent(
channel_registration_id=self.channel_id,
to=[self.phone_number],
emoji="\uD83D\uDE00",
message_id="<<ReplyMessageIdGuid>>",
)
# calling send() with whatsapp message details
message_responses = messaging_client.send(video_options)
response = message_responses.receipts[0]
print("Message with message ID {} was successful sent to {}".format(response.message_id, response.to))
To run send_reaction_message()
, update the main method:
#Calling send_reaction_message()
messages.send_reaction_message()
Run the code
To run the code, make sure you are in the directory where your reaction-messages-quickstart.py
file is located.
python reaction-messages-quickstart.py
Azure Communication Services - Advanced Messages Quickstart
WhatsApp Reaction 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_reaction_message(self):
from azure.communication.messages import NotificationMessagesClient
from azure.communication.messages.models import ReactionNotificationContent
messaging_client = NotificationMessagesClient.from_connection_string(self.connection_string)
video_options = ReactionNotificationContent(
channel_registration_id=self.channel_id,
to=[self.phone_number],
emoji="\uD83D\uDE00",
message_id="<<ReplyMessageIdGuid>>",
)
# calling send() with whatsapp message details
message_responses = messaging_client.send(video_options)
response = message_responses.receipts[0]
print("WhatsApp Reaction Message with message ID {} was successful sent to {}".format(response.message_id, response.to))
if __name__ == '__main__':
messages = MessagesQuickstart()
messages.send_reaction_message()
Other samples
You can review and download other sample codes on GitHub at Python Messages SDK.
Next steps
For more information, see: