Welcome to Hackster!
Hackster is a community dedicated to learning hardware, from beginner to pro. Join us, it's free!
AMD Telecom
Published

SMS Slack Command With Routee

Make your life easier by sending SMS with Jave and Routee, while on Slack.

IntermediateProtip30 minutes559
SMS Slack Command With Routee

Things used in this project

Software apps and online services

Slack
Slack
Routee

Story

Read more

Code

Slack Routee integration

Java
### 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);
}

Credits

AMD Telecom
1 project • 0 followers
Contact

Comments

Please log in or sign up to comment.