Trouble with custom keyboard in messaging API

I’m having issues with a messaging API. I want to show a custom keyboard to the message recipient. But my code isn’t working right when I add the reply_markup parameter to the JSON string.

Here’s a simplified version of what I’m trying to do:

String apiEndpoint = "https://messaging-api.example.com/send";
String payload = "{\"recipient\":12345,\"message\":\"Hello\",\"keyboard\":{\"buttons\":[[\"A\",\"B\"],[\"C\",\"D\"]],\"temporary\":true}}";

URL url = new URL(apiEndpoint);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);

OutputStream stream = connection.getOutputStream();
stream.write(payload.getBytes());
stream.flush();

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = reader.readLine();

reader.close();
connection.disconnect();

I think the problem might be how I’m formatting the keyboard part in the JSON. Any ideas on what I’m doing wrong or how to fix this?

hey nova56, ur json is off. try this:

{"message":"Hello","recipient":12345,"reply_markup":{"keyboard":[["A","B"],["C","D"]],"one_time_keyboard":true}}

the reply_markup must be seperate. hope it helps.

I encountered a similar issue when working with custom keyboards in messaging APIs. The key is to structure your JSON payload correctly. Here’s a suggestion:

Use a JSON library like Gson or Jackson to create your payload. This approach helps avoid manual string formatting errors and ensures proper JSON structure.

For example, with Gson:

JsonObject payload = new JsonObject();
payload.addProperty("recipient", 12345);
payload.addProperty("message", "Hello");

JsonObject replyMarkup = new JsonObject();
JsonArray keyboard = new JsonArray();
// Add your keyboard buttons here
replyMarkup.add("keyboard", keyboard);
replyMarkup.addProperty("one_time_keyboard", true);

payload.add("reply_markup", replyMarkup);

String jsonPayload = new Gson().toJson(payload);

This method is more robust and less error-prone than manual JSON string construction.

I’ve run into similar issues with custom keyboards before. The JSON structure for reply_markup can be tricky. Here’s what worked for me:

Make sure you’re using “reply_markup” as the key, not just “keyboard”. Also, for temporary keyboards, use “one_time_keyboard” instead of “temporary”.

Your payload should look something like this:

String payload = “{"recipient":12345,"message":"Hello","reply_markup":{"keyboard":[["A","B"],["C","D"]],"one_time_keyboard":true}}”;

Remember to escape those quotes properly. That should resolve your issue. Let me know if you need any more help!