Send a Text Message

In this code snippet you learn how to send a Facebook message using the Messages API.

For a step-by-step guide to this topic, you can read our tutorial Sending Facebook Messenger messages with the Messages API.

Example

Find the description for all variables used in each code snippet below:

Key Description
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.

Prerequisites

If you do not have an application you can create one. Make sure you also configure your webhooks.

Write the code

Add the following to send-text.sh:

curl -X POST $MESSAGES_API_URL \
     -H 'Authorization: Bearer '$JWT\
     -H 'Content-Type: application/json' \
     -H 'Accept: application/json' \
     -d $'{
  "message_type": "text",
  "text": "This is a Facebook Messenger Message sent from the Messages API",
  "to": "$FB_RECIPIENT_ID",
  "from": "$FB_SENDER_ID",
  "channel": "messenger"
}'

View full source

Run your code

Save this file to your machine and run it:

bash send-text.sh

Prerequisites

If you do not have an application you can create one. Make sure you also configure your webhooks.

npm install @vonage/server-sdk

Create a file named send-text.js and add the following code:

const Vonage = require('@vonage/server-sdk');
const MessengerText = require('@vonage/server-sdk/lib/Messages/MessengerText');

const vonage = new Vonage(
    {
        apiKey: VONAGE_API_KEY,
        apiSecret: VONAGE_API_SECRET,
        applicationId: VONAGE_APPLICATION_ID,
        privateKey: VONAGE_APPLICATION_PRIVATE_KEY_PATH,
    },
    {
        apiHost: BASE_URL,
    }
);

View full source

Write the code

Add the following to send-text.js:

vonage.messages.send(
    new MessengerText(
        'This is a Facebook Messenger text message sent using the Messages API',
        FB_RECIPIENT_ID,
        FB_SENDER_ID
    ),
    (err, data) => {
        if (err) {
            console.error(err);
        } else {
            console.log(data.message_uuid);
        }
    }
);

View full source

Run your code

Save this file to your machine and run it:

node send-text.js

Prerequisites

If you do not have an application you can create one. Make sure you also configure your webhooks.

Add the following to `build.gradle`:

compile 'com.vonage:client:6.2.0'

Create a class named SendMessengerText and add the following code to the main method:

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

MessagesClient messagesClient = client.getMessagesClient();

View full source

Write the code

Add the following to the main method of the SendMessengerText class:

var message = MessengerTextRequest.builder()
        .from(FROM_ID).to(TO_ID)
        .text("Reminder of your event, which starts in 30 minutes.")
        .category(Category.MESSAGE_TAG)
        .tag(Tag.CONFIRMED_EVENT_UPDATE)
        .build();

try {
    MessageResponse response = messagesClient.sendMessage(message);
    System.out.println("Message sent successfully. ID: " + response.getMessageUuid());
}
catch (MessageResponseException mrx) {
    switch (mrx.getStatusCode()) {
        default: throw mrx;  
        case 401: // Bad credentials
            throw new IllegalStateException(mrx.getTitle(), mrx);
        case 422: // Invalid
            throw new IllegalStateException(mrx.getDetail(), mrx);
        case 402: // Low balance
            client.getAccountClient().topUp("transactionID");
            break;
        case 429: // Rate limit
            Thread.sleep(12_000);
            break;
    }
}

View full source

Run your code

We can use the application plugin for Gradle to simplify the running of our application. Update your build.gradle with the following:

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

Run the following gradle command to execute your application, replacing com.vonage.quickstart.messages.messenger with the package containing SendMessengerText:

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

Prerequisites

If you do not have an application you can create one. Make sure you also configure your webhooks.

Install-Package Vonage

Write the code

Add the following to SendMessengerText.cs:

var credentials = Credentials.FromApiKeyAndSecret(
    apiKey,
    apiSecret
);

var vonageClient = new VonageClient(credentials);

var request = new MessengerTextRequest
{
    To = to,
    From = brandName,
    Text = "This is a Facebook Messenger Message sent from the Messages API"
};

var response = await vonageClient.MessagesClient.SendAsync(request);

View full source

Prerequisites

If you do not have an application you can create one. Make sure you also configure your webhooks.

pip install vonage

Write the code

Add the following to send_text.py:

client = vonage.Client(
    application_id=VONAGE_APPLICATION_ID,
    private_key=VONAGE_APPLICATION_PRIVATE_KEY_PATH,
)

client.messages.send_message(
    {
        "channel": "messenger",
        "message_type": "text",
        "to": FB_RECIPIENT_ID,
        "from": VONAGE_FB_SENDER_ID,
        "text": "This is a Facebook Messenger text message sent using the Vonage Messages API",
    }
)

View full source

Run your code

Save this file to your machine and run it:

python3 send_text.py

Prerequisites

If you do not have an application you can create one. Make sure you also configure your webhooks.

gem install vonage

Write the code

Add the following to send-text.rb:

client = Vonage::Client.new(
  application_id: VONAGE_APPLICATION_ID,
  private_key: File.read(VONAGE_APPLICATION_PRIVATE_KEY_PATH)
)

message = Vonage::Messaging::Message.messenger(
  type: 'text',
  message: "This is a Facebook Messenger text message sent using the Messages API"
)

client.messaging.send(
  from: VONAGE_FB_SENDER_ID,
  to: FB_RECIPIENT_ID,
  **message
)

View full source

Run your code

Save this file to your machine and run it:

ruby send-text.rb

Try it out

When you run the code a Facebook message is sent to the recipient.