Add WhatsApp reminder
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
package de.jeyp91.whatsapp;
|
||||
|
||||
import de.jeyp91.tippligaforum.TippligaSQLConnector;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.json.simple.JSONObject;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class WhatsAppNotifier {
|
||||
private final String host = System.getenv("TLW_WHATSAPP_HOST");
|
||||
private final String port = System.getenv("TLW_WHATSAPP_PORT");
|
||||
private final String apiKey = System.getenv("TLW_WHATSAPP_API_KEY");
|
||||
private static final Logger logger = LogManager.getLogger(WhatsAppNotifier.class);
|
||||
private final HttpClient client;
|
||||
private final OpenAIConnector openAIConnector = new OpenAIConnector();
|
||||
|
||||
public WhatsAppNotifier() {
|
||||
client = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(10))
|
||||
.build();
|
||||
}
|
||||
|
||||
public void sendNotifications() {
|
||||
ArrayList<WhatsAppReminder> reminders = TippligaSQLConnector.getInstance().getNextWhatsAppReminders(24);
|
||||
reminders.addAll(TippligaSQLConnector.getInstance().getNextWhatsAppReminders(1));
|
||||
reminders.forEach(reminder -> {
|
||||
boolean success = sendMessage(reminder);
|
||||
if (success) {
|
||||
markReminderAsSent(reminder);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public boolean sendMessage(WhatsAppReminder reminder) {
|
||||
String message = openAIConnector.getReminderMessage(reminder);
|
||||
JSONObject body = new JSONObject();
|
||||
body.put("number", reminder.phoneNumber().substring(2));
|
||||
body.put("message", message);
|
||||
HttpRequest req = HttpRequest.newBuilder()
|
||||
.uri(URI.create(this.host + (this.port != null ? ":" + this.port : "") + "/send"))
|
||||
.headers("Content-Type", "application/json")
|
||||
.headers("x-api-key", apiKey)
|
||||
.POST(HttpRequest.BodyPublishers.ofString(body.toJSONString()))
|
||||
.build();
|
||||
boolean success = false;
|
||||
try {
|
||||
client.send(req, HttpResponse.BodyHandlers.ofString()).body();
|
||||
success = true;
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to send WhatsApp message: " + e.getMessage());
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
public void markReminderAsSent(WhatsAppReminder reminder) {
|
||||
TippligaSQLConnector.getInstance().markWhatsAppReminderAsSent(reminder);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user