45 lines
1.5 KiB
Java
45 lines
1.5 KiB
Java
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();
|
||
}
|
||
}
|
||
} |