Skip to content

Instantly share code, notes, and snippets.

@tors42
Created March 3, 2024 15:50
Show Gist options
  • Save tors42/6c693aaf659c89bd4eb88d491b3e0fd8 to your computer and use it in GitHub Desktop.
Save tors42/6c693aaf659c89bd4eb88d491b3e0fd8 to your computer and use it in GitHub Desktop.
A script which uses the Lichess API to listen for events, in order to detect any missed challenges
if (! Files.exists(Path.of("chariot.jar"))) {
Files.write(Path.of("chariot.jar"), URI.create(
"https://repo1.maven.org/maven2/io/github/tors42/chariot/0.0.84/chariot-0.0.84.jar"
).toURL().openStream().readAllBytes());
}
/env --class-path chariot.jar
import java.time.LocalTime;
import java.util.prefs.Preferences;
import chariot.*;
import chariot.Client.*;
import chariot.model.*;
import chariot.model.ChallengeInfo.FromTo;
import chariot.model.Event.*;
void logMissedChallenges(ClientAuth client, String myId) {
client.board().connect().stream().forEach(event -> { switch(event) {
case GameStartEvent start -> {
}
case GameStopEvent stop -> {
}
case ChallengeCreatedEvent created -> {
}
case ChallengeDeclinedEvent declined -> {
}
case ChallengeCanceledEvent canceled -> {
if (canceled.challenge().players() instanceof FromTo(var challenger, var challenged)
&& challenged.user().id().equals(myId)) {
System.out.println(LocalTime.now().withNano(0) + " Missed challenge from " + challenger.user());
}
}
}});
}
ClientAuth initializeClient() {
return switch(Client.load(Preferences.userRoot().node("challenge-log"))) {
case ClientAuth client when client.scopes().contains(Scope.challenge_read) -> client;
case Client client -> switch(client.withPkce(
url -> System.out.println("Visit Lichess to grant access at,\n" + url),
pkce -> pkce.scope(Scope.challenge_read))) {
case AuthOk(var ok) -> {
ok.store(Preferences.userRoot().node("challenge-log"));
yield ok;
}
case AuthFail(var msg) -> {
System.out.println("Failed to authenticate: " + msg);
yield null;
}
};
};
}
if (initializeClient() instanceof ClientAuth client
&& client.account().profile() instanceof Entry(var user)) {
System.out.println("Listening for missed challenges...");
logMissedChallenges(client, user.id());
} else {
System.out.println("Failed to listen for missed challenges.");
}
@tors42
Copy link
Author

tors42 commented Mar 3, 2024

Here's a video showing it in action,
where my "tors42" account is listening for missed challenges,
and I use my bot account "charibot" to send and cancel a challenge to "tors42",
and the "missed-challenges.jsh" script shows a message about the missed challenge!

missed-challenges.webm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment