Sending plain text messages via Knit Communication APIs

This guide will help you send text messages on Slack/MS Teams using Knit APIs.

Before we start, do loot at:

👍

Prerequisites

  • You should have Slack/Teams integration id.

1. Sending a text message to an employee

If you want to send message to message to an employee you need channel id for that employee. This can be easily retrieved using employee email via Get DM Id From Email.

import com.fasterxml.jackson.*
import okhttp3.*;
import java.util.*;

public class SendMessage {

    private static final ObjectMapper mapper = new ObjectMapper();
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    
    public static String getDirectMessageId(String email) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.getknit.dev/v1.0/comm.dm.get")
                .addHeader("Authorization", "Bearer " + "API_KEY")
                .addHeader("X-Knit-Integration-Id", "Integration Id")
                .build();

        Response response = client.newCall(request).execute();
        JsonNode jsonNode = mapper.readTree(response.body().string());
        if (!jsonNode.get("success").asBoolean()) {
            // Handle Error
        }

        return jsonNode.at("/data/channelId").asText();
    }

    public static void sendHelloMessage(String email) {
        String channelId = getDirectMessageId(email);
        OkHttpClient client = new OkHttpClient();
      
        Map<String, Object> map = new HashMap<>();
        map.put("message", "Hello ! from Knit");
        map.put("channelId", channelId);
        map.put("channelType", "dm");

        String body = toJson(map); // convert to json
        Request request = new Request.Builder()
                .url("https://api.getknit.dev/v1.0/comm.msg.send")
                .addHeader("Authorization", "Bearer " + "API_KEY")
                .addHeader("X-Knit-Integration-Id", "Integration Id")
                .post(RequestBody.create(body, JSON))
                .build();


        Response response = client.newCall(request).execute();
        JsonNode jsonNode = mapper.readTree(response.body().string());
        String messageId = jsonNode.at("/data/messageId").asText();
        // This message Id can  be used for further updating message

    }

}

2. Sending text messages to all employees

In case you want to send messages to a bunch of employees , then you need to fetch their direct message ids using List Direct Message Ids.

🚧

Store channel/DM IDs in your database.

Knit doesn't store any of your user's data including channel and DM IDs. Thus, store these IDs in your DB and resuse them for messaging.

import com.fasterxml.jackson.*
import okhttp3.*;
import java.util.*;

public class SendMessage {

   private static final ObjectMapper mapper = new ObjectMapper();
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public static void sendDirectMessageToAllEmployees() throws IOException {
        String pageToken = null;
        List<Map<String, String>>dmList = new ArrayList<>();
        // Fetch All Users DM Ids
        while (true) {
            String url = "https://api.getknit.dev/v1.0/comm.dm.list";
            if (pageToken != null) url += "&pageToken=" + pageToken;
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Authorization", "Bearer " + "API_KEY")
                    .addHeader("X-Knit-Integration-Id", "Integration Id")
                    .build();
            Response response = client.newCall(request).execute();
            JsonNode jsonNode = mapper.readTree(response.body().string());
            JsonNode dataNode = jsonNode.with("data");
            for (JsonNode node : dataNode.withArray("members")) {
                dmList.add(Map.of("email", node.get("email").asText(), "id", node.get("id").asText()));
            }

            JsonNode pageTokenNode = jsonNode.get("nextPageToken");
            if (pageTokenNode != null) pageToken = pageTokenNode.asText();
            else break;
        }
        
        // Send Message
        dmList.forEach(user -> {
            String id = user.get("id");
            sendHelloMessage(id);
        });
        
    }

    public static void sendHelloMessage(String channelId) {
        OkHttpClient client = new OkHttpClient();
        Map<String, Object> map = new HashMap<>();
        map.put("message", "Hello ! from Knit");
        map.put("channelId", channelId);
        map.put("channelType", "dm");

        String body = toJson(map); // convert to json
        Request request = new Request.Builder()
                .url("https://api.getknit.dev/v1.0/comm.msg.send")
                .addHeader("Authorization", "Bearer " + "API_KEY")
                .addHeader("X-Knit-Integration-Id", "Integration Id")
                .post(RequestBody.create(body, JSON))
                .build();
        Response response = client.newCall(request).execute();
        JsonNode jsonNode = mapper.readTree(response.body().string());
        String messageId = jsonNode.at("/data/messageId").asText();
        // This message Id can  be used for further updating message

    }

}

3. Sending text messages to a channel

If you want to send message to a channel then you can use List Channels API. This will contain channel ID along with channel name. If you know the channel name already then get it's channel ID to send a message on the channel.

👍

Ask your users for channel preference and store it in DB.

Ask your user for channel preference during onboarding and then save the channel name and ID in DB. Use these details to send notifications/nudges to the user selected channel.

import com.fasterxml.jackson.*
import okhttp3.*;
import java.util.*;

public class SendMessage {

  private static final ObjectMapper mapper = new ObjectMapper();
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public static void sendMessageInChannel(String channelName) throws IOException {
        String pageToken = null;
        List<Map<String, String>>channelsList = new ArrayList<>();
        // Fetch All channels ids
        while (true) {
            String url = "https://api.getknit.dev/v1/comm.channels.list";
            if (pageToken != null) url += "&pageToken=" + pageToken;
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Authorization", "Bearer " + "API_KEY")
                    .addHeader("X-Knit-Integration-Id", "Integration Id")
                    .build();
            Response response = client.newCall(request).execute();
            JsonNode jsonNode = mapper.readTree(response.body().string());
            JsonNode dataNode = jsonNode.with("data");
            for (JsonNode node : dataNode.withArray("channels")) {
                channelsList.add(Map.of("name", node.get("name").asText(), "id", node.get("id").asText()));
            }

            JsonNode pageTokenNode = jsonNode.get("nextPageToken");
            if (pageTokenNode != null) pageToken = pageTokenNode.asText();
            else break;
        }

        // Filter channel based on name
        channelsList.forEach(channel ->{
            if (channel.get("name").equals(channelName))  sendHelloMessage(channel.get("id"));
        });


    }

    public static void sendHelloMessage(String channelId) {
        OkHttpClient client = new OkHttpClient();
        Map<String, Object> map = new HashMap<>();
        map.put("message", "Hello ! from Knit");
        map.put("channelId", channelId);
        map.put("channelType", "dm");

        String body = toJson(map); // convert to json
        Request request = new Request.Builder()
                .url("https://api.getknit.dev/v1.0/comm.msg.send")
                .addHeader("Authorization", "Bearer " + "API_KEY")
                .addHeader("X-Knit-Integration-Id", "Integration Id")
                .post(RequestBody.create(body, JSON))
                .build();


        Response response = client.newCall(request).execute();
        JsonNode jsonNode = mapper.readTree(response.body().string());
        String messageId = jsonNode.at("/data/messageId").asText();
        // This message Id can  be used for further updating message

    }

}

🚧

Private channels information is limited.

For Slack, we can list a private channel ID only if Bot is member of channel.

For Teams, Bot can not access any info about private channels.