Handle an incoming message

Note:

Before you can get started, you need the following already set up:

  • Set all Conversation API configuration settings.
  • JDK 8 or later and a familiarity with how to create a new Java application.
  • Gradle and a familiarity with how use the Gradle build tools.
  • ngrok. You'll use ngrok to open a tunnel to your local server.

Using the Conversation API, you can receive and respond to messages from any channel you have configured. This tutorial shows you how to set up a Java application that receives and responds to messages using the Java SDK.

Note:

This tutorial is easier to accomplish if you have already completed the steps for Sending a message.

Steps:
  1. Set up your Java application
  2. Configure your Conversation API webhook
  3. Test the application

Set up your Java application

  1. Create a new folder where you want your application project, then open a command prompt to that location.
  2. Create a new Java application using Gradle with the following command:
    Copy
    Copied
    gradle init

    In the prompts, select that you want to create an application, name your project and source package app, and then accept the defaults for the rest of the options.

Add the Sinch Java SDK and other dependencies

  1. In your project folder, navigate to the /app folder and open the build.gradle file.
  2. Replace all of the code in the file with the following code:
    Copy
    Copied
    plugins {
      id 'application'
      id 'org.springframework.boot' version '2.5.5'
      id 'io.spring.dependency-management' version '1.0.11.RELEASE'
      id 'java'
    }
    
    configurations {
      compileOnly {
        extendsFrom annotationProcessor
      }
    }
    
    repositories {
      mavenCentral()
    }
    
    dependencies {
      implementation 'org.springframework.boot:spring-boot-starter-web'
      implementation 'com.sinch.sdk:java-sdk:+'
      compileOnly 'org.projectlombok:lombok'
      annotationProcessor 'org.projectlombok:lombok'
      testImplementation 'org.springframework.boot:spring-boot-starter-test'
    }
    
    application {
      mainClass = 'app.App'
    }

    This adds the Sinch Java SDK, Spring, and Lombok to your project. You will use Spring to listen to incoming HTTP requests. Lombok is used to deserialize requests.

  3. Save and close the file.

Modify your application

  1. Open the App.java file in your project folder, located in \app\scr\main\java\app. Populate that file with the "App.java" code found on this page and save the file. This code starts a server that listens for incoming messages. It then sends a text message in response.
    Note:

    This sample application is configured for the US Region. If your Conversation API app wasn't created in the US region, you must change the Region.US parameter to Region.EU.

App.java

This code sample is to be used with the instructions on this page to build a web server that will handle and respond to incoming messages.

package app;

// Get your Access Key and Access Secret at dashboard.sinch.com/settings/access-keys

import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import com.sinch.sdk.Sinch;
import com.sinch.sdk.api.conversationapi.factory.RecipientFactory;
import com.sinch.sdk.api.conversationapi.model.request.message.TextMessageRequest;
import com.sinch.sdk.model.Region;
import com.sinch.sdk.model.conversationapi.ContactMessage;
import com.sinch.sdk.model.conversationapi.ConversationMessage;
import com.sinch.sdk.model.conversationapi.TextMessage;
import lombok.Builder;
import lombok.Value;
import lombok.extern.jackson.Jacksonized;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Optional;

@SpringBootApplication
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

	@Controller
	static class WebhookController {

		private static final String ACCESS_KEY = "";
		private static final String ACCESS_SECRET = "";

		@PostMapping
		@ResponseBody
		void webhook(@RequestBody WebhookDto payload) {
			Sinch.init(ACCESS_KEY, ACCESS_SECRET, payload.getProjectId());

			Sinch.conversationApi(Region.US)
					.messages(payload.getAppId())
					.send(new TextMessageRequest(
							"Reply from Conversation API and the Sinch Java SDK. You sent: " +
									Optional.ofNullable(payload.getMessage().getContactMessage())
											.map(ContactMessage::getTextMessage)
											.map(TextMessage::getText)
											.orElse("TextMessage body not found"))
							.recipient(RecipientFactory.fromContactId(payload.getMessage().getContactId())));
		}

		@Value
		@Builder
		@Jacksonized
		@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
		static class WebhookDto {
			String appId;
			String projectId;
			ConversationMessage message;
		}

	}

}
  1. Assign your values to the following parameters:
ParameterYour value
ACCESS_KEYFind your access key on your Sinch dashboard.
ACCESS_SECRETFind your access secret on your Sinch dashboard.
Note: Access secrets are only available during initial key creation.
  1. Save the file.

Start your web server and set up a tunnel

  1. In your project directory, start the server by executing the following command:
    Copy
    Copied
    gradle run

    By default, your web server is started on port 8080.

  2. Now you need to open a tunnel to the server you just set up. We are using ngrok for this. If you don't have ngrok installed already, install it with the following command:
    Copy
    Copied
    npm install ngrok -g
  3. Open a terminal or command prompt and enter:
    Copy
    Copied
    ngrok http 8080
  4. Copy the HTTPS address that ends with .ngrok.io.

Configure your webhook

For your application to receive messages from Conversation API, you must configure a webhook in your Conversation API app. For detailed instructions on configuring a webhook, click here.

  1. Set your webhook URL to the HTTP address you copied in the previous step.
  2. Assign the following triggers:
    • CONVERSATION_START
    • CONVERSATION_STOP
    • EVENT_DELIVERY
    • EVENT_INBOUND
    • MESSAGE_DELIVERY
    • MESSAGE_INBOUND
    • UNSUPPORTED

Test the application

Now that your server is running and your webhook is configured, you can test the application.

From your messaging platform, send your Conversation API app a message. You will receive a message back in response on the messaging platform.

Additional resources

Read the links below to learn more:

Was this page helpful?

App.java

This code sample is to be used with the instructions on this page to build a web server that will handle and respond to incoming messages.

package app;

// Get your Access Key and Access Secret at dashboard.sinch.com/settings/access-keys

import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import com.sinch.sdk.Sinch;
import com.sinch.sdk.api.conversationapi.factory.RecipientFactory;
import com.sinch.sdk.api.conversationapi.model.request.message.TextMessageRequest;
import com.sinch.sdk.model.Region;
import com.sinch.sdk.model.conversationapi.ContactMessage;
import com.sinch.sdk.model.conversationapi.ConversationMessage;
import com.sinch.sdk.model.conversationapi.TextMessage;
import lombok.Builder;
import lombok.Value;
import lombok.extern.jackson.Jacksonized;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Optional;

@SpringBootApplication
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

	@Controller
	static class WebhookController {

		private static final String ACCESS_KEY = "";
		private static final String ACCESS_SECRET = "";

		@PostMapping
		@ResponseBody
		void webhook(@RequestBody WebhookDto payload) {
			Sinch.init(ACCESS_KEY, ACCESS_SECRET, payload.getProjectId());

			Sinch.conversationApi(Region.US)
					.messages(payload.getAppId())
					.send(new TextMessageRequest(
							"Reply from Conversation API and the Sinch Java SDK. You sent: " +
									Optional.ofNullable(payload.getMessage().getContactMessage())
											.map(ContactMessage::getTextMessage)
											.map(TextMessage::getText)
											.orElse("TextMessage body not found"))
							.recipient(RecipientFactory.fromContactId(payload.getMessage().getContactId())));
		}

		@Value
		@Builder
		@Jacksonized
		@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
		static class WebhookDto {
			String appId;
			String projectId;
			ConversationMessage message;
		}

	}

}