Add WhatsApp reminder
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
package de.jeyp91.whatsapp;
|
||||
|
||||
import org.json.simple.JSONArray;
|
||||
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.util.HashMap;
|
||||
|
||||
import static de.jeyp91.apifootball.APIFootballConnector.stringToJSONObject;
|
||||
|
||||
public class OpenAIConnector {
|
||||
private final HttpClient client;
|
||||
private final String OPENAI_TOKEN = System.getenv("OPENAI_TOKEN");
|
||||
private final String OPENAPI_URL = "https://api.openai.com/v1/chat/completions";
|
||||
private final String OPENAPI_MODEL = "gpt-3.5-turbo-0125";
|
||||
private final HashMap<String, String> generatedMessages = new HashMap<>();
|
||||
|
||||
public OpenAIConnector() {
|
||||
client = HttpClient.newBuilder().build();
|
||||
}
|
||||
|
||||
public String getReminderMessage(WhatsAppReminder reminder) {
|
||||
String key = reminder.leagueName() + reminder.matchdayName() + reminder.todayTomorrow() + reminder.time();
|
||||
String message;
|
||||
if (generatedMessages.containsKey(key)) {
|
||||
message = generatedMessages.get(key);
|
||||
} else {
|
||||
message = executeReminderPrompt(reminder.leagueName(), reminder.matchdayName(), reminder.todayTomorrow(), reminder.time(), reminder.remainingHours());
|
||||
generatedMessages.put(key, message);
|
||||
}
|
||||
message = message.replace("Hey", "Hey " + reminder.username());
|
||||
String end = "\nDu kannst deine Tipps wie immer unter https://tippliga-wuerzburg.de/app.php/football/bet abgeben.\nViele Grüße\nDie Tippliga Admins";
|
||||
message += end;
|
||||
return message;
|
||||
}
|
||||
|
||||
private String executeReminderPrompt(String leagueName, String matchdayName, String deliveryDay, String time, int remainingHours) {
|
||||
String systemPrompt = "Generiere eine Nachricht, die dem Zweck dient, jemanden daran zu erinnern, seine noch fehlenden Tipps für den kommenden Spieltag abzuschicken. Die Nachricht muss so klingen, als ob ein Freund sie in natürlicher Sprache abschickt. Sie muss auf Deutsch sein. Die Nachricht muss den richtigen Singular und Plural für die Anzahl der fehlenden Wetten verwenden. Halte dich genau an die Vorlage und ersetze die Teile gekennzeichnet durch \"{}\" durch passende Passagen. Die Antwort auf diesen Prompt soll ausschließlich die Nachricht sein.\n\n "
|
||||
+"Dies ist die Vorlage:\n"
|
||||
+"Hey,\n"
|
||||
+ (remainingHours == 24 ? "{ein netter einleitender Satz der \"league_name\", \"matchday_name\" enthält}.\n" : "{ein einleitender Satz der \"league_name\", \"matchday_name\" enthält und klar macht, dass die Zeit abläuft und nur noch weniger als eine Stunde Zeit für die Abgabe der Tipps bleibt}.\n")
|
||||
+"Bitte gib die fehlenden Tipps bis {delivery_day} um {time} ab.";
|
||||
JSONObject userInput = new JSONObject();
|
||||
userInput.put("league_name", leagueName);
|
||||
userInput.put("matchday_name", matchdayName);
|
||||
userInput.put("delivery_day", deliveryDay);
|
||||
userInput.put("time", time);
|
||||
String user = userInput.toJSONString();
|
||||
JSONObject jsonBody = new JSONObject();
|
||||
jsonBody.put("model", OPENAPI_MODEL);
|
||||
JSONArray messages = new JSONArray();
|
||||
JSONObject system = new JSONObject();
|
||||
system.put("role", "system");
|
||||
system.put("content", systemPrompt);
|
||||
messages.add(system);
|
||||
JSONObject userMessage = new JSONObject();
|
||||
userMessage.put("role", "user");
|
||||
userMessage.put("content", user);
|
||||
messages.add(userMessage);
|
||||
jsonBody.put("messages", messages);
|
||||
HttpRequest openAIRequest = HttpRequest.newBuilder()
|
||||
.uri(URI.create(OPENAPI_URL))
|
||||
.headers("Content-Type", "application/json")
|
||||
.headers("Authorization", "Bearer " + OPENAI_TOKEN)
|
||||
.POST(HttpRequest.BodyPublishers.ofString(jsonBody.toJSONString()))
|
||||
.build();
|
||||
JSONObject response = new JSONObject();
|
||||
try {
|
||||
response = stringToJSONObject(client.send(openAIRequest, HttpResponse.BodyHandlers.ofString()).body());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
JSONArray choices = (JSONArray) response.get("choices");
|
||||
JSONObject choice = (JSONObject) choices.get(0);
|
||||
JSONObject message = (JSONObject) choice.get("message");
|
||||
return message.get("content").toString();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package de.jeyp91.whatsapp;
|
||||
|
||||
public record WhatsAppReminder(int season,
|
||||
int league,
|
||||
String leagueName,
|
||||
int matchday,
|
||||
String matchdayName,
|
||||
String deliveryDate,
|
||||
String todayTomorrow,
|
||||
String time,
|
||||
int remainingHours,
|
||||
int userId,
|
||||
String username,
|
||||
String phoneNumber,
|
||||
int missingBets) {
|
||||
}
|
||||
Reference in New Issue
Block a user