Files
kr_1/TelegramNotifier.java
2026-05-23 15:11:39 +00:00

52 lines
1.8 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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();
}
}
}