画像メッセージを送る

このコード・スニペットでは、Messages APIを使ってFacebook Messengerから画像メッセージを送信する方法を学びます。

このトピックに関するステップバイステップのガイドについては、チュートリアルをお読みください。 Messages APIを使ったFacebook Messengerメッセージの送信.

各コード・スニペットで使用されているすべての変数の説明を以下に示します:

キー説明
VONAGE_APPLICATION_ID

The Vonage Application ID.

VONAGE_APPLICATION_PRIVATE_KEY_PATH

Private key path.

VONAGE_PRIVATE_KEY_PATH

Private key path.

BASE_URL

For production use the base URL is https://api.nexmo.com/. For sandbox testing the base URL is https://messages-sandbox.nexmo.com/.

MESSAGES_API_URL

There are two versions of the API, each with their own endpoints. For production the previous Messages API endpoint was https://api.nexmo.com/v0.1/messages, the new one is https://api.nexmo.com/v1/messages. For sandbox testing the Messages API endpoint is https://messages-sandbox.nexmo.com/v0.1/messages or https://messages-sandbox.nexmo.com/v1/messages, depending on which version you have set in the sandbox dashboard.

FB_SENDER_ID

Your Page ID. The FB_SENDER_ID is the same as the to.id value you received in the inbound messenger event on your Inbound Message Webhook URL. For sandbox testing this is 107083064136738.

VONAGE_FB_SENDER_ID

Refer to FB_SENDER_ID above

FROM_ID

Refer to FB_SENDER_ID above

FB_RECIPIENT_ID

The PSID of the user you want to reply to. The FB_RECIPIENT_ID is the PSID of the Facebook User you are messaging. This value is the from.id value you received in the inbound messenger event on your Inbound Message Webhook URL.

TO_ID

Refer to FB_RECIPIENT_ID above.

IMAGE_URL

The link to the image file to send. Messenger supports .jpg, .jpeg, .png and .gif types.

前提条件

申込書をお持ちでない場合は、ひとつ作るウェブフックの設定 もご確認ください。

コードを書く

send-image.sh に以下を追加する:

curl -X POST "${MESSAGES_API_URL}" \
  -H "Authorization: Bearer "$JWT\
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -d $'{
    "to": "'${MESSENGER_RECIPIENT_ID}'",
    "from": "'${MESSENGER_SENDER_ID}'",
    "channel": "messenger",
    "message_type": "image",
    "image": {
      "url": "'${MESSAGES_IMAGE_URL}'"
    }
  }'

全文を見る

コードを実行する

このファイルをあなたのマシンに保存し、実行する:

bash send-image.sh

前提条件

申込書をお持ちでない場合は、ひとつ作るウェブフックの設定 もご確認ください。

npm install @vonage/server-sdk @vonage/messages

send-image.js という名前のファイルを作成し、以下のコードを追加する:

const { Vonage } = require('@vonage/server-sdk');
const { Channels } = require('@vonage/messages');

/**
 * It is best to send messages using JWT instead of basic auth. If you leave out
 * apiKey and apiSecret, the messages SDK will send requests using JWT tokens
 *
 * @link https://developer.vonage.com/en/messages/technical-details#authentication
 */
const vonage = new Vonage(
  {
    applicationId: VONAGE_APPLICATION_ID,
    privateKey: VONAGE_PRIVATE_KEY,
  },
  {
    ...(MESSAGES_API_URL ? {apiHost: MESSAGES_API_URL} : {}),
  },
);

全文を見る

コードを書く

send-image.js に以下を追加する:

vonage.messages.send({
  messageType: 'image',
  channel: Channels.MESSENGER,
  image: {
    url: MESSAGES_IMAGE_URL,
  },
  to: MESSENGER_RECIPIENT_ID,
  from: MESSENGER_SENDER_ID,
})
  .then(({ messageUUID }) => console.log(messageUUID))
  .catch((error) => console.error(error));

全文を見る

コードを実行する

このファイルをあなたのマシンに保存し、実行する:

node send-image.js

前提条件

申込書をお持ちでない場合は、ひとつ作るウェブフックの設定 もご確認ください。

build.gradle に以下を追加する:

implementation 'com.vonage:server-sdk-kotlin:2.1.1'

SendMessengerImage という名前のファイルを作成し、main メソッドに以下のコードを追加する:

val client = Vonage {
    applicationId(VONAGE_APPLICATION_ID)
    privateKeyPath(VONAGE_PRIVATE_KEY_PATH)
}

全文を見る

コードを書く

SendMessengerImage ファイルのmain メソッドに以下を追加する:

val messageId = client.messages.send(
    messengerImage {
        to(MESSENGER_RECIPIENT_ID)
        from(MESSENGER_SENDER_ID)
        url(MESSAGES_IMAGE_URL)
    }
)

全文を見る

コードを実行する

Gradle用のアプリケーション プラグインを使うことで、アプリケーションの実行を簡単にすることができます。build.gradle を以下のように更新する:

apply plugin: 'application'
mainClassName = project.hasProperty('main') ? project.getProperty('main') : ''

以下のgradle コマンドを実行し、com.vonage.quickstart.kt.messages.messengerSendMessengerImage を含むパッケージに置き換えてアプリケーションを実行する:

gradle run -Pmain=com.vonage.quickstart.kt.messages.messenger.SendMessengerImage

前提条件

申込書をお持ちでない場合は、ひとつ作るウェブフックの設定 もご確認ください。

build.gradle に以下を追加する:

implementation 'com.vonage:server-sdk:9.3.1'

SendMessengerImage という名前のファイルを作成し、main メソッドに以下のコードを追加する:

VonageClient client = VonageClient.builder()
		.applicationId(VONAGE_APPLICATION_ID)
		.privateKeyPath(VONAGE_PRIVATE_KEY_PATH)
		.build();

全文を見る

コードを書く

SendMessengerImage ファイルのmain メソッドに以下を追加する:

var response = client.getMessagesClient().sendMessage(
		MessengerImageRequest.builder()
			.from(MESSENGER_SENDER_ID)
			.to(MESSENGER_RECIPIENT_ID)
			.url(MESSAGES_IMAGE_URL)
			.build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

全文を見る

コードを実行する

Gradle用のアプリケーション プラグインを使うことで、アプリケーションの実行を簡単にすることができます。build.gradle を以下のように更新する:

apply plugin: 'application'
mainClassName = project.hasProperty('main') ? project.getProperty('main') : ''

以下のgradle コマンドを実行し、com.vonage.quickstart.messages.messengerSendMessengerImage を含むパッケージに置き換えてアプリケーションを実行する:

gradle run -Pmain=com.vonage.quickstart.messages.messenger.SendMessengerImage

前提条件

申込書をお持ちでない場合は、ひとつ作るウェブフックの設定 もご確認ください。

Install-Package Vonage

コードを書く

SendMessengerImage.cs に以下を追加する:

var credentials = Credentials.FromAppIdAndPrivateKeyPath(VONAGE_APPLICATION_ID, VONAGE_PRIVATE_KEY_PATH);
var vonageClient = new VonageClient(credentials);
var request = new MessengerImageRequest
{
    To = MESSENGER_RECIPIENT_ID,
    From = MESSENGER_SENDER_ID,
    Image = new Attachment
    {
        Url = MESSAGES_IMAGE_URL
    }
};
var response = await vonageClient.MessagesClient.SendAsync(request);

全文を見る

前提条件

申込書をお持ちでない場合は、ひとつ作るウェブフックの設定 もご確認ください。

composer require vonage/client

send-image.php という名前のファイルを作成し、以下のコードを追加する:

$keypair = new \Vonage\Client\Credentials\Keypair(
    file_get_contents(VONAGE_APPLICATION_PRIVATE_KEY_PATH),
    VONAGE_APPLICATION_ID
);

$client = new \Vonage\Client($keypair);

全文を見る

コードを書く

send-image.php に以下を追加する:

$imageObject = new \Vonage\Messages\MessageObjects\ImageObject(
    'https://example.com/image.jpg',
    'This is an image'
);

$message = new \Vonage\Messages\Channel\Messenger\MessengerImage(
    TO_NUMBER,
    FROM_NUMBER,
    $imageObject
);

$client->messages()->send($message);

全文を見る

コードを実行する

このファイルをあなたのマシンに保存し、実行する:

php send-image.php

前提条件

申込書をお持ちでない場合は、ひとつ作るウェブフックの設定 もご確認ください。

pip install vonage python-dotenv

コードを書く

send-image.py に以下を追加する:

from vonage import Auth, Vonage
from vonage_messages import MessengerImage, MessengerResource

client = Vonage(
    Auth(
        application_id=VONAGE_APPLICATION_ID,
        private_key=VONAGE_PRIVATE_KEY,
    )
)

message = MessengerImage(
    to=MESSENGER_RECIPIENT_ID,
    from_=MESSENGER_SENDER_ID,
    image=MessengerResource(url=MESSAGES_IMAGE_URL),
)

response = client.messages.send(message)
print(response)

全文を見る

コードを実行する

このファイルをあなたのマシンに保存し、実行する:

python messages/messenger/send-image.py

前提条件

申込書をお持ちでない場合は、ひとつ作るウェブフックの設定 もご確認ください。

gem install vonage

send-image.rb という名前のファイルを作成し、以下のコードを追加する:

client = Vonage::Client.new(
  application_id: VONAGE_APPLICATION_ID,
  private_key: VONAGE_PRIVATE_KEY
)

全文を見る

コードを書く

send-image.rb に以下を追加する:

message = client.messaging.messenger(
  type: 'image',
  message: {
    url: MESSAGES_IMAGE_URL
  }
)

client.messaging.send(
  from: MESSENGER_SENDER_ID,
  to: MESSENGER_RECIPIENT_ID,
  **message
)

全文を見る

コードを実行する

このファイルをあなたのマシンに保存し、実行する:

ruby send-image.rb

試してみる

コードを実行すると、メッセンジャーの受信者に画像メッセージが送信されます。