import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; public class TelegramNotifier { private static String botToken; private static String chatId; /** * Инициализация бота один раз в начале программы */ public static void init(String token, String chatId) { TelegramNotifier.botToken = token; TelegramNotifier.chatId = chatId; } /** * Отправка сообщения в Telegram */ public static void sendMessage(String text) { if (botToken == null || chatId == null || botToken.isEmpty() || chatId.isEmpty()) { return; // если не настроено — тихо пропускаем } try { String encodedText = URLEncoder.encode(text, StandardCharsets.UTF_8); String urlString = "https://api.telegram.org/bot" + botToken + "/sendMessage?chat_id=" + chatId + "&text=" + encodedText + "&parse_mode=HTML"; URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); int responseCode = conn.getResponseCode(); if (responseCode != 200) { System.err.println("Ошибка Telegram API: " + responseCode); } } catch (Exception e) { System.err.println("Не удалось отправить сообщение в Telegram:"); e.printStackTrace(); } } }