commit a808355f0001d94a7ced426c73c3b47b91d4cd4e Author: Vombit Date: Sat May 23 15:11:39 2026 +0000 Upload files to "/" diff --git a/CurrencyAnalyzer.java b/CurrencyAnalyzer.java new file mode 100644 index 0000000..a224969 --- /dev/null +++ b/CurrencyAnalyzer.java @@ -0,0 +1,39 @@ +public class CurrencyAnalyzer { + + private static double lastValue = -1; + + public static void analyze(double current) { + if (lastValue == -1) { + lastValue = current; + + // Уведомление при запуске + String startMsg = "✅ Мониторинг курса USD запущен\n" + + "Текущий курс: " + current + " ₽"; + TelegramNotifier.sendMessage(startMsg); + + System.out.println("Начальное значение USD: " + current); + return; + } + + String changeMsg = ""; + if (current > lastValue) { + changeMsg = "📈 Курс доллара вырос ↑"; + } else if (current < lastValue) { + changeMsg = "📉 Курс доллара упал ↓"; + } else { + return; // без изменений — не спамим + } + + // Уведомление в Telegram + String telegramMsg = changeMsg + "\n" + + "Было: " + lastValue + " ₽\n" + + "Стало: " + current + " ₽"; + TelegramNotifier.sendMessage(telegramMsg); + + // Вывод в консоль (чистый текст) + System.out.println(changeMsg.replace("", "").replace("", "") + + " (было " + lastValue + ", стало " + current + ")"); + + lastValue = current; + } +} \ No newline at end of file diff --git a/CurrencyParser.java b/CurrencyParser.java new file mode 100644 index 0000000..4324f85 --- /dev/null +++ b/CurrencyParser.java @@ -0,0 +1,38 @@ +import java.util.regex.*; + +public class CurrencyParser { + + /** + * Парсит курс USD с актуальной страницы ЦБ + * РФ[](https://cbr.ru/currency_base/daily/) + * Структура: таблица с строкой + * + * 840 + * USD... + * 76,0535 + * + */ + public static double parseUSD(String html) { + + // Более точный и надёжный regex под текущую верстку сайта + Pattern pattern = Pattern.compile( + "USD\\s*" + + "1\\s*" + + "Доллар США\\s*" + + "([0-9,]+)", + Pattern.DOTALL | Pattern.CASE_INSENSITIVE); + + Matcher matcher = pattern.matcher(html); + + if (matcher.find()) { + String rateStr = matcher.group(1).replace(',', '.'); // заменяем запятую на точку + try { + return Double.parseDouble(rateStr); + } catch (NumberFormatException e) { + System.err.println("Ошибка парсинга числа: " + matcher.group(1)); + } + } + + return -1; // не удалось найти + } +} \ No newline at end of file diff --git a/Main.java b/Main.java new file mode 100644 index 0000000..3eca629 --- /dev/null +++ b/Main.java @@ -0,0 +1,34 @@ +public class Main { + + public static void main(String[] args) { + String botToken = "8586609598:AAHRN6eqpkqCOP4xjX_FH20jdpjbJncmqBY"; + String chatId = "462049828"; + + TelegramNotifier.init(botToken, chatId); + System.out.println("Telegram-уведомления активированы!"); + + String url = "https://cbr.ru/currency_base/daily/"; + + while (true) { + try { + String html = WebLoader.loadPage(url); + + double usd = CurrencyParser.parseUSD(html); + + if (usd != -1) { + System.out.println("USD: " + usd); + + ExcelWriter.write(usd); + CurrencyAnalyzer.analyze(usd); + } else { + System.err.println("Не удалось спарсить курс USD"); + } + + Thread.sleep(60 * 1000); + + } catch (Exception e) { + e.printStackTrace(); + } + } + } +} \ No newline at end of file diff --git a/TelegramNotifier.java b/TelegramNotifier.java new file mode 100644 index 0000000..511452d --- /dev/null +++ b/TelegramNotifier.java @@ -0,0 +1,52 @@ +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(); + } + } +} \ No newline at end of file diff --git a/WebLoader.java b/WebLoader.java new file mode 100644 index 0000000..2df1027 --- /dev/null +++ b/WebLoader.java @@ -0,0 +1,33 @@ +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; + +public class WebLoader { + + public static String loadPage(String urlString) { + StringBuilder result = new StringBuilder(); + + try { + URL url = new URL(urlString); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + conn.setRequestProperty("User-Agent", "Mozilla/5.0"); // чтобы сайт не блокировал + + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) { + + String line; + while ((line = reader.readLine()) != null) { + result.append(line).append("\n"); + } + } + + } catch (Exception e) { + e.printStackTrace(); + } + + return result.toString(); + } +} \ No newline at end of file