Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Sending SMS Messages Through Slack With Java and Routee

DZone's Guide to

Sending SMS Messages Through Slack With Java and Routee

Want to send SMS messages without reaching for your phone? Here's how you can set up a simple Java app for Slack to handle it for you.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

Using Slack for your communication is easy and reliable. Wouldn’t you like to be able to send SMS too, without having to use your phone?

Follow this simple guide to maximize your Slack account’s potential.

Firstly, you will need:

  • Any text editor or IDE of your choice.
  • An internet hosting service that allows you to upload the simple application you are going to build.

Step 1: Routee Setup

To get started:

  • Go to www.routee.net and click on the “START A FREE TRIAL” button.
  • Choose the “Developer’s Platform” and fill in the form to proceed.
  • Click “Register” and log into your email account to confirm your Routee account.

Step 2: Slack Setup

As for Slack:

  • Register your team on Slack:
    • Head to www.slack.com and click on “Create Workspace” at the top right corner of the page, then enter your email address and click “Next”. After that, enter the confirmation code sent to your email.
    • On the next page, fill in your personal details and click on the “Continue to password” button; enter your password to proceed.
    • On the next page, fill in your organization’s information and click “Continue to Company Name” button. Fill in the text field that appears.
    • Click on “Continue to Team URL”, and once you enter the address you will use with your team, click “Create Team”. Your team is now created.
    • Finally, you can choose teammates to invite — or you can do this later.
  • Set up your Slack app:
    • Go to Slack’s API page (www.api.slack.com) and click on “Building Slack apps” button under the “Start here” menu in the middle of the page.
    • Click on the green “Create a Slack app” button and enter your app details.
    • Choose the team you want to use this app and click “Create App”.
  • Set up the Slack command:
    • Under the “features” section in your Slack app menu, you will find the “Slash Commands” button. Click on it and then click on “Create New Command” button and fill in the form with the following data:
      • for “Command”: “/SMS”
      • for “Request URL”: add the address of the already uploaded handler
      • for “Short Description”: write something describing what the command will do
      • for “Usage hint” : should be “+359899000000 <Message> <text>”
    • Now you only have to click on the “Save” button and your command is ready to be used.
//Java

//Set up your config

private String slackVerificationToken = "your-slack-verification-token";
private String slackCommandInputRegex = "^(\\+[0-9]{12})\\s(.*)$"; // expression used to separate phone number and actual text message

private String routeeAppId = "your-routee-application-id";
private String routeeAppSecret = "your-routee-application-secret";

// Get authenticated through Routee's API

private String routeeAuthenticate(String routeeAppId, String routeeAppSecret) throws MalformedURLException, IOException {

    Base64.Encoder encoder = Base64.getEncoder();
    String authString = routeeAppId + ":" + routeeAppSecret;
    String token = encoder.encodeToString(authString.getBytes());
    String accessToken = "";

    URL url = new URL("https://auth.routee.net/oauth/token");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", "Basic " + token);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    connection.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
    wr.writeBytes("grant_type=client_credentials");
    wr.close();

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    try {
        JSONParser parser = new JSONParser();
        JSONObject jsonObject = (JSONObject)parser.parse(response.toString());
        accessToken = (String) jsonObject.get("access_token");
    } catch (Exception e) {
        e.printStackTrace();
    }

    return accessToken;
}

// Send the SMS message

private boolean sendSmsMessage(String authToken, String message, String sender, String receiver) throws MalformedURLException, IOException {

    URL url = new URL("https://connect.routee.net/sms");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    String requestBody = "{\"body\":\"" + message + "\", \"to\":\"" + receiver + "\", \"from\":\"" + sender + "\"}";

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", "Bearer " + authToken);
    connection.setRequestProperty("Content-Type", "application/json");

    if (sender.length() > 11) {
        sender = sender.substring(0,11);
    }

    connection.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
    wr.writeBytes(requestBody);
    wr.close();

    int responseCode = connection.getResponseCode();

    return responseCode == 200;
}

// Perform HTTP request validation and returning a proper message to Slack's user

private void sendSlackResponse(String message, String channelId, String slackResponseUrl) throws MalformedURLException, IOException {

    URL url = new URL(slackResponseUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    String requestBody = "{\"channel\":\"" + channelId + "\", \"text\":\"" + message + "\"}";
    String requestBodyLength = Integer.toString(requestBody.length());

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Length", "" + requestBodyLength + "");
    connection.setRequestProperty("Content-Type", "application/json");

    connection.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
    wr.writeBytes(requestBody);
    wr.close();
}


// validate request token
if (slackVerificationToken.equals(token)) { 
    String slackResponseMessage = "";

    Pattern pattern = Pattern.compile(slackCommandInputRegex);
    Matcher matcher = pattern.matcher(commandText);

    // validate command syntax
    if (matcher.matches()) { 
        String receiver = matcher.group(1);
        String message = matcher.group(2);
        String authToken = this.routeeAuthenticate(routeeAppId, routeeAppSecret);
        boolean success = this.sendSmsMessage(authToken, message, userName, receiver);

        if (success) {
            slackResponseMessage = "Message successfully send to " + receiver;
        } else {
            slackResponseMessage = "Sms message can't be send!";
        }
    } else {
        slackResponseMessage = "Wrong command format! The correct one is - /sms +359899000000 Message text";
    }

    String channelId = request.getParameter("channel_id");
    String responseUrl = request.getParameter("response_url");

    this.sendSlackResponse(slackResponseMessage, channelId, responseUrl);
}


Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
java ,slack app ,java sms ,routee ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}