bot en java
This commit is contained in:
@ -0,0 +1,30 @@
|
||||
package es.imunnic.inversionitasBot;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.telegram.telegrambots.meta.TelegramBotsApi;
|
||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
|
||||
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;
|
||||
|
||||
@SpringBootApplication
|
||||
public class InversionitasBotApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(InversionitasBotApplication.class, args);
|
||||
ApplicationContext context = SpringApplication.run(InversionitasBotApplication.class, args);
|
||||
InversionitasBotApplication app = context.getBean(InversionitasBotApplication.class);
|
||||
app.initBot();
|
||||
}
|
||||
|
||||
public void initBot() {
|
||||
TelegramBot warbot = new TelegramBot();
|
||||
try {
|
||||
TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class);
|
||||
telegramBotsApi.registerBot(warbot);
|
||||
} catch (TelegramApiException t) {
|
||||
t.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,86 @@
|
||||
package es.imunnic.inversionitasBot;
|
||||
|
||||
import es.imunnic.inversionitasBot.services.ApiService;
|
||||
import org.json.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
|
||||
import org.telegram.telegrambots.meta.api.objects.Update;
|
||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
public class TelegramBot extends TelegramLongPollingBot {
|
||||
|
||||
@Value("${telegram.bot.username}")
|
||||
private String BOT_USERNAME;
|
||||
@Value("${telegram.bot.token}")
|
||||
private String BOT_TOKEN;
|
||||
|
||||
@Override
|
||||
public String getBotUsername() {
|
||||
return BOT_USERNAME;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBotToken() {
|
||||
return BOT_TOKEN;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUpdateReceived(Update update) {
|
||||
if (update.hasMessage() && update.getMessage().hasText()) {
|
||||
String messageText = update.getMessage().getText();
|
||||
String chatId = update.getMessage().getChatId().toString();
|
||||
|
||||
if (messageText.equalsIgnoreCase("/resumen")) {
|
||||
String resumen = construirResumenNoticias();
|
||||
sendMessage(chatId, resumen);
|
||||
} else {
|
||||
sendMessage(chatId, "Comando no reconocido. Usa /resumen para obtener el resumen diario.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void sendMessage(String chatId, String text) {
|
||||
try {
|
||||
SendMessage message = new SendMessage();
|
||||
message.setChatId(chatId);
|
||||
message.setText(text);
|
||||
execute(message);
|
||||
} catch (TelegramApiException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private String construirResumenNoticias() {
|
||||
LocalDate today = LocalDate.now();
|
||||
String fechaInicio = today.format(DateTimeFormatter.ISO_DATE);
|
||||
String fechaFin = today.format(DateTimeFormatter.ISO_DATE);
|
||||
|
||||
// Palabras clave de ejemplo
|
||||
String[] keywords = {"política", "economía", "tecnología"};
|
||||
|
||||
StringBuilder mensaje = new StringBuilder("📢 *Resumen de noticias del día:*\n\n");
|
||||
for (String keyword : keywords) {
|
||||
String jsonResponse = ApiService.getTitlesByKeyword(keyword, fechaInicio, fechaFin);
|
||||
JSONObject jsonObject = new JSONObject(jsonResponse);
|
||||
|
||||
if (jsonObject.has("titles")) {
|
||||
String titles = jsonObject.getString("titles");
|
||||
mensaje.append("🔹 *").append(keyword).append("*:\n");
|
||||
mensaje.append(" - ").append(titles.replace(",", "\n - ")).append("\n\n");
|
||||
} else {
|
||||
mensaje.append("🔹 *").append(keyword).append("*: No hay noticias disponibles.\n\n");
|
||||
}
|
||||
}
|
||||
|
||||
mensaje.append("📢 ¡Mañana volveremos con más información!");
|
||||
return mensaje.toString();
|
||||
}
|
||||
}
|
@ -0,0 +1,104 @@
|
||||
package es.imunnic.inversionitasBot.services;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class ApiService {
|
||||
@Value("${apiservice.url}")
|
||||
private static String API_BASE_URL;
|
||||
|
||||
// Método genérico para hacer solicitudes GET
|
||||
public static String sendGetRequest(String endpoint) {
|
||||
try {
|
||||
URL url = new URL(API_BASE_URL + endpoint);
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||
StringBuilder content = new StringBuilder();
|
||||
String inputLine;
|
||||
while ((inputLine = in.readLine()) != null) {
|
||||
content.append(inputLine);
|
||||
}
|
||||
in.close();
|
||||
connection.disconnect();
|
||||
|
||||
return content.toString();
|
||||
} catch (Exception e) {
|
||||
return "{\"error\": \"Error al obtener datos de la API\"}";
|
||||
}
|
||||
}
|
||||
|
||||
// 1️⃣ Obtener el conteo de noticias por fuente
|
||||
public static String getNewsCountBySource() {
|
||||
return sendGetRequest("/count/by-source");
|
||||
}
|
||||
|
||||
// 2️⃣ Obtener el conteo de noticias por autor
|
||||
public static String getNewsCountByAuthor() {
|
||||
return sendGetRequest("/count/by-author");
|
||||
}
|
||||
|
||||
// 3️⃣ Obtener noticia por ID
|
||||
public static String getNewsById(int newsId) {
|
||||
return sendGetRequest("/" + newsId);
|
||||
}
|
||||
|
||||
// 4️⃣ Obtener el conteo de noticias por keyword
|
||||
public static String getNewsCountByKeyword(String fechaInicio, String fechaFin) {
|
||||
String params = "?fechaInicio=" + fechaInicio + "&fechaFin=" + fechaFin;
|
||||
return sendGetRequest("/count/by-keyword" + params);
|
||||
}
|
||||
|
||||
// 5️⃣ Obtener todas las keywords
|
||||
public static String getAllKeywords() {
|
||||
return sendGetRequest("/keywords/");
|
||||
}
|
||||
|
||||
// 6️⃣ Contar noticias por fuente con una keyword y rango de fechas
|
||||
public static String getNewsCountBySourceForKeyword(String keyword, String fechaInicio, String fechaFin) {
|
||||
String params = "?keyword=" + encodeParam(keyword) + "&fechaInicio=" + fechaInicio + "&fechaFin=" + fechaFin;
|
||||
return sendGetRequest("/count/by-source/keyword/date-range" + params);
|
||||
}
|
||||
|
||||
// 7️⃣ Obtener títulos de noticias por keyword en un rango de fechas
|
||||
public static String getTitlesByKeyword(String keyword, String fechaInicio, String fechaFin) {
|
||||
String params = "?keyword=" + encodeParam(keyword) + "&fecha_inicio=" + fechaInicio + "&fecha_fin=" + fechaFin;
|
||||
return sendGetRequest("/titles/by-keyword/date-range" + params);
|
||||
}
|
||||
|
||||
// 8️⃣ Obtener todos los títulos de noticias en un rango de fechas
|
||||
public static String getNewsTitles(String fechaInicio, String fechaFin) {
|
||||
String params = "?fechaInicio=" + fechaInicio + "&fechaFin=" + fechaFin;
|
||||
return sendGetRequest("/titles/" + params);
|
||||
}
|
||||
|
||||
// 9️⃣ Obtener todas las noticias con paginación
|
||||
public static String getAllNews(String fechaInicio, String fechaFin, int page, int pageSize) {
|
||||
String params = "?fechaInicio=" + fechaInicio + "&fechaFin=" + fechaFin +
|
||||
"&page=" + page + "&pageSize=" + pageSize;
|
||||
return sendGetRequest("/" + params);
|
||||
}
|
||||
|
||||
// 🔟 Método para formatear LocalDateTime a String (si se usa en Java)
|
||||
public static String formatDate(LocalDateTime dateTime) {
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
|
||||
return dateTime.format(formatter);
|
||||
}
|
||||
|
||||
// 🌎 Método auxiliar para codificar parámetros en URL
|
||||
private static String encodeParam(String param) {
|
||||
return URLEncoder.encode(param, StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
4
bot/src/main/resources/application.properties
Normal file
4
bot/src/main/resources/application.properties
Normal file
@ -0,0 +1,4 @@
|
||||
spring.application.name=inversionitasBot
|
||||
telegram.bot.username=Inversionitas_Bot
|
||||
telegram.bot.token=7626026035:AAHEMp_iIN3y8AwywL0R6OTQvNi7EcJZ0iY
|
||||
apiservice.url=http://fastapi_app/news
|
@ -0,0 +1,13 @@
|
||||
package es.imunnic.inversionitasBot;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class InversionitasBotApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user