Replace MyTelegramBot.java

parent 3d36336d
import com.google.gson.Gson; import org.json.JSONArray;
import org.json.JSONObject;
import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.TelegramBotsApi; import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession; import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;
import java.util.HashMap; import java.util.ArrayList;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set;
public class MyTelegramBot extends TelegramLongPollingBot { public class MyTelegramBot extends TelegramLongPollingBot {
private Map<Long, Boolean> firstMessages = new HashMap<>(); private List<String> docTypesList = new ArrayList<>();
private Set<Long> processedChatIds = new HashSet<>();
@Override @Override
public void onUpdateReceived(Update update) { public void onUpdateReceived(Update update) {
if (update.hasMessage() && update.getMessage().hasText()) { if (update.hasCallbackQuery()) {
Message message = update.getMessage(); handleCallbackQuery(update.getCallbackQuery());
Long chatId = message.getChatId(); } else if (update.hasMessage() && update.getMessage().hasText()) {
handleMessage(update.getMessage());
// Print the chat ID only once }
System.out.println("New Chat_Id: " + chatId); }
String text = message.getText().trim().toLowerCase(); private void handleCallbackQuery(CallbackQuery callbackQuery) {
String selectedOption = callbackQuery.getData();
Long chatId = callbackQuery.getMessage().getChatId();
// Respond to the user's message
SendMessage response = new SendMessage(); SendMessage response = new SendMessage();
response.setChatId(chatId.toString()); response.setChatId(chatId.toString());
response.setText("Option selected: " + selectedOption);
if (text.equals("send table")) {
// Check if the table has already been sent to this chat ID
if (processedChatIds.contains(chatId)) {
// If the table has already been sent, do not send it again
response.setText("Table has already been sent to this chat.");
} else {
// Example JSON data string
String jsonData = "{\n" +
" \"data\": [\n" +
" {\"Intents\": \"Area Sales\", \"Invocation\": \"Customer outstanding\"},\n" +
" {\"Intents\": \"Current GL balance of an account\", \"Invocation\": \"What is the outstanding for customer\"},\n" +
" {\"Intents\": \"Customer Sales\", \"Invocation\": \"Show Customer Sales\"},\n" +
" {\"Intents\": \"Division Sale\", \"Invocation\": \"Show Division Sales\"}\n" +
" ]\n" +
"}";
// Format JSON data into tabular form
SendMessage tabularResponse = formatJsonToTable(jsonData);
try { try {
execute(tabularResponse); execute(response);
// Add the chat ID to the set of processed chat IDs
processedChatIds.add(chatId);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
e.printStackTrace(); e.printStackTrace();
} }
return; // Exit the method to prevent sending duplicate responses
} }
} else {
response.setText("You say: " + text);
private void handleMessage(Message message) {
// Check if the message was sent by the bot itself
if (message.getFrom().getUserName().equals(getBotUsername())) {
return;
}
Long chatId = message.getChatId();
System.out.println("New chatId --" + chatId);
String text = message.getText();
if ("give option".equalsIgnoreCase(text)) {
sendInlineOptions(chatId);
}
}
private void sendInlineOptions(Long chatId) {
// Parse the JSON string and extract docType values
String json = "{\"docTypes\":[{\"minAttachmentRequired\":0,\"docType\":\"Invoice\",\"attached\":0,\"contentType\":[\"PDF\",\"IMAGE\"],\"maxAttachmentAllowed\":0},{\"minAttachmentRequired\":0,\"docType\":\"UPLOAD FORMATS\",\"attached\":0,\"contentType\":[\"MS_EXCEL\",\"MS_WORD\"],\"maxAttachmentAllowed\":0},{\"minAttachmentRequired\":0,\"docType\":\"HR Policy\",\"attached\":1,\"contentType\":[\"PDF\",\"IMAGE\",\"VIDEO\",\"ZIP\",\"MS_EXCEL\",\"MS_WORD\"],\"maxAttachmentAllowed\":0},{\"minAttachmentRequired\":0,\"docType\":\"Presentation\",\"attached\":2,\"contentType\":[\"IMAGE\",\"VIDEO\",\"ZIP\",\"AR_OBJECT\"],\"maxAttachmentAllowed\":0},{\"minAttachmentRequired\":0,\"docType\":\"Literature\",\"attached\":0,\"contentType\":[\"PDF\"],\"maxAttachmentAllowed\":1},{\"minAttachmentRequired\":0,\"docType\":\"Product Demo\",\"attached\":0,\"contentType\":[\"VIDEO\",\"ZIP\"],\"maxAttachmentAllowed\":1},{\"minAttachmentRequired\":0,\"docType\":\"Product Manual\",\"attached\":0,\"contentType\":[\"PDF\"],\"maxAttachmentAllowed\":4}],\"objName\":\"content_library\"}";
JSONObject jsonObject = new JSONObject(json);
JSONArray docTypesArray = jsonObject.getJSONArray("docTypes");
// Extract docType values and add to ArrayList
for (int i = 0; i < docTypesArray.length(); i++) {
JSONObject docTypeObject = docTypesArray.getJSONObject(i);
String docType = docTypeObject.getString("docType");
docTypesList.add(docType);
}
// Create inline keyboard with docType options
SendMessage optionsMessage = new SendMessage();
optionsMessage.setChatId(chatId.toString());
optionsMessage.setText("Please select a document type:");
List<List<InlineKeyboardButton>> rowsInline = new ArrayList<>();
List<InlineKeyboardButton> currentRow = new ArrayList<>();
for (String docType : docTypesList) {
if (currentRow.size() == 2) {
rowsInline.add(currentRow);
currentRow = new ArrayList<>();
}
currentRow.add(createInlineButton(docType));
}
// Add the last row if it's not empty
if (!currentRow.isEmpty()) {
rowsInline.add(currentRow);
} }
// Send the response // Set the keyboard
InlineKeyboardMarkup markupInline = new InlineKeyboardMarkup();
markupInline.setKeyboard(rowsInline);
optionsMessage.setReplyMarkup(markupInline); // Set inline keyboard markup
// Send the message
try { try {
execute(response); execute(optionsMessage);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
private InlineKeyboardButton createInlineButton(String text) {
InlineKeyboardButton button = new InlineKeyboardButton();
button.setText(text);
button.setCallbackData(text); // Set callback data to the option text
return button;
} }
@Override @Override
...@@ -92,64 +130,4 @@ public class MyTelegramBot extends TelegramLongPollingBot { ...@@ -92,64 +130,4 @@ public class MyTelegramBot extends TelegramLongPollingBot {
e.printStackTrace(); e.printStackTrace();
} }
} }
// Format JSON data into tabular form
public SendMessage formatJsonToTable(String jsonData) {
SendMessage response = new SendMessage();
response.setParseMode("HTML");
// Parse JSON string into Java objects
Gson gson = new Gson();
Data data = gson.fromJson(jsonData, Data.class);
// Format data into a tabular structure
StringBuilder table = new StringBuilder();
table.append("<b>Table:</b>\n\n");
table.append("<pre>");
table.append("Intents | Invocation\n");
table.append("--------|-------\n");
for (Row row : data.getData()) {
table.append(String.format("%-8s| %-6d\n", row.getName(), row.getNumber()));
}
table.append("</pre>");
// Set the tabular data as the message text
response.setText(table.toString());
return response;
}
// Define classes to represent JSON data
static class Data {
private List<Row> data;
public List<Row> getData() {
return data;
}
public void setData(List<Row> data) {
this.data = data;
}
}
static class Row {
private String Name;
private int Number;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getNumber() {
return Number;
}
public void setNumber(int number) {
Number = number;
}
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment