Enviar uma mensagem com imagem

Neste trecho de código, você aprenderá a enviar uma mensagem com imagem pelo Facebook Messenger usando a Messages API.

Para obter um guia passo a passo sobre esse assunto, você pode ler nosso tutorial Envio de mensagens pelo Facebook Messenger com a Messages API.

Exemplo

Veja a seguir a descrição de todas as variáveis utilizadas em cada trecho de código:

ChaveDescrição
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.

Pré-requisitos

Se você não tiver um aplicativo, acesse criar um. Certifique-se também de acessar configure seus webhooks.

Escreva o código

Adicione o seguinte ao arquivo ` 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}'"
    }
  }'

Ver código-fonte completo

Execute seu código

Salve este arquivo no seu computador e execute-o:

bash send-image.sh

Pré-requisitos

Se você não tiver um aplicativo, acesse criar um. Certifique-se também de acessar configure seus webhooks.

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

Crie um arquivo chamado ` send-image.js ` e insira o seguinte código:

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} : {}),
  },
);

Ver código-fonte completo

Escreva o código

Adicione o seguinte ao arquivo ` 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));

Ver código-fonte completo

Execute seu código

Salve este arquivo no seu computador e execute-o:

node send-image.js

Pré-requisitos

Se você não tiver um aplicativo, acesse criar um. Certifique-se também de acessar configure seus webhooks.

Adicione o seguinte ao arquivo ` build.gradle`:

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

Crie um arquivo chamado ` SendMessengerImage ` e adicione o código a seguir ao método ` main `:

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

Ver código-fonte completo

Escreva o código

Adicione o seguinte ao método ` main ` do arquivo ` SendMessengerImage `:

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

Ver código-fonte completo

Execute seu código

Podemos usar o plugin “ aplicativo ” para o Gradle a fim de simplificar a execução do nosso aplicativo. Atualize seu arquivo ` build.gradle ` com o seguinte:

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

Execute o seguinte comando ` gradle ` para rodar seu aplicativo, substituindo ` com.vonage.quickstart.kt.messages.messenger ` pelo pacote que contém ` SendMessengerImage`:

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

Pré-requisitos

Se você não tiver um aplicativo, acesse criar um. Certifique-se também de acessar configure seus webhooks.

Adicione o seguinte ao arquivo ` build.gradle`:

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

Crie um arquivo chamado ` SendMessengerImage ` e adicione o código a seguir ao método ` main `:

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

Ver código-fonte completo

Escreva o código

Adicione o seguinte ao método ` main ` do arquivo ` SendMessengerImage `:

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());

Ver código-fonte completo

Execute seu código

Podemos usar o plugin “ aplicativo ” para o Gradle a fim de simplificar a execução do nosso aplicativo. Atualize seu arquivo ` build.gradle ` com o seguinte:

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

Execute o seguinte comando ` gradle ` para rodar seu aplicativo, substituindo ` com.vonage.quickstart.messages.messenger ` pelo pacote que contém ` SendMessengerImage`:

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

Pré-requisitos

Se você não tiver um aplicativo, acesse criar um. Certifique-se também de acessar configure seus webhooks.

Install-Package Vonage

Escreva o código

Adicione o seguinte ao arquivo ` 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);

Ver código-fonte completo

Pré-requisitos

Se você não tiver um aplicativo, acesse criar um. Certifique-se também de acessar configure seus webhooks.

composer require vonage/client

Crie um arquivo chamado ` send-image.php ` e insira o seguinte código:

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

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

Ver código-fonte completo

Escreva o código

Adicione o seguinte ao arquivo ` 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);

Ver código-fonte completo

Execute seu código

Salve este arquivo no seu computador e execute-o:

php send-image.php

Pré-requisitos

Se você não tiver um aplicativo, acesse criar um. Certifique-se também de acessar configure seus webhooks.

pip install vonage python-dotenv

Escreva o código

Adicione o seguinte ao arquivo ` 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)

Ver código-fonte completo

Execute seu código

Salve este arquivo no seu computador e execute-o:

python messages/messenger/send-image.py

Pré-requisitos

Se você não tiver um aplicativo, acesse criar um. Certifique-se também de acessar configure seus webhooks.

gem install vonage

Crie um arquivo chamado ` send-image.rb ` e insira o seguinte código:

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

Ver código-fonte completo

Escreva o código

Adicione o seguinte ao arquivo ` 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
)

Ver código-fonte completo

Execute seu código

Salve este arquivo no seu computador e execute-o:

ruby send-image.rb

Experimente

Ao executar o código, uma mensagem com imagem é enviada ao destinatário do Messenger.