Files
kr_1/TelegramNotifier.java
2026-05-31 13:36:33 +05:00

45 lines
1.5 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 bot_token;
private static String chat_id;
public static void init(String token, String chatId) {
TelegramNotifier.bot_token = token;
TelegramNotifier.chat_id = chatId;
}
public static void sendMessage(String text) {
if (bot_token == null || chat_id == null || bot_token.isEmpty() || chat_id.isEmpty()) {
return;
}
try {
String encoded_text = URLEncoder.encode(text, StandardCharsets.UTF_8);
String url_string = "https://api.telegram.org/bot" + bot_token +
"/sendMessage?chat_id=" + chat_id +
"&text=" + encoded_text +
"&parse_mode=HTML";
URL url = new URL(url_string);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
int response_code = conn.getResponseCode();
if (response_code != 200) {
System.err.println("Ошибка Telegram API: " + response_code);
}
} catch (Exception e) {
System.err.println("Не удалось отправить сообщение в Telegram:");
e.printStackTrace();
}
}
}