initial commit
This commit is contained in:
@@ -0,0 +1,114 @@
|
||||
package dev.ksan.botinator;
|
||||
|
||||
import dev.arbjerg.lavalink.client.Helpers;
|
||||
import dev.arbjerg.lavalink.client.LavalinkClient;
|
||||
import dev.arbjerg.lavalink.client.NodeOptions;
|
||||
import dev.arbjerg.lavalink.libraries.jda.JDAVoiceUpdateListener;
|
||||
import dev.ksan.botinator.command.Command;
|
||||
import dev.ksan.botinator.command.CommandManager;
|
||||
import dev.ksan.botinator.command.commands.*;
|
||||
import dev.ksan.botinator.music.MusicManager;
|
||||
import net.dv8tion.jda.api.JDA;
|
||||
import net.dv8tion.jda.api.JDABuilder;
|
||||
import net.dv8tion.jda.api.entities.Guild;
|
||||
import net.dv8tion.jda.api.events.session.ReadyEvent;
|
||||
import net.dv8tion.jda.api.hooks.ListenerAdapter;
|
||||
import net.dv8tion.jda.api.requests.GatewayIntent;
|
||||
import net.dv8tion.jda.api.utils.MemberCachePolicy;
|
||||
import net.dv8tion.jda.api.utils.cache.CacheFlag;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Entry point: reads config from the environment, connects to Lavalink, builds
|
||||
* JDA, and wires up the commands. Command logic lives in {@link CommandManager}
|
||||
* and the classes under {@code dev.ksan.botinator.command.commands}.
|
||||
*/
|
||||
public class Main extends ListenerAdapter {
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
String token = System.getenv("BOT_TOKEN");
|
||||
if (token == null || token.isBlank()) {
|
||||
System.err.println("ERROR: environment variable BOT_TOKEN is not set. "
|
||||
+ "Set it to your Discord bot token and try again.");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
// Lavalink client must be created before JDA so we can plug in the voice
|
||||
// interceptor. Its node points at a running Lavalink v4 server.
|
||||
LavalinkClient lavalink = new LavalinkClient(Helpers.getUserIdFromToken(token));
|
||||
lavalink.addNode(new NodeOptions.Builder()
|
||||
.setName("main")
|
||||
.setServerUri(getenv("LAVALINK_URI", "ws://localhost:2333"))
|
||||
.setPassword(getenv("LAVALINK_PASSWORD", "youshallnotpass"))
|
||||
.build());
|
||||
|
||||
MusicManager musicManager = new MusicManager(lavalink);
|
||||
|
||||
List<Command> commands = List.of(
|
||||
new HelloCommand(),
|
||||
new SayCommand(),
|
||||
new RollDiceCommand(),
|
||||
new ARMeterCommand(),
|
||||
new PlayCommand(musicManager),
|
||||
new SkipCommand(musicManager),
|
||||
new QueueCommand(musicManager),
|
||||
new LoopCommand(musicManager),
|
||||
new ClearCommand(musicManager)
|
||||
);
|
||||
CommandManager commandManager = new CommandManager(commands);
|
||||
|
||||
// Music needs the voice-state intent + cache so we can find the caller's
|
||||
// voice channel; the interceptor forwards voice updates to Lavalink.
|
||||
JDA jda = JDABuilder.createLight(token, GatewayIntent.GUILD_VOICE_STATES)
|
||||
.enableCache(CacheFlag.VOICE_STATE)
|
||||
// Cache members who are in a voice channel; without this JDA won't
|
||||
// attach a voice state, so getMember().getVoiceState() stays null.
|
||||
.setMemberCachePolicy(MemberCachePolicy.VOICE)
|
||||
.setVoiceDispatchInterceptor(new JDAVoiceUpdateListener(lavalink)).setAutoReconnect(true)
|
||||
.addEventListeners(new Main(), commandManager)
|
||||
.build();
|
||||
|
||||
// Block until the gateway connection is fully established.
|
||||
jda.awaitReady();
|
||||
|
||||
registerCommands(jda, commandManager);
|
||||
}
|
||||
|
||||
private static void registerCommands(JDA jda, CommandManager commandManager) {
|
||||
String guildId = System.getenv("GUILD_ID");
|
||||
if (guildId != null && !guildId.isBlank()) {
|
||||
Guild guild = jda.getGuildById(guildId);
|
||||
if (guild != null) {
|
||||
// Guild commands register instantly.
|
||||
guild.updateCommands()
|
||||
.addCommands(commandManager.getCommandData())
|
||||
.queue();
|
||||
System.out.println("Registered " + commandManager.getCommandData().size()
|
||||
+ " guild command(s) for guild " + guildId);
|
||||
return;
|
||||
}
|
||||
System.err.println("WARNING: GUILD_ID " + guildId
|
||||
+ " not found (is the bot a member of that guild?). Falling back to global.");
|
||||
}
|
||||
|
||||
// Global commands can take up to an hour to appear.
|
||||
jda.updateCommands()
|
||||
.addCommands(commandManager.getCommandData())
|
||||
.queue();
|
||||
System.out.println("Registered " + commandManager.getCommandData().size()
|
||||
+ " global command(s) (may take up to an hour to appear).");
|
||||
}
|
||||
|
||||
private static String getenv(String name, String fallback) {
|
||||
String value = System.getenv(name);
|
||||
return (value == null || value.isBlank()) ? fallback : value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReady(ReadyEvent event) {
|
||||
JDA jda = event.getJDA();
|
||||
System.out.println("Bot connected and ready as "
|
||||
+ jda.getSelfUser().getAsTag() + " (id " + jda.getSelfUser().getId() + ").");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package dev.ksan.botinator.command;
|
||||
|
||||
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
|
||||
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData;
|
||||
|
||||
/**
|
||||
* A single slash command. Each command knows how to describe itself (name,
|
||||
* description, options) and how to respond when invoked. Commands that attach
|
||||
* buttons can also claim and handle their component interactions.
|
||||
*/
|
||||
public interface Command {
|
||||
|
||||
/** Name, description and options used to register the command with Discord. */
|
||||
SlashCommandData getData();
|
||||
|
||||
/** Handle an invocation of this command. */
|
||||
void execute(SlashCommandInteractionEvent event);
|
||||
|
||||
/** Convenience: the command name, used for routing. */
|
||||
default String getName() {
|
||||
return getData().getName();
|
||||
}
|
||||
|
||||
/** Whether this command owns the button with the given component id. */
|
||||
default boolean handlesComponent(String componentId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Handle a button interaction previously claimed via {@link #handlesComponent}. */
|
||||
default void onComponent(ButtonInteractionEvent event) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package dev.ksan.botinator.command;
|
||||
|
||||
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
|
||||
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
|
||||
import net.dv8tion.jda.api.hooks.ListenerAdapter;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Holds all commands and routes each slash-command interaction to the matching
|
||||
* {@link Command}. Registering it as a JDA event listener is all Main needs to do.
|
||||
*/
|
||||
public class CommandManager extends ListenerAdapter {
|
||||
|
||||
private final Map<String, Command> commands = new LinkedHashMap<>();
|
||||
|
||||
public CommandManager(List<Command> commands) {
|
||||
for (Command command : commands) {
|
||||
this.commands.put(command.getName(), command);
|
||||
}
|
||||
}
|
||||
|
||||
/** The command definitions to send to Discord during registration. */
|
||||
public List<SlashCommandData> getCommandData() {
|
||||
List<SlashCommandData> data = new ArrayList<>();
|
||||
for (Command command : commands.values()) {
|
||||
data.add(command.getData());
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSlashCommandInteraction(SlashCommandInteractionEvent event) {
|
||||
Command command = commands.get(event.getName());
|
||||
if (command == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
command.execute(event);
|
||||
} catch (Exception e) {
|
||||
System.err.println("Error handling /" + event.getName() + ": " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
if (!event.isAcknowledged()) {
|
||||
event.reply("Something went wrong running that command.").setEphemeral(true).queue();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onButtonInteraction(ButtonInteractionEvent event) {
|
||||
for (Command command : commands.values()) {
|
||||
if (command.handlesComponent(event.getComponentId())) {
|
||||
try {
|
||||
command.onComponent(event);
|
||||
} catch (Exception e) {
|
||||
System.err.println("Error handling component "
|
||||
+ event.getComponentId() + ": " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package dev.ksan.botinator.command.commands;
|
||||
|
||||
import dev.ksan.botinator.command.Command;
|
||||
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.Commands;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
// No need to know what an AR is... so please don't even ask
|
||||
public class ARMeterCommand implements Command {
|
||||
|
||||
private static final Set<String> ALWAYS_100_USERS_ID = loadIDs("ALWAYS_100_USERS_FILE", "always100.txt");
|
||||
|
||||
private static final Set<String> ALWAYS_90_USERS_ID = loadIDs("ALWAYS_90_USERS_FILE", "always90.txt");
|
||||
|
||||
|
||||
@Override
|
||||
public SlashCommandData getData() {
|
||||
return Commands.slash("armeter", "Measure what's your percentage of being an AR");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(SlashCommandInteractionEvent event) {
|
||||
String userId = event.getUser().getId();
|
||||
int percent;
|
||||
if (ALWAYS_100_USERS_ID.contains(userId)) {
|
||||
percent = 100;
|
||||
} else if (ALWAYS_90_USERS_ID.contains(userId)) {
|
||||
percent = ThreadLocalRandom.current().nextInt(90, 101);
|
||||
} else {
|
||||
percent = ThreadLocalRandom.current().nextInt(0, 101);
|
||||
}
|
||||
event.reply(event.getUser().getAsMention() + " you have a " + percent + "% chance of being an AR!").queue();
|
||||
}
|
||||
private static Set<String> loadIDs(String envVar, String file) {
|
||||
String path = System.getenv().getOrDefault(envVar, file);
|
||||
|
||||
try{
|
||||
Set<String> ids = Files.readAllLines(Path.of(path), StandardCharsets.UTF_8).stream().map(String::trim)
|
||||
.filter(line -> !line.isEmpty() && !line.startsWith("#")).collect(Collectors.toSet());
|
||||
|
||||
return ids;
|
||||
|
||||
} catch (IOException e) {
|
||||
System.err.println("Failed to load IDs from " + file + ": " + e.getMessage());
|
||||
return Set.of();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package dev.ksan.botinator.command.commands;
|
||||
|
||||
import dev.ksan.botinator.command.Command;
|
||||
import dev.ksan.botinator.music.MusicManager;
|
||||
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.Commands;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData;
|
||||
|
||||
public class ClearCommand implements Command {
|
||||
|
||||
private final MusicManager music;
|
||||
|
||||
public ClearCommand(MusicManager music) {
|
||||
this.music = music;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SlashCommandData getData() {
|
||||
return Commands.slash("clear", "Clear the entire queue (keeps the current track playing)");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(SlashCommandInteractionEvent event) {
|
||||
if (event.getGuild() == null) {
|
||||
event.reply("This command only works in a server.").setEphemeral(true).queue();
|
||||
return;
|
||||
}
|
||||
|
||||
int removed = music.clearQueue(event.getGuild().getIdLong());
|
||||
if (removed == 0) {
|
||||
event.reply("The queue is already empty.").setEphemeral(true).queue();
|
||||
} else {
|
||||
event.reply("🗑️ Cleared **" + removed + "** track(s) from the queue.").queue();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package dev.ksan.botinator.command.commands;
|
||||
|
||||
import dev.ksan.botinator.command.Command;
|
||||
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.Commands;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData;
|
||||
|
||||
public class HelloCommand implements Command {
|
||||
|
||||
@Override
|
||||
public SlashCommandData getData() {
|
||||
return Commands.slash("hello", "Test command");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(SlashCommandInteractionEvent event) {
|
||||
event.reply("Hello World! I'm working").queue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package dev.ksan.botinator.command.commands;
|
||||
|
||||
import dev.ksan.botinator.command.Command;
|
||||
import dev.ksan.botinator.music.MusicManager;
|
||||
import dev.ksan.botinator.music.MusicManager.LoopMode;
|
||||
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
|
||||
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
|
||||
import net.dv8tion.jda.api.interactions.commands.OptionType;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.Commands;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData;
|
||||
|
||||
/**
|
||||
* Controls how playback repeats. Bare {@code /loop} toggles looping the whole
|
||||
* queue on and off; {@code /loop mode:song} loops just the current track, and
|
||||
* {@code /loop mode:off} stops looping.
|
||||
*/
|
||||
public class LoopCommand implements Command {
|
||||
|
||||
private final MusicManager manager;
|
||||
|
||||
public LoopCommand(MusicManager manager) {
|
||||
this.manager = manager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SlashCommandData getData() {
|
||||
return Commands.slash("loop", "Loop the queue, the current song, or turn looping off.")
|
||||
.addOptions(new OptionData(OptionType.STRING, "mode",
|
||||
"What to loop — leave empty to toggle the whole queue.", false)
|
||||
.addChoice("queue", "queue")
|
||||
.addChoice("song", "song")
|
||||
.addChoice("off", "off"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(SlashCommandInteractionEvent event) {
|
||||
if (event.getGuild() == null) {
|
||||
event.reply("This command only works in a server.").setEphemeral(true).queue();
|
||||
return;
|
||||
}
|
||||
|
||||
long guildId = event.getGuild().getIdLong();
|
||||
OptionMapping modeOption = event.getOption("mode");
|
||||
|
||||
LoopMode mode;
|
||||
if (modeOption == null) {
|
||||
// Bare /loop toggles whole-queue looping.
|
||||
mode = manager.toggleQueueLoop(guildId);
|
||||
} else {
|
||||
mode = manager.setLoopMode(guildId, switch (modeOption.getAsString()) {
|
||||
case "song" -> LoopMode.SONG;
|
||||
case "queue" -> LoopMode.QUEUE;
|
||||
default -> LoopMode.OFF;
|
||||
});
|
||||
}
|
||||
|
||||
event.reply(describe(mode)).queue();
|
||||
}
|
||||
|
||||
private static String describe(LoopMode mode) {
|
||||
return switch (mode) {
|
||||
case QUEUE -> "🔁 Now looping the **whole queue**.";
|
||||
case SONG -> "🔂 Now looping the **current song**.";
|
||||
case OFF -> "➡️ Looping is now **off**.";
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package dev.ksan.botinator.command.commands;
|
||||
|
||||
import dev.arbjerg.lavalink.client.AbstractAudioLoadResultHandler;
|
||||
import dev.arbjerg.lavalink.client.Link;
|
||||
import dev.arbjerg.lavalink.client.player.LoadFailed;
|
||||
import dev.arbjerg.lavalink.client.player.PlaylistLoaded;
|
||||
import dev.arbjerg.lavalink.client.player.SearchResult;
|
||||
import dev.arbjerg.lavalink.client.player.Track;
|
||||
import dev.arbjerg.lavalink.client.player.TrackLoaded;
|
||||
import dev.ksan.botinator.command.Command;
|
||||
import dev.ksan.botinator.music.MusicManager;
|
||||
import dev.ksan.botinator.util.CatchPhrases;
|
||||
import net.dv8tion.jda.api.entities.GuildVoiceState;
|
||||
import net.dv8tion.jda.api.entities.channel.middleman.AudioChannel;
|
||||
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
|
||||
import net.dv8tion.jda.api.interactions.commands.OptionType;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.Commands;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Plays audio in the caller's voice channel via Lavalink. Accepts a direct
|
||||
* media/YouTube URL, a playlist URL, or plain text (treated as a YouTube search).
|
||||
* If something is already playing, the track(s) are added to the queue.
|
||||
*/
|
||||
public class PlayCommand implements Command {
|
||||
|
||||
private final MusicManager music;
|
||||
|
||||
public PlayCommand(MusicManager music) {
|
||||
this.music = music;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SlashCommandData getData() {
|
||||
return Commands.slash("play", "Play or queue a track, playlist, or search query")
|
||||
.addOption(OptionType.STRING, "query", "A media/YouTube/playlist URL or search text", true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(SlashCommandInteractionEvent event) {
|
||||
if (event.getGuild() == null || event.getMember() == null) {
|
||||
event.reply("This command only works in a server.").setEphemeral(true).queue();
|
||||
return;
|
||||
}
|
||||
|
||||
GuildVoiceState voiceState = event.getMember().getVoiceState();
|
||||
AudioChannel channel = voiceState == null ? null : voiceState.getChannel();
|
||||
if (channel == null) {
|
||||
event.reply("Join a voice channel first, then run /play.").setEphemeral(true).queue();
|
||||
return;
|
||||
}
|
||||
|
||||
// Loading a track hits the network, so acknowledge the interaction first.
|
||||
event.deferReply().queue();
|
||||
|
||||
// With Lavalink, use the direct audio controller (NOT the audio manager):
|
||||
// JDA only opens the gateway voice connection; Lavalink sends the audio.
|
||||
event.getJDA().getDirectAudioController().connect(channel);
|
||||
|
||||
long guildId = event.getGuild().getIdLong();
|
||||
String raw = event.getOption("query").getAsString().trim();
|
||||
String identifier = isUrl(raw) ? raw : "ytsearch:" + raw;
|
||||
|
||||
Link link = music.getLink(guildId);
|
||||
link.loadItem(identifier).subscribe(new AbstractAudioLoadResultHandler() {
|
||||
@Override
|
||||
public void ontrackLoaded(TrackLoaded result) {
|
||||
queueSingle(result.getTrack());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSearchResultLoaded(SearchResult result) {
|
||||
List<Track> tracks = result.getTracks();
|
||||
if (tracks.isEmpty()) {
|
||||
edit("No results for that search.");
|
||||
return;
|
||||
}
|
||||
queueSingle(tracks.get(0));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPlaylistLoaded(PlaylistLoaded result) {
|
||||
List<Track> tracks = result.getTracks();
|
||||
if (tracks.isEmpty()) {
|
||||
edit("That playlist was empty.");
|
||||
return;
|
||||
}
|
||||
boolean startedNow = music.enqueueAll(guildId, tracks);
|
||||
String header = "➕ Queued **" + tracks.size() + "** tracks from **"
|
||||
+ result.getInfo().getName() + "**";
|
||||
edit(startedNow
|
||||
? header + " — now playing **" + tracks.get(0).getInfo().getTitle() + "**"
|
||||
: header);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void noMatches() {
|
||||
edit("Couldn't find anything for that.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadFailed(LoadFailed result) {
|
||||
edit("Failed to load: " + result.getException().getMessage());
|
||||
}
|
||||
|
||||
private void queueSingle(Track track) {
|
||||
boolean startedNow = music.enqueue(guildId, track);
|
||||
String verb = startedNow ? "▶️ Now playing: **" : "➕ Added to queue: **";
|
||||
edit(verb + track.getInfo().getTitle() + "** by " + track.getInfo().getAuthor() + "\n"
|
||||
+ "\n**" + CatchPhrases.getOptimistic() + "**");
|
||||
}
|
||||
|
||||
private void edit(String message) {
|
||||
event.getHook().editOriginal(message).queue();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static boolean isUrl(String s) {
|
||||
return s.startsWith("http://") || s.startsWith("https://");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package dev.ksan.botinator.command.commands;
|
||||
|
||||
import dev.arbjerg.lavalink.client.player.Track;
|
||||
import dev.arbjerg.lavalink.protocol.v4.TrackInfo;
|
||||
import dev.ksan.botinator.command.Command;
|
||||
import dev.ksan.botinator.music.MusicManager;
|
||||
import net.dv8tion.jda.api.EmbedBuilder;
|
||||
import net.dv8tion.jda.api.components.actionrow.ActionRow;
|
||||
import net.dv8tion.jda.api.components.buttons.Button;
|
||||
import net.dv8tion.jda.api.entities.MessageEmbed;
|
||||
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
|
||||
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.Commands;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Shows the queue as a paginated embed with Prev/Next buttons — 10 tracks per
|
||||
* page. The buttons re-read the live queue each press, so the view stays current.
|
||||
*/
|
||||
public class QueueCommand implements Command {
|
||||
|
||||
private static final int PAGE_SIZE = 10;
|
||||
private static final String ID_PREFIX = "queue:";
|
||||
|
||||
private final MusicManager music;
|
||||
|
||||
public QueueCommand(MusicManager music) {
|
||||
this.music = music;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SlashCommandData getData() {
|
||||
return Commands.slash("queue", "Show the current queue.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(SlashCommandInteractionEvent event) {
|
||||
if (event.getGuild() == null) {
|
||||
event.reply("This command only works in a server.").setEphemeral(true).queue();
|
||||
return;
|
||||
}
|
||||
|
||||
long guildId = event.getGuild().getIdLong();
|
||||
Track current = music.getCurrent(guildId);
|
||||
List<Track> upcoming = music.getQueue(guildId);
|
||||
if (current == null && upcoming.isEmpty()) {
|
||||
event.reply("There is nothing queued.").setEphemeral(true).queue();
|
||||
return;
|
||||
}
|
||||
|
||||
int totalPages = totalPages(upcoming.size());
|
||||
MusicManager.LoopMode mode = music.getLoopMode(guildId);
|
||||
|
||||
event.replyEmbeds(render(current, upcoming, 0, mode))
|
||||
.addComponents(navRow(0, totalPages))
|
||||
.queue();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean handlesComponent(String componentId) {
|
||||
return componentId.startsWith(ID_PREFIX);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComponent(ButtonInteractionEvent event) {
|
||||
if (event.getGuild() == null) {
|
||||
event.deferEdit().queue();
|
||||
return;
|
||||
}
|
||||
|
||||
long guildId = event.getGuild().getIdLong();
|
||||
Track current = music.getCurrent(guildId);
|
||||
List<Track> upcoming = music.getQueue(guildId);
|
||||
int totalPages = totalPages(upcoming.size());
|
||||
int page = clamp(parsePage(event.getComponentId()), totalPages);
|
||||
|
||||
MusicManager.LoopMode mode = music.getLoopMode(guildId);
|
||||
|
||||
event.editMessageEmbeds(render(current, upcoming, page, mode))
|
||||
.setComponents(navRow(page, totalPages))
|
||||
.queue();
|
||||
}
|
||||
|
||||
private MessageEmbed render(Track current, List<Track> upcoming, int page, MusicManager.LoopMode mode) {
|
||||
int totalPages = totalPages(upcoming.size());
|
||||
page = clamp(page, totalPages);
|
||||
EmbedBuilder eb;
|
||||
if (mode == MusicManager.LoopMode.QUEUE) {
|
||||
eb = new EmbedBuilder()
|
||||
.setTitle("🎵 Looped Queue")
|
||||
.setColor(new Color(0x5865F2));
|
||||
|
||||
} else if( mode == MusicManager.LoopMode.OFF) {
|
||||
eb = new EmbedBuilder().setTitle("🎵 Looping Current Song Only")
|
||||
.setColor(new Color(0x5865F2));
|
||||
} else {
|
||||
eb = new EmbedBuilder()
|
||||
.setTitle("🎵 Queue")
|
||||
.setColor(new Color(0x5865F2));
|
||||
|
||||
}
|
||||
if (current != null) {
|
||||
eb.addField("Now Playing", formatLine(current), false);
|
||||
}
|
||||
|
||||
if (upcoming.isEmpty()) {
|
||||
eb.setDescription("*Nothing else queued.*");
|
||||
} else {
|
||||
int start = page * PAGE_SIZE;
|
||||
int end = Math.min(start + PAGE_SIZE, upcoming.size());
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = start; i < end; i++) {
|
||||
sb.append('`').append(i + 1).append(".` ")
|
||||
.append(formatLine(upcoming.get(i))).append('\n');
|
||||
}
|
||||
eb.setDescription(sb.toString());
|
||||
}
|
||||
|
||||
eb.setFooter("Page " + (page + 1) + "/" + totalPages
|
||||
+ " • " + upcoming.size() + " in queue • "
|
||||
+ formatDuration(totalMillis(upcoming)) + " total");
|
||||
return eb.build();
|
||||
}
|
||||
|
||||
private static ActionRow navRow(int page, int totalPages) {
|
||||
Button prev = Button.primary(ID_PREFIX + (page - 1), "◀ Prev").withDisabled(page <= 0);
|
||||
Button next = Button.primary(ID_PREFIX + (page + 1), "Next ▶").withDisabled(page >= totalPages - 1);
|
||||
return ActionRow.of(prev, next);
|
||||
}
|
||||
|
||||
private static String formatLine(Track track) {
|
||||
TrackInfo info = track.getInfo();
|
||||
String title = escape(info.getTitle());
|
||||
String uri = info.getUri();
|
||||
String name = (uri != null && !uri.isBlank()) ? "[" + title + "](" + uri + ")" : "**" + title + "**";
|
||||
String length = info.isStream() ? "🔴 LIVE" : formatDuration(info.getLength());
|
||||
return name + " — " + escape(info.getAuthor()) + " `" + length + "`";
|
||||
}
|
||||
|
||||
private static long totalMillis(List<Track> tracks) {
|
||||
long total = 0;
|
||||
for (Track track : tracks) {
|
||||
if (!track.getInfo().isStream()) {
|
||||
total += track.getInfo().getLength();
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
private static int totalPages(int queueSize) {
|
||||
return Math.max(1, (int) Math.ceil(queueSize / (double) PAGE_SIZE));
|
||||
}
|
||||
|
||||
private static int clamp(int page, int totalPages) {
|
||||
return Math.max(0, Math.min(page, totalPages - 1));
|
||||
}
|
||||
|
||||
private static int parsePage(String componentId) {
|
||||
try {
|
||||
return Integer.parseInt(componentId.substring(ID_PREFIX.length()));
|
||||
} catch (NumberFormatException e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static String formatDuration(long millis) {
|
||||
long totalSeconds = millis / 1000;
|
||||
long hours = totalSeconds / 3600;
|
||||
long minutes = (totalSeconds % 3600) / 60;
|
||||
long seconds = totalSeconds % 60;
|
||||
return hours > 0
|
||||
? String.format("%d:%02d:%02d", hours, minutes, seconds)
|
||||
: String.format("%d:%02d", minutes, seconds);
|
||||
}
|
||||
|
||||
/** Keep track titles from breaking the surrounding markdown link. */
|
||||
private static String escape(String s) {
|
||||
return s.replace("[", "(").replace("]", ")");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package dev.ksan.botinator.command.commands;
|
||||
|
||||
import dev.ksan.botinator.command.Command;
|
||||
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
|
||||
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
|
||||
import net.dv8tion.jda.api.interactions.commands.OptionType;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.Commands;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData;
|
||||
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
public class RollDiceCommand implements Command {
|
||||
|
||||
@Override
|
||||
public SlashCommandData getData() {
|
||||
return Commands.slash("rolldice", "Roll a die")
|
||||
.addOption(OptionType.INTEGER, "sides", "Number of sides (default 6)", false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(SlashCommandInteractionEvent event) {
|
||||
int sides = event.getOption("sides", 6, OptionMapping::getAsInt);
|
||||
if (sides < 2) {
|
||||
event.reply("A die needs at least 2 sides.").setEphemeral(true).queue();
|
||||
return;
|
||||
}
|
||||
int roll = ThreadLocalRandom.current().nextInt(1, sides + 1);
|
||||
event.reply("🎲 You rolled a **" + roll + "** (d" + sides + ")").queue();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package dev.ksan.botinator.command.commands;
|
||||
|
||||
import dev.ksan.botinator.command.Command;
|
||||
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
|
||||
import net.dv8tion.jda.api.interactions.commands.OptionType;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.Commands;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
public class SayCommand implements Command {
|
||||
|
||||
@Override
|
||||
public SlashCommandData getData() {
|
||||
return Commands.slash("say", "Make the bot repeat your message")
|
||||
.addOption(OptionType.STRING, "message", "What the bot should say", true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(SlashCommandInteractionEvent event) {
|
||||
String message = event.getOption("message").getAsString();
|
||||
// Suppress mentions so /say can't be used to ping @everyone or roles.
|
||||
event.reply(message)
|
||||
.setAllowedMentions(Collections.emptyList())
|
||||
.queue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package dev.ksan.botinator.command.commands;
|
||||
|
||||
import dev.ksan.botinator.command.Command;
|
||||
import dev.ksan.botinator.music.MusicManager;
|
||||
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.Commands;
|
||||
import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData;
|
||||
|
||||
public class SkipCommand implements Command {
|
||||
|
||||
private final MusicManager music;
|
||||
|
||||
public SkipCommand(MusicManager music) {
|
||||
this.music = music;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SlashCommandData getData() {
|
||||
return Commands.slash("skip", "Skip the current track");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(SlashCommandInteractionEvent event) {
|
||||
if (event.getGuild() == null) {
|
||||
event.reply("This command only works in a server.").setEphemeral(true).queue();
|
||||
return;
|
||||
}
|
||||
|
||||
MusicManager.SkipResult result = music.skip(event.getGuild().getIdLong());
|
||||
if (!result.somethingWasPlaying()) {
|
||||
event.reply("Nothing is playing.").setEphemeral(true).queue();
|
||||
} else if (result.nowPlaying() != null) {
|
||||
event.reply("⏭️ Skipped. Now playing: **"
|
||||
+ result.nowPlaying().getInfo().getTitle() + "**").queue();
|
||||
} else {
|
||||
event.reply("⏭️ Skipped. The queue is now empty.").queue();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package dev.ksan.botinator.music;
|
||||
|
||||
import dev.arbjerg.lavalink.client.LavalinkClient;
|
||||
import dev.arbjerg.lavalink.client.Link;
|
||||
import dev.arbjerg.lavalink.client.event.TrackEndEvent;
|
||||
import dev.arbjerg.lavalink.client.player.Track;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Per-guild playback state: a queue of upcoming tracks plus the track currently
|
||||
* playing. Starts a track immediately when idle, queues it when busy, and
|
||||
* auto-advances to the next track when one finishes.
|
||||
*/
|
||||
public class MusicManager {
|
||||
|
||||
private final LavalinkClient lavalink;
|
||||
private final Map<Long, GuildMusic> byGuild = new ConcurrentHashMap<>();
|
||||
|
||||
public MusicManager(LavalinkClient lavalink) {
|
||||
this.lavalink = lavalink;
|
||||
// Advance the queue whenever a track finishes on its own.
|
||||
lavalink.on(TrackEndEvent.class).subscribe(this::onTrackEnd);
|
||||
}
|
||||
|
||||
/** A snapshot of the upcoming (not-yet-played) tracks for a guild. */
|
||||
public List<Track> getQueue(long guildId) {
|
||||
GuildMusic music = byGuild.get(guildId);
|
||||
if (music == null) {
|
||||
return List.of();
|
||||
}
|
||||
synchronized (music) {
|
||||
return List.copyOf(music.queue);
|
||||
}
|
||||
}
|
||||
|
||||
/** The track currently playing in a guild, or null if nothing is playing. */
|
||||
public Track getCurrent(long guildId) {
|
||||
GuildMusic music = byGuild.get(guildId);
|
||||
if (music == null) {
|
||||
return null;
|
||||
}
|
||||
synchronized (music) {
|
||||
return music.current;
|
||||
}
|
||||
}
|
||||
|
||||
/** The Lavalink link for a guild, used by commands to load tracks. */
|
||||
public Link getLink(long guildId) {
|
||||
return lavalink.getOrCreateLink(guildId);
|
||||
}
|
||||
|
||||
/** How playback repeats: not at all, the current song, or the whole queue. */
|
||||
public enum LoopMode { OFF, SONG, QUEUE }
|
||||
|
||||
/** The guild's current loop mode (OFF if it has never played anything). */
|
||||
public LoopMode getLoopMode(long guildId) {
|
||||
GuildMusic music = byGuild.get(guildId);
|
||||
if (music == null) {
|
||||
return LoopMode.OFF;
|
||||
}
|
||||
synchronized (music) {
|
||||
return music.mode;
|
||||
}
|
||||
}
|
||||
|
||||
/** Sets the guild's loop mode and returns it. */
|
||||
public LoopMode setLoopMode(long guildId, LoopMode mode) {
|
||||
GuildMusic music = byGuild.computeIfAbsent(guildId, id -> new GuildMusic());
|
||||
synchronized (music) {
|
||||
music.mode = mode;
|
||||
return music.mode;
|
||||
}
|
||||
}
|
||||
|
||||
/** Toggles whole-queue looping: OFF (or SONG) turns it on, QUEUE turns it off. Returns the new mode. */
|
||||
public LoopMode toggleQueueLoop(long guildId) {
|
||||
GuildMusic music = byGuild.computeIfAbsent(guildId, id -> new GuildMusic());
|
||||
synchronized (music) {
|
||||
music.mode = (music.mode == LoopMode.QUEUE) ? LoopMode.OFF : LoopMode.QUEUE;
|
||||
return music.mode;
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds one track. Returns true if it started playing now, false if it was queued. */
|
||||
public boolean enqueue(long guildId, Track track) {
|
||||
GuildMusic music = byGuild.computeIfAbsent(guildId, id -> new GuildMusic());
|
||||
synchronized (music) {
|
||||
return enqueueLocked(guildId, music, track);
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds many tracks (a playlist). Returns true if the first track started playing now. */
|
||||
public boolean enqueueAll(long guildId, List<Track> tracks) {
|
||||
GuildMusic music = byGuild.computeIfAbsent(guildId, id -> new GuildMusic());
|
||||
synchronized (music) {
|
||||
boolean startedFirst = false;
|
||||
for (int i = 0; i < tracks.size(); i++) {
|
||||
boolean started = enqueueLocked(guildId, music, tracks.get(i));
|
||||
if (i == 0) {
|
||||
startedFirst = started;
|
||||
}
|
||||
}
|
||||
return startedFirst;
|
||||
}
|
||||
}
|
||||
|
||||
/** Skips the current track and starts the next one, if any. */
|
||||
public SkipResult skip(long guildId) {
|
||||
GuildMusic music = byGuild.computeIfAbsent(guildId, id -> new GuildMusic());
|
||||
synchronized (music) {
|
||||
if (music.current == null) {
|
||||
return new SkipResult(false, null);
|
||||
}
|
||||
return new SkipResult(true, advance(guildId, music, false));
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes all upcoming tracks without stopping the current one. Returns how many were removed. */
|
||||
public int clearQueue(long guildId) {
|
||||
GuildMusic music = byGuild.get(guildId);
|
||||
if (music == null) {
|
||||
return 0;
|
||||
}
|
||||
synchronized (music) {
|
||||
int removed = music.queue.size();
|
||||
music.queue.clear();
|
||||
return removed;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean enqueueLocked(long guildId, GuildMusic music, Track track) {
|
||||
if (music.current == null) {
|
||||
music.current = track;
|
||||
play(guildId, track);
|
||||
return true;
|
||||
}
|
||||
music.queue.add(track);
|
||||
return false;
|
||||
}
|
||||
|
||||
private void onTrackEnd(TrackEndEvent event) {
|
||||
// mayStartNext is false for REPLACED/STOPPED (which our own skip/replace
|
||||
// calls trigger) and true only when a track ended naturally or failed.
|
||||
if (!event.getEndReason().getMayStartNext()) {
|
||||
return;
|
||||
}
|
||||
GuildMusic music = byGuild.get(event.getGuildId());
|
||||
if (music == null) {
|
||||
return;
|
||||
}
|
||||
synchronized (music) {
|
||||
advance(event.getGuildId(), music, true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves to the next queued track (or stops if empty). Returns the new current
|
||||
* track, or null. Honours the guild's loop mode: SONG replays the finished
|
||||
* track when it ends on its own, QUEUE sends the finished/skipped track to the
|
||||
* back so the whole queue cycles. {@code naturalEnd} is true when a track ended
|
||||
* by itself and false for an explicit skip — a skip always moves on, even in
|
||||
* SONG mode.
|
||||
*/
|
||||
private Track advance(long guildId, GuildMusic music, boolean naturalEnd) {
|
||||
Track finished = music.current;
|
||||
if (music.mode == LoopMode.SONG && naturalEnd && finished != null) {
|
||||
play(guildId, finished);
|
||||
return finished;
|
||||
}
|
||||
if (music.mode == LoopMode.QUEUE && finished != null) {
|
||||
music.queue.add(finished);
|
||||
}
|
||||
Track next = music.queue.poll();
|
||||
music.current = next;
|
||||
if (next != null) {
|
||||
play(guildId, next);
|
||||
} else {
|
||||
lavalink.getOrCreateLink(guildId).createOrUpdatePlayer().stopTrack().subscribe();
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
private void play(long guildId, Track track) {
|
||||
lavalink.getOrCreateLink(guildId).createOrUpdatePlayer().setTrack(track).subscribe();
|
||||
}
|
||||
|
||||
/** Outcome of a skip: whether anything was playing, and the track now playing (may be null). */
|
||||
public record SkipResult(boolean somethingWasPlaying, Track nowPlaying) {
|
||||
}
|
||||
|
||||
private static final class GuildMusic {
|
||||
private final Deque<Track> queue = new ArrayDeque<>();
|
||||
private Track current;
|
||||
private LoopMode mode = LoopMode.OFF;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package dev.ksan.botinator.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* Static catalog of catchphrases, loaded from a text file at startup.
|
||||
* <p>
|
||||
* The file path comes from the {@code CATCHPHRASES_FILE} environment variable,
|
||||
* defaulting to {@code catchphrases.txt} in the working directory. One phrase per
|
||||
* line; blank lines and lines starting with {@code #} are ignored.
|
||||
* <p>
|
||||
* Getters: {@link #getOptimistic()} for a random phrase, or {@link #getOptimistic(int)}
|
||||
* for a specific one by index (any int; wrapped into range).
|
||||
*/
|
||||
public final class CatchPhrases {
|
||||
|
||||
private CatchPhrases() {
|
||||
}
|
||||
|
||||
// Used only if the file is missing or empty, so the getters never fail.
|
||||
private static final List<String> FALLBACK = List.of("...");
|
||||
|
||||
private static final List<String> OPTIMISTIC = load();
|
||||
|
||||
private static List<String> load() {
|
||||
String path = System.getenv().getOrDefault("CATCHPHRASES_FILE", "catchphrases.txt");
|
||||
try {
|
||||
List<String> phrases = Files.readAllLines(Path.of(path), StandardCharsets.UTF_8).stream()
|
||||
.map(String::trim)
|
||||
.filter(line -> !line.isEmpty() && !line.startsWith("#"))
|
||||
.toList();
|
||||
if (phrases.isEmpty()) {
|
||||
System.err.println("CatchPhrases: '" + path + "' has no phrases; using fallback.");
|
||||
return FALLBACK;
|
||||
}
|
||||
System.out.println("CatchPhrases: loaded " + phrases.size() + " phrase(s) from " + path);
|
||||
return phrases;
|
||||
} catch (IOException e) {
|
||||
System.err.println("CatchPhrases: couldn't read '" + path + "' ("
|
||||
+ e.getMessage() + "); using fallback.");
|
||||
return FALLBACK;
|
||||
}
|
||||
}
|
||||
|
||||
/** A random optimistic catchphrase. */
|
||||
public static String getOptimistic() {
|
||||
return pick(OPTIMISTIC, new Random());
|
||||
}
|
||||
|
||||
/** A specific optimistic catchphrase by index (any int; wrapped into range). */
|
||||
public static String getOptimistic(int index) {
|
||||
return pick(OPTIMISTIC, index);
|
||||
}
|
||||
|
||||
private static String pick(List<String> phrases, Random random) {
|
||||
return phrases.get(random.nextInt(phrases.size()));
|
||||
}
|
||||
|
||||
private static String pick(List<String> phrases, int index) {
|
||||
return phrases.get(Math.floorMod(index, phrases.size()));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user