次の方法で共有


高度なメッセージングを使用してテキストとメディアの WhatsApp メッセージを送信する

Azure Communication Services では、WhatsApp メッセージを送受信することができます。 この記事では、アプリを Azure Communication Advanced Messages SDK と統合して、WhatsApp メッセージの送受信を開始する方法について説明します。 この記事を完了すると、ご利用の Azure アカウントでわずかな (米国ドルで数セント未満の) コストが発生します。

前提条件

環境を設定する

.NET プロジェクトを作成する

プロジェクトを作成するには、「Visual Studio を使用して .NET コンソール アプリケーションを作成する」のチュートリアルに従います。

コードをコンパイルするには、Ctrl+F7 キーを押します。

パッケージをインストールする

C# プロジェクトに Azure.Communication.Messages NuGet パッケージをインストールします。

  1. [Project]>[Manage NuGet Packages...] で NuGet パッケージ マネージャーを開きます。
  2. パッケージ Azure.Communication.Messages を検索します。
  3. 最新リリースをインストールします。

アプリのフレームワークを設定する

テキスト エディターで Program.cs ファイルを開きます。

Program.cs の内容を次のコードで置き換えます。

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

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

            // Quickstart code goes here
        }
    }
}

高度なメッセージングの機能を使用するには、using ディレクティブを追加して、Azure.Communication.Messages 名前空間を含めます。

using Azure.Communication.Messages;

オブジェクト モデル

Azure Communication Services Advance Messaging SDK for .NET の主な機能のいくつかは、以下のクラスとインターフェイスによって処理されます。

Class Name (クラス名) 説明
NotificationMessagesClient Azure Communication Services リソースに接続します。 これはメッセージを送信します。
MessageTemplate 使用するテンプレートと、メッセージのテンプレート プロパティの内容を定義します。
TemplateNotificationContent 送信しようとしているテンプレート メッセージの "対象者" と "内容" を定義します。
TextNotificationContent 送信しようとしているテキスト メッセージの "対象者" と "内容" を定義します。
ImageNotificationContent 送信しようとしている画像メディア メッセージの "対象者" と "内容" を定義します。
DocumentNotificationContent 送信しようとしているドキュメント メディア メッセージの "対象者" と "内容" を定義します。
VideoNotificationContent 送信しようとしているビデオ メディア メッセージの "対象者" と "内容" を定義します。
AudioNotificationContent 送信しようとしているオーディオ メディア メッセージの "対象者" と "内容" を定義します。

Note

詳細については、Azure SDK for .NET のリファレンス Azure.Communication.Messages 名前空間をご覧ください。

一般的な構成

次の手順に従って、Python プログラム messages-quickstart.py に必要なコード スニペットを追加します。

クライアントを認証する

Messages SDK は NotificationMessagesClient を使用してメッセージを送信します。 NotificationMessagesClient メソッドは、Azure portal で Azure Communication Services リソースから取得した接続文字列を使用して認証できます。 接続文字列の詳細については、「接続文字列とサービス エンドポイントにアクセスする」をご覧ください。

わかりやすくするために、このクイック スタートでは接続文字列を使用して認証を行います。 運用環境では、サービス プリンシパルを使用することをお勧めします。

Azure portal の Azure Communication Services リソースから接続文字列を取得します。 左側にある [Keys] タブに移動します。主キーの Connection string フィールドをコピーします。 接続文字列は、形式 endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key} になっています。

Azure portal の Azure Communication Services リソースを示すスクリーンショット。[主キー] セクションの [接続文字列] フィールドが表示されています。

環境変数 COMMUNICATION_SERVICES_CONNECTION_STRING を接続文字列の値に設定します。
コンソール ウィンドウを開き、次のコマンドを入力します。

setx COMMUNICATION_SERVICES_CONNECTION_STRING "<your connection string>"

環境変数を追加した後、環境変数の読み取りを必要とする実行中のプログラム (コンソール ウィンドウを含む) については、再起動が必要となる場合があります。 たとえば、Visual Studio をエディターとして使用している場合、サンプルを実行する前に Visual Studio を再起動します。

お使いのシステムの環境変数を設定する方法の詳細については、「環境変数に接続文字列を格納する」の手順に従ってください。

NotificationMessagesClient をインスタンス化するには、Main メソッドに次のコードを追加します。

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

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

チャネル登録 ID の設定

チャネル登録 ID GUID は、チャネルの登録時に作成されています。 ポータルの Azure Communication Services リソースの [チャネル] タブで確認できます。

Azure portal の Azure Communication Services リソースを示すスクリーンショット。[チャネル] タブが表示されています。[チャネル ID] フィールドのコピー アクションに注意が必要です。

これを channelRegistrationId という変数に割り当てます。

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

受信者リストの設定

WhatsApp アカウントに紐付けられた有効な電話番号を指定する必要があります。 この WhatsApp アカウントは、このクイックスタートで送信されたテンプレート、テキスト、およびメディア メッセージを受信します。

この例では、個人の電話番号を使用できます。

受信者の電話番号は、WhatsApp チャネル登録に紐付けたビジネス電話番号 (送信者 ID) にすることはできません。 送信者 ID は、受信者に送信されるテキスト メッセージやメディア メッセージの送信者として表示されます。

電話番号には国番号を含める必要があります。 電話番号の形式の詳細については、電話番号の形式に関する WhatsApp ドキュメントをご覧ください。

Note

現在、受信者リストでサポートされている電話番号は 1 つだけです。

次のように受信者リストを作成します。

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

例:

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

ビジネス ユーザーと WhatsApp ユーザーの間でメッセージの送信を開始する

WhatsApp ビジネス アカウントと WhatsApp ユーザーの間の会話は、次の 2 つのいずれかの方法で開始できます。

  • 企業は、WhatsApp ユーザーにテンプレート メッセージを送信します。
  • WhatsApp ユーザーは、ビジネス番号にメッセージを送信します。

企業が対話型の会話を開始することはできません。 企業は、ユーザーからメッセージを受信した後にのみ対話型メッセージを送信できます。 企業は、アクティブな会話中にのみ対話型メッセージをユーザーに送信できます。 24 時間の会話ウィンドウの有効期限が切れると、ユーザーだけが対話型の会話を再開できます。 会話の詳細については、WhatsApp Business Platform で定義をご覧ください。

個人用 WhatsApp アカウントから対話型の会話を開始するには、ビジネス番号 (送信者 ID) にメッセージを送信します。

WhatsApp Business アカウント番号に送信されたユーザー メッセージを示す Web 上で表示された WhatsApp の会話。

コード例

次の手順に従って、Program.cs ファイルの Main 関数に必要なコード スニペットを追加します。

重要

WhatsApp ユーザーにテキストまたはメディア メッセージを送信するには、最初に WhatsApp ユーザーが WhatsApp ビジネス アカウントにメッセージを送信する必要があります。 詳細については、「ビジネス ユーザーと WhatsApp ユーザーの間のメッセージ送信開始」を参照してください。

WhatsApp ユーザーにテキスト メッセージを送信する

Messages SDK を使用すると、Contoso は WhatsApp ユーザーが開始した WhatsApp テキスト メッセージを送信できます。 テキスト メッセージを送信するには、次のものが必要です。

この例では、WhatsApp ユーザーにテキスト メッセージ "Thanks for your feedback.\n From Notification Messaging SDK." で返信しています

次のテキスト メッセージを組み立てて送信します。

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

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

WhatsApp ユーザーに画像メディア メッセージを送信する

Messages SDK を使用すると、Contoso は WhatsApp メディア メッセージを WhatsApp ユーザーに送信できます。 埋め込みメディア メッセージを送信するには、次のものが必要です。

重要

SDK バージョン 1.1.0 の時点では、MediaNotificationContent は画像では非推奨となっています。 画像の送信には ImageNotificationContent を使用することをお勧めします。 DocumentNotificationContentVideoNotificationContentAudioNotificationContent などの他のメディアの種類では、他のコンテンツ固有のクラスを検討します。

画像メッセージをアセンブルします。

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

画像メッセージを送信します。

var imageResponse = await notificationMessagesClient.SendAsync(imageNotificationContent);

WhatsApp ユーザーにドキュメント メディア メッセージを送信する

Messages SDK を使用すると、Contoso は WhatsApp メディア メッセージを WhatsApp ユーザーに送信できます。 埋め込みメディア メッセージを送信するには、次のものが必要です。

ドキュメントの内容をアセンブルします。

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

ドキュメント メッセージを送信します。

var documentResponse = await notificationMessagesClient.SendAsync(documentNotificationContent);

WhatsApp ユーザーにビデオ メディア メッセージを送信する

Messages SDK を使用すると、Contoso は WhatsApp メディア メッセージを WhatsApp ユーザーに送信できます。 埋め込みメディア メッセージを送信するには、次のものが必要です。

ビデオ メッセージをアセンブルします。

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

ビデオ メッセージを送信します。

var videoResponse = await notificationMessagesClient.SendAsync(videoNotificationContent);

WhatsApp ユーザーにオーディオ メディア メッセージを送信する

Messages SDK を使用すると、Contoso は WhatsApp メディア メッセージを WhatsApp ユーザーに送信できます。 埋め込みメディア メッセージを送信するには、次のものが必要です。

オーディオ メッセージをアセンブルします。

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

オーディオ メッセージを送信します。

var audioResponse = await notificationMessagesClient.SendAsync(audioNotificationContent);

コードの実行

プログラムをビルドして実行します。

テキストまたはメディア メッセージを WhatsApp ユーザーに送信するには、WhatsApp ビジネス アカウントと WhatsApp ユーザーの間で会話がアクティブである必要があります。

アクティブな会話がない場合、この例では、テンプレート メッセージの送信とテキスト メッセージの送信の間に待機時間を追加します。 この遅延を追加することで、企業に返信するのに十分な時間をユーザーの WhatsApp アカウントで確保できます。 参考のために、サンプル コードにある完全な例では、次のメッセージを送信する前にユーザーによる手動入力を求めるプロンプトが表示されます。

成功すると、ユーザーの WhatsApp アカウントに 3 件のメッセージが届きます。

  1. コードをコンパイルするには、Ctrl+F7 キーを押します。
  2. デバッグせずにプログラムを実行するには、Ctrl+F5 キーを押します。

完全なサンプル コード

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

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

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

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

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

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

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

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

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

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

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

前提条件

環境を設定する

メッセージを送信するための環境を設定するには、次のセクションの手順を実行します。

新しい Java アプリケーションを作成する

ターミナルまたはコマンド ウィンドウを開き、Java アプリケーションを作成するディレクトリに移動します。 次のコマンドを実行して、maven-archetype-quickstart テンプレートから Java プロジェクトを生成します。

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

generate 目標により、artifactId 値と同じ名前のディレクトリが作成されます。 このディレクトリの下の src/main/java ディレクトリにはプロジェクトのソース コードが含まれ、src/test/java ディレクトリにはテスト ソースが含まれ、pom.xml ファイルはプロジェクトのプロジェクト オブジェクト モデル (POM) です。

パッケージをインストールする

テキスト エディターで pom.xml ファイルを開きます。 依存関係のグループに、次の dependency 要素を追加します。

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

アプリのフレームワークを設定する

テキスト エディターで /src/main/java/com/communication/quickstart/App.java を開き、import ディレクティブを追加して、System.out.println("Hello world!"); ステートメントを削除します:

package com.communication.quickstart;

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

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

コード例

次の手順に従って、App.java ファイルの Main 関数に必要なコード スニペットを追加します。

ビジネス ユーザーと WhatsApp ユーザーの間でメッセージの送信を開始する

WhatsApp ビジネス アカウントと WhatsApp ユーザーの間の会話は、次の 2 つのいずれかの方法で開始できます。

  • 企業は、WhatsApp ユーザーにテンプレート メッセージを送信します。
  • WhatsApp ユーザーは、ビジネス番号にメッセージを送信します。

会話の開始方法に関係なく、ユーザーが企業にメッセージを送信するまで、企業はテンプレート メッセージしか送信できません。ユーザーが企業にメッセージを送信してはじめて、企業はアクティブな会話中にテキストまたはメディア メッセージをユーザーに送信できます。 24 時間の会話期間が終了したら、会話を再開する必要があります。 会話の詳細については、WhatsApp Business Platform にある定義を参照してください。

クライアントを認証する

メッセージ クライアントの認証には、次のようないくつかの異なるオプションを使用できます。

クライアントを認証するには、接続文字列を使用して NotificationMessagesClient または MessageTemplateClient をインスタンス化します。 クライアントは、com.azure.core.http.HttpClient インターフェイスを実装する任意のカスタム HTTP クライアントを使用して初期化することもできます。

わかりやすくするために、このクイック スタートでは接続文字列を使用して認証を行います。 運用環境では、サービス プリンシパルを使用することをお勧めします。

Azure portal の Azure Communication Services リソースから接続文字列を取得します。 左側にある [Keys] タブに移動します。Primary keyConnection string フィールドをコピーします。 接続文字列は、形式 endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key} になっています。

Azure portal の Azure Communication Services リソースを示すスクリーンショット。[主キー] セクションの [接続文字列] フィールドが表示されています。

環境変数 COMMUNICATION_SERVICES_CONNECTION_STRING を接続文字列の値に設定します。
コンソール ウィンドウを開き、次のコマンドを入力します。

setx COMMUNICATION_SERVICES_CONNECTION_STRING "<your connection string>"

お使いのシステムの環境変数を設定する方法の詳細については、「環境変数に接続文字列を格納する」の手順に従ってください。

NotificationMessagesClient をインスタンス化するには、main メソッドに次のコードを追加します。

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

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

チャネル登録 ID の設定

チャネル登録 ID GUID は、チャネルの登録時に作成されたものです。 ポータルの Azure Communication Services リソースの [チャネル] タブで確認できます。

Azure portal の Azure Communication Services リソースを示すスクリーンショット。[チャネル] タブが表示されています。[チャネル ID] フィールドのコピー アクションに注意が必要です。

これを channelRegistrationId という変数に割り当てます。

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

受信者リストの設定

WhatsApp アカウントを紐付けた実際の電話番号を指定する必要があります。 この WhatsApp アカウントは、クイックスタートで送信されたテキスト メッセージとメディア メッセージを受信します。 このクイックスタートでは、この電話番号は個人用の電話番号でも問題ありません。

受信者の電話番号は、WhatsApp チャネル登録に紐付けたビジネス電話番号 (送信者 ID) にすることはできません。 送信者 ID は、受信者に送信されるテキスト メッセージやメディア メッセージの送信者として表示されます。

電話番号には国番号を含める必要があります。 電話番号の形式の詳細については、電話番号の形式に関する WhatsApp ドキュメントを参照してください。

Note

現在、受信者リストでサポートされている電話番号は 1 つだけです。

次のように受信者リストを作成します。

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

例:

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

WhatsApp ユーザーにテキスト メッセージを送信する

Messages SDK を使用すると、Contoso は WhatsApp ユーザーが開始した WhatsApp メッセージ テキストを送信できます。 テキスト メッセージを送信するには、以下の詳細情報が必要です。

この例では、WhatsApp ユーザーにテキスト メッセージ "Thanks for your feedback.\n From Notification Messaging SDK." で返信しています

重要

WhatsApp ユーザーにテキスト メッセージを送信するには、最初に WhatsApp ユーザーが WhatsApp ビジネス アカウントにメッセージを送信する必要があります。 詳細については、「ビジネス ユーザーと WhatsApp ユーザーの間のメッセージ送信開始」を参照してください。

次のテキスト メッセージを組み立てて送信します。

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

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

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

WhatsApp ユーザーに画像メディア メッセージを送信する

Messages SDK を使用すると、Contoso はメディア (画像、ビデオ、オーディオ、またはドキュメント) メッセージを WhatsApp ユーザーに送信できます。 埋め込みメディア メッセージを送信するには、次のものが必要です。

重要

SDK バージョン 1.1.0 の時点では、MediaNotificationContent は画像では非推奨となっています。 ImageNotificationContent を使用して画像を送信することをお勧めします。 DocumentNotificationContentVideoNotificationContentAudioNotificationContent などの他のメディアの種類では、他のコンテンツ固有のクラスを検討します。

重要

WhatsApp ユーザーに画像メッセージを送信するには、最初に WhatsApp ユーザーが WhatsApp ビジネス アカウントにメッセージを送信する必要があります。 詳細については、「ビジネス ユーザーと WhatsApp ユーザーの間のメッセージ送信開始」を参照してください。

次の画像メッセージを組み立てて送信します。

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

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

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

WhatsApp ユーザーにビデオ メディア メッセージを送信する

Messages SDK を使用すると、Contoso はメディア (画像、ビデオ、オーディオ、またはドキュメント) メッセージを WhatsApp ユーザーに送信できます。 埋め込みメディア メッセージを送信するには、次のものが必要です。

重要

WhatsApp ユーザーにビデオ メッセージを送信するには、最初に WhatsApp ユーザーが WhatsApp ビジネス アカウントにメッセージを送信する必要があります。 詳細については、「ビジネス ユーザーと WhatsApp ユーザーの間のメッセージ送信開始」を参照してください。

ビデオ メッセージをアセンブルして送信します。

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

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

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

WhatsApp ユーザーにオーディオ メディア メッセージを送信する

Messages SDK を使用すると、Contoso はメディア (画像、ビデオ、オーディオ、またはドキュメント) メッセージを WhatsApp ユーザーに送信できます。 埋め込みメディア メッセージを送信するには、次のものが必要です。

重要

WhatsApp ユーザーにオーディオ メッセージを送信するには、最初に WhatsApp ユーザーが WhatsApp ビジネス アカウントにメッセージを送信する必要があります。 詳細については、「ビジネス ユーザーと WhatsApp ユーザーの間のメッセージ送信開始」を参照してください。

オーディオ メッセージをアセンブルして送信します。

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

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

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

WhatsApp ユーザーにドキュメント メディア メッセージを送信する

Messages SDK を使用すると、Contoso はメディア (画像、ビデオ、オーディオ、またはドキュメント) メッセージを WhatsApp ユーザーに送信できます。 埋め込みメディア メッセージを送信するには、次のものが必要です。

重要

WhatsApp ユーザーにドキュメント メッセージを送信するには、最初に WhatsApp ユーザーが WhatsApp ビジネス アカウントにメッセージを送信する必要があります。 詳細については、「ビジネス ユーザーと WhatsApp ユーザーの間のメッセージ送信開始」を参照してください。

ドキュメント メッセージをアセンブルして送信します。

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

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

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

コードの実行

  1. pom.xml ファイルが格納されているディレクトリを開き、mvn コマンドを使用してプロジェクトをコンパイルします。

    mvn compile
    
  2. 次の mvn コマンドを実行して、アプリを実行します。

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

完全なサンプル コード

このクイックスタートの最終的なコードは GitHub にあります。

前提条件

設定

新しい Node.js アプリケーションを作成する

  1. 自分のアプリ用に新しいディレクトリを作成し、ターミナルまたはコマンド ウィンドウで開きます。

  2. 次のコマンドを実行します。

    mkdir advance-messages-quickstart && cd advance-messages-quickstart
    
  3. 既定の設定で次のコマンドを実行して、package.json ファイルを作成します。

    npm init -y
    
  4. テキスト エディターを使って、プロジェクトのルート ディレクトリに send-messages.js というファイルを作成します。

  5. 次のコード スニペットをファイル send-messages.js に追加します。

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

次のセクションを完了して、この例のソース コードを作成した send-messages.js ファイルに追加します。

パッケージをインストールする

npm install コマンドを使用して、Azure Communication Services Advance Messaging SDK for JavaScript をインストールします。

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

--save オプションを使用すると、package.json ファイル内の依存関係としてライブラリが表示されます。

コード例

次の手順に従って、send-messages.js ファイルの Main 関数に必要なコード スニペットを追加します。

ビジネス ユーザーと WhatsApp ユーザーの間でメッセージの送信を開始する

WhatsApp ビジネス アカウントと WhatsApp ユーザーの間の会話は、次の 2 つのいずれかの方法で開始できます。

  • 企業は、WhatsApp ユーザーにテンプレート メッセージを送信します。
  • WhatsApp ユーザーは、ビジネス番号にメッセージを送信します。

会話の開始方法に関係なく、ユーザーが企業にメッセージを送信するまで、企業はテンプレート メッセージしか送信できません。ユーザーが企業にメッセージを送信してはじめて、企業はアクティブな会話中にテキストまたはメディア メッセージをユーザーに送信できます。 24 時間の会話期間が終了したら、会話を再開する必要があります。 会話の詳細については、WhatsApp Business Platform にある定義を参照してください。

クライアントを認証する

次のコードは、dotenv パッケージを使用して、COMMUNICATION_SERVICES_CONNECTION_STRING という名前の環境変数からリソースの接続文字列を取得します。

わかりやすくするために、このクイック スタートでは接続文字列を使用して認証を行います。 運用環境では、サービス プリンシパルを使用することをお勧めします。

Azure portal の Azure Communication Services リソースから接続文字列を取得します。 左側にある [Keys] タブに移動します。Primary keyConnection string フィールドをコピーします。 接続文字列は、形式 endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key} になっています。

Azure portal の Azure Communication Services リソースを示すスクリーンショット。[主キー] セクションの [接続文字列] フィールドが表示されています。

環境変数 COMMUNICATION_SERVICES_CONNECTION_STRING を接続文字列の値に設定します。
コンソール ウィンドウを開き、次のコマンドを入力します。

setx COMMUNICATION_SERVICES_CONNECTION_STRING "<your connection string>"

お使いのシステムの環境変数を設定する方法の詳細については、「環境変数に接続文字列を格納する」の手順に従ってください。

NotificationClient のインスタンスを作成するには、Main メソッドに次のコードを追加します。

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

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

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

チャネル登録 ID の設定

チャネル登録 ID GUID は、チャネルの登録時に作成されたものです。 ポータルの Azure Communication Services リソースの [チャネル] タブで確認できます。

Azure portal の Azure Communication Services リソースを示すスクリーンショット。[チャネル] タブが表示されています。[チャネル ID] フィールドのコピー アクションに注意が必要です。

これを channelRegistrationId という変数に割り当てます。

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

受信者リストの設定

WhatsApp アカウントを紐付けた実際の電話番号を指定する必要があります。 この WhatsApp アカウントは、このクイックスタートで送信されたテンプレート、テキスト、およびメディア メッセージを受信します。 このクイックスタートでは、この電話番号は個人用の電話番号でも問題ありません。

受信者の電話番号は、WhatsApp チャネル登録に紐付けたビジネス電話番号 (送信者 ID) にすることはできません。 送信者 ID は、受信者に送信されるテキスト メッセージやメディア メッセージの送信者として表示されます。

電話番号には国番号を含める必要があります。 電話番号の形式の詳細については、電話番号の形式に関する WhatsApp ドキュメントを参照してください。

Note

現在、受信者リストでサポートされている電話番号は 1 つだけです。

次のように受信者リストを作成します。

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

例:

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

重要

WhatsApp ユーザーにメッセージを送信するには、最初に WhatsApp ユーザーが WhatsApp ビジネス アカウントにメッセージを送信する必要があります。 詳細については、「ビジネス ユーザーと WhatsApp ユーザーの間のメッセージ送信開始」を参照してください。

WhatsApp ユーザーにテキスト メッセージを送信する

Messages SDK を使用すると、Contoso は WhatsApp ユーザーによって開始されたときに WhatsApp テキスト メッセージを送信できます。 テキスト メッセージを送信するには:

この例では、WhatsApp ユーザーにテキスト メッセージ "Thanks for your feedback.\n From Notification Messaging SDK." で返信しています

次のテキスト メッセージを組み立てて送信します。

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

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

WhatsApp ユーザーに画像メディア メッセージを送信する

Messages SDK を使用すると、Contoso はメディア (画像、ビデオ、オーディオ、またはドキュメント) メッセージを WhatsApp ユーザーに送信できます。 埋め込みメディア メッセージを送信するには、次のものが必要です。

重要

SDK バージョン 2.0.0 の時点では、MediaNotificationContent は画像では非推奨となっています。 ImageNotificationContent を使用して画像を送信することをお勧めします。 DocumentNotificationContentVideoNotificationContentAudioNotificationContent などの他のメディアの種類では、他のコンテンツ固有のクラスを検討します。

画像メッセージを送信するには、画像の URL を指定します。 次に例を示します。

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

次のメディア メッセージを組み立てて送信します。

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

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

WhatsApp ユーザーにビデオ メディア メッセージを送信する

Messages SDK を使用すると、Contoso はメディア (画像、ビデオ、オーディオ、またはドキュメント) メッセージを WhatsApp ユーザーに送信できます。 埋め込みメディア メッセージを送信するには、次のものが必要です。

ビデオ メッセージを送信するには、ビデオの URL を指定します。 たとえば、

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

ビデオ メッセージをアセンブルして送信します。

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

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

WhatsApp ユーザーにオーディオ メディア メッセージを送信する

Messages SDK を使用すると、Contoso はメディア (画像、ビデオ、オーディオ、またはドキュメント) メッセージを WhatsApp ユーザーに送信できます。 埋め込みメディア メッセージを送信するには、次のものが必要です。

オーディオ メッセージを送信するには、オーディオ ファイルの URL を指定します。 例

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

オーディオ メッセージをアセンブルして送信します。

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

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

WhatsApp ユーザーにドキュメント メディア メッセージを送信する

Messages SDK を使用すると、Contoso はメディア (画像、ビデオ、オーディオ、またはドキュメント) メッセージを WhatsApp ユーザーに送信できます。 埋め込みメディア メッセージを送信するには、次のものが必要です。

ドキュメント メッセージを送信するには、ドキュメントの URL を指定します。 たとえば、

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

ドキュメント メッセージをアセンブルして送信します。

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

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

コードの実行

node コマンドを使用して、send-messages.js ファイルに追加したコードを実行します。

node ./send-messages.js

完全なサンプル コード

このクイックスタートの最終的なコードは GitHub にあります。

前提条件

設定

新しい Python アプリケーションを作成する

ターミナルまたはコンソール ウィンドウで、アプリケーション用の新しいフォルダーを作成して開きます。

mkdir messages-quickstart && cd messages-quickstart

パッケージをインストールする

Python 1.1.0 以降の Azure Communication Messages クライアント ライブラリを使う必要があります。

コンソールのプロンプトから次のコマンドを実行します:

pip install azure-communication-messages

InteractiveMessages、Reactions、Stickers には、以下のベータ版を使用してください:

pip install azure-communication-messages==1.2.0b1

アプリのフレームワークを設定する

messages-quickstart.py という名前の新しいファイルを作成し、基本的なプログラム構造を追加します。

type nul > messages-quickstart.py   

基本的なプログラム構造

import os

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

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

オブジェクト モデル

Python 用 Azure Communication Services Messages SDK が備える主な機能のいくつかは、以下のクラスとインターフェイスにより処理されます。

Class Name (クラス名) 説明
NotificationMessagesClient Azure Communication Services リソースに接続します。 これはメッセージを送信します。
MessageTemplate 使用するテンプレートと、メッセージのテンプレート プロパティの内容を定義します。
TemplateNotificationContent 送信しようとしているテンプレート メッセージの "対象者" と "内容" を定義します。
TextNotificationContent 送信しようとしているテキスト メッセージの "対象者" と "内容" を定義します。
ImageNotificationContent 送信しようとしている画像メディア メッセージの "対象者" と "内容" を定義します。
DocumentNotificationContent 送信しようとしているドキュメント メディア メッセージの "対象者" と "内容" を定義します。
VideoNotificationContent 送信しようとしているビデオ メディア メッセージの "対象者" と "内容" を定義します。
AudioNotificationContent 送信しようとしているオーディオ メディア メッセージの "対象者" と "内容" を定義します。

Note

詳細については、Azure SDK for Python のリファレンスであるメッセージ パッケージをご覧ください。

一般的な構成

次の手順に従って、必要なコード スニペットを messages-quickstart.py Python プログラムに追加します。

クライアントを認証する

メッセージの送信は NotificationMessagesClient を使用して行われます。 NotificationMessagesClient は、Azure portal で Azure Communication Services リソースから取得した接続文字列を使用して認証できます。 接続文字列の詳細については、「access-your-connection-strings-and-service-endpoints」を参照してください。

スクリーンショットに示すように、Azure portal から Azure Communication Resource 接続文字列を取得します。 左側にある [Keys] タブに移動します。主キーの Connection string フィールドをコピーします。 接続文字列は、形式 endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key} になっています。

Azure portal の Azure Communication Services リソースを示すスクリーンショット。[キー] セクションの [主キー] フィールドが表示されています。

環境変数 COMMUNICATION_SERVICES_CONNECTION_STRING を接続文字列の値に設定します。
コンソール ウィンドウを開き、次のコマンドを入力します。

setx COMMUNICATION_SERVICES_CONNECTION_STRING "<your connection string>"

環境変数を追加した後、環境変数の読み取りを必要とする実行中のプログラム (コンソール ウィンドウを含む) については、再起動が必要となる場合があります。 たとえば、Visual Studio をエディターとして使用している場合、サンプルを実行する前に Visual Studio を再起動します。

お使いのシステムの環境変数を設定する方法の詳細については、「環境変数に接続文字列を格納する」の手順に従ってください。

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

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

チャネル登録 ID の設定

チャネル登録 ID GUID は、チャネルの登録時に作成されています。 ポータルの Azure Communication Services リソースの [チャネル] タブで確認できます。

Azure portal の Azure Communication Services リソースを示すスクリーンショット。[チャネル] タブが表示されています。[チャネル ID] フィールドのコピー アクションに注意が必要です。

これを channelRegistrationId という変数に割り当てます。

    channelRegistrationId = os.getenv("WHATSAPP_CHANNEL_ID_GUID")

受信者リストの設定

WhatsApp アカウントに紐付けられた有効な電話番号を指定する必要があります。 この WhatsApp アカウントは、このクイックスタートで送信されたテンプレート、テキスト、およびメディア メッセージを受信します。

この例では、個人の電話番号を使用できます。

受信者の電話番号は、WhatsApp チャネル登録に紐付けたビジネス電話番号 (送信者 ID) にすることはできません。 送信者 ID は、受信者に送信されるテキスト メッセージやメディア メッセージの送信者として表示されます。

電話番号には国番号を含める必要があります。 電話番号の形式の詳細については、電話番号の形式に関する WhatsApp ドキュメントをご覧ください。

Note

現在、受信者リストでサポートされている電話番号は 1 つだけです。

次のように受信者リストを設定します。

    phone_number = os.getenv("RECIPIENT_WHATSAPP_PHONE_NUMBER")

使用例:

    # Example only
    to=[self.phone_number],

ビジネス ユーザーと WhatsApp ユーザーの間でメッセージの送信を開始する

WhatsApp ビジネス アカウントと WhatsApp ユーザーの間の会話は、次の 2 つのいずれかの方法で開始できます。

  • 企業は、WhatsApp ユーザーにテンプレート メッセージを送信します。
  • WhatsApp ユーザーは、ビジネス番号にメッセージを送信します。

企業が対話型の会話を開始することはできません。 企業は、ユーザーからメッセージを受信した後にのみ対話型メッセージを送信できます。 企業は、アクティブな会話中にのみ対話型メッセージをユーザーに送信できます。 24 時間の会話ウィンドウの有効期限が切れると、ユーザーだけが対話型の会話を再開できます。 会話の詳細については、WhatsApp Business Platform で定義をご覧ください。

個人用 WhatsApp アカウントから対話型の会話を開始するには、ビジネス番号 (送信者 ID) にメッセージを送信します。

WhatsApp Business アカウント番号に送信されたユーザー メッセージを示す Web 上で表示された WhatsApp の会話。

コード例

次の手順に従って、Python プログラム messages-quickstart.py に必要なコード スニペットを追加します。

WhatsApp ユーザーにテキスト メッセージを送信する

Messages SDK を使用すると、Contoso は WhatsApp ユーザーによって開始されたときに WhatsApp テキスト メッセージを送信できます。 テキスト メッセージを送信するには:

重要

WhatsApp ユーザーにテキスト メッセージを送信するには、最初に WhatsApp ユーザーが WhatsApp ビジネス アカウントにメッセージを送信する必要があります。 詳細については、「ビジネス ユーザーと WhatsApp ユーザーの間のメッセージ送信開始」を参照してください。

この例では、WhatsApp ユーザーにテキスト メッセージ "Thanks for your feedback.\n From Notification Messaging SDK." で返信しています

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

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

send_text_message() を実行するには、Main メソッドを更新します。

    #Calling send_text_message()
    messages.send_text_message()

WhatsApp ユーザーに画像メディア メッセージを送信する

Messages SDK を使用すると、Contoso は WhatsApp 画像メッセージを WhatsApp ユーザーに送信できます。 画像を埋め込んだメッセージを送信するには:

重要

WhatsApp ユーザーにテキスト メッセージを送信するには、最初に WhatsApp ユーザーが WhatsApp ビジネス アカウントにメッセージを送信する必要があります。 詳細については、「ビジネス ユーザーと WhatsApp ユーザーの間のメッセージ送信開始」を参照してください。

WhatsApp メディア メッセージを送信するときに使用する media_uri の例。

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

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

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

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

send_text_message() を実行するには、Main メソッドを更新します。

    # Calling send_image_message()
    messages.send_image_message()

WhatsApp ユーザーにドキュメント メディア メッセージを送信する

Messages SDK を使用すると、Contoso は WhatsApp ユーザーに WhatsApp ドキュメント メッセージを送信できます。 ドキュメントを埋め込んだメッセージを送信するには:

重要

WhatsApp ユーザーにドキュメント メッセージを送信するには、最初に WhatsApp ユーザーが WhatsApp ビジネス アカウントにメッセージを送信する必要があります。 詳細については、「ビジネス ユーザーと WhatsApp ユーザーの間のメッセージ送信開始」を参照してください。

WhatsApp メディア メッセージを送信するときに使用する media_uri の例。

input_media_uri: str = "##DocumentLinkPlaceholder##"

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

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

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

send_text_message() を実行するには、Main メソッドを更新します。

    # Calling send_image_message()
    messages.send_image_message()

WhatsApp ユーザーにオーディオ メディア メッセージを送信する

Messages SDK を使用すると、Contoso は WhatsApp 画像メッセージを WhatsApp ユーザーに送信できます。 オーディオを埋め込んだメッセージを送信するには:

重要

WhatsApp ユーザーにオーディオ メッセージを送信するには、最初に WhatsApp ユーザーが WhatsApp ビジネス アカウントにメッセージを送信する必要があります。 詳細については、「ビジネス ユーザーと WhatsApp ユーザーの間のメッセージ送信開始」を参照してください。

WhatsApp メディア メッセージを送信するときに使用する media_uri の例。

input_media_uri: str = "##AudioLinkPlaceholder##"

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

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

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

send_text_message() を実行するには、Main メソッドを更新します。

    # Calling send_image_message()
    messages.send_image_message()

WhatsApp ユーザーにビデオ メディア メッセージを送信する

Messages SDK を使用すると、Contoso は WhatsApp ビデオ メッセージを WhatsApp ユーザーに送信できます。 ビデオを埋め込んだメッセージを送信するには:

重要

WhatsApp ユーザーにビデオ メッセージを送信するには、最初に WhatsApp ユーザーが WhatsApp ビジネス アカウントにメッセージを送信する必要があります。 詳細については、「ビジネス ユーザーと WhatsApp ユーザーの間のメッセージ送信開始」を参照してください。

WhatsApp メディア メッセージを送信するときに使用する media_uri の例。

input_media_uri: str = "##VideoLinkPlaceholder##"

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

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

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

send_text_message() を実行するには、Main メソッドを更新します。

    # Calling send_image_message()
    messages.send_image_message()

コードの実行

コードを実行するには、messages-quickstart.py ファイルがあるディレクトリにいることを確認します。

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

完全なサンプル コード

Note

サンプル コード内のすべてのプレースホルダー変数を実際の値に置き換えます。

import os

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

その他のサンプル

Python Messages SDK の他のサンプル コードは、GitHubで確認およびダウンロードできます。

次のステップ

この記事では、WhatsApp SDK の高度なメッセージングについて説明しました。 詳細については、次の記事をご覧ください。