From aee076c854ec3374b79f923014d7c06207057f9c Mon Sep 17 00:00:00 2001 From: John Grosh Date: Fri, 2 Sep 2022 21:56:19 -0400 Subject: [PATCH 01/24] add more sources --- pom.xml | 16 ++++++++++------ .../jagrosh/jmusicbot/audio/PlayerManager.java | 2 ++ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/pom.xml b/pom.xml index 9d5d06a24..d8a31ac47 100644 --- a/pom.xml +++ b/pom.xml @@ -25,6 +25,11 @@ always + + m2.duncte123.dev + m2-duncte123 + https://m2.duncte123.dev/releases + @@ -53,17 +58,16 @@ lavaplayer jmusicbot-SNAPSHOT - - com.github.jagrosh JLyrics master-SNAPSHOT + + com.dunctebot + sourcemanagers + 1.8.1 + diff --git a/src/main/java/com/jagrosh/jmusicbot/audio/PlayerManager.java b/src/main/java/com/jagrosh/jmusicbot/audio/PlayerManager.java index ec4721950..f4a5605ce 100644 --- a/src/main/java/com/jagrosh/jmusicbot/audio/PlayerManager.java +++ b/src/main/java/com/jagrosh/jmusicbot/audio/PlayerManager.java @@ -15,6 +15,7 @@ */ package com.jagrosh.jmusicbot.audio; +import com.dunctebot.sourcemanagers.DuncteBotSources; import com.jagrosh.jmusicbot.Bot; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager; @@ -40,6 +41,7 @@ public void init() TransformativeAudioSourceManager.createTransforms(bot.getConfig().getTransforms()).forEach(t -> registerSourceManager(t)); AudioSourceManagers.registerRemoteSources(this); AudioSourceManagers.registerLocalSource(this); + DuncteBotSources.registerAll(this, "en-US"); source(YoutubeAudioSourceManager.class).setPlaylistPageCount(10); } From 0e1f0d3bfa70123a40ba633395842472eb28b0e5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 5 Dec 2023 22:17:47 +0000 Subject: [PATCH 02/24] Bump ch.qos.logback:logback-classic from 1.2.3 to 1.2.13 Bumps [ch.qos.logback:logback-classic](https://github.com/qos-ch/logback) from 1.2.3 to 1.2.13. - [Commits](https://github.com/qos-ch/logback/compare/v_1.2.3...v_1.2.13) --- updated-dependencies: - dependency-name: ch.qos.logback:logback-classic dependency-type: direct:production ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b5b4cf6fe..8edd0973a 100644 --- a/pom.xml +++ b/pom.xml @@ -69,7 +69,7 @@ ch.qos.logback logback-classic - 1.2.3 + 1.2.13 com.typesafe From cd7e643228523026891534f2065bb7f04874109b Mon Sep 17 00:00:00 2001 From: Michail Date: Sat, 10 Feb 2024 23:10:07 +0100 Subject: [PATCH 03/24] Possible workaround for Eval command failing --- src/main/java/com/jagrosh/jmusicbot/commands/owner/EvalCmd.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/com/jagrosh/jmusicbot/commands/owner/EvalCmd.java b/src/main/java/com/jagrosh/jmusicbot/commands/owner/EvalCmd.java index 4c50d7d34..a5ad59e9d 100644 --- a/src/main/java/com/jagrosh/jmusicbot/commands/owner/EvalCmd.java +++ b/src/main/java/com/jagrosh/jmusicbot/commands/owner/EvalCmd.java @@ -45,8 +45,6 @@ protected void execute(CommandEvent event) se.put("bot", bot); se.put("event", event); se.put("jda", event.getJDA()); - se.put("guild", event.getGuild()); - se.put("channel", event.getChannel()); try { event.reply(event.getClient().getSuccess()+" Evaluated Successfully:\n```\n"+se.eval(event.getArgs())+" ```"); From 53875f27917b0318e3b99bd6e06e09c8a7c82331 Mon Sep 17 00:00:00 2001 From: Michail Date: Sat, 10 Feb 2024 23:25:11 +0100 Subject: [PATCH 04/24] Properly fix eval command failing in DMs --- .../java/com/jagrosh/jmusicbot/commands/owner/EvalCmd.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/com/jagrosh/jmusicbot/commands/owner/EvalCmd.java b/src/main/java/com/jagrosh/jmusicbot/commands/owner/EvalCmd.java index a5ad59e9d..1a7f0294c 100644 --- a/src/main/java/com/jagrosh/jmusicbot/commands/owner/EvalCmd.java +++ b/src/main/java/com/jagrosh/jmusicbot/commands/owner/EvalCmd.java @@ -20,6 +20,7 @@ import com.jagrosh.jdautilities.command.CommandEvent; import com.jagrosh.jmusicbot.Bot; import com.jagrosh.jmusicbot.commands.OwnerCommand; +import net.dv8tion.jda.api.entities.ChannelType; /** * @@ -45,6 +46,10 @@ protected void execute(CommandEvent event) se.put("bot", bot); se.put("event", event); se.put("jda", event.getJDA()); + if (event.getChannelType() != ChannelType.PRIVATE) { + se.put("guild", event.getGuild()); + se.put("channel", event.getChannel()); + } try { event.reply(event.getClient().getSuccess()+" Evaluated Successfully:\n```\n"+se.eval(event.getArgs())+" ```"); From 2d4f2671c980fe6b546cfb23527ce62fbdd99ba3 Mon Sep 17 00:00:00 2001 From: Michail Date: Wed, 28 Feb 2024 21:01:08 +0100 Subject: [PATCH 05/24] Don't warn about failing to load server settings when the file isn't found --- .../java/com/jagrosh/jmusicbot/settings/SettingsManager.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/jagrosh/jmusicbot/settings/SettingsManager.java b/src/main/java/com/jagrosh/jmusicbot/settings/SettingsManager.java index 4a70a0fba..3961907b2 100644 --- a/src/main/java/com/jagrosh/jmusicbot/settings/SettingsManager.java +++ b/src/main/java/com/jagrosh/jmusicbot/settings/SettingsManager.java @@ -57,8 +57,10 @@ public SettingsManager() o.has("prefix") ? o.getString("prefix") : null, o.has("skip_ratio") ? o.getDouble("skip_ratio") : SKIP_RATIO)); }); + } catch (NoSuchFileException e) { + // ignore, it just means no settings have been saved yet } catch(IOException | JSONException e) { - LoggerFactory.getLogger("Settings").warn("Failed to load server settings (this is normal if no settings have been set yet): "+e); + LoggerFactory.getLogger("Settings").warn("Failed to load server settings: "+e); } } From 90d9a1631a977bc99b8a4e49a72b7cf20c385a8f Mon Sep 17 00:00:00 2001 From: Michail Date: Wed, 28 Feb 2024 21:33:10 +0100 Subject: [PATCH 06/24] Create a new serversettings.json file if one doesn't exist --- .../jagrosh/jmusicbot/settings/SettingsManager.java | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/jagrosh/jmusicbot/settings/SettingsManager.java b/src/main/java/com/jagrosh/jmusicbot/settings/SettingsManager.java index 3961907b2..3cd02cf59 100644 --- a/src/main/java/com/jagrosh/jmusicbot/settings/SettingsManager.java +++ b/src/main/java/com/jagrosh/jmusicbot/settings/SettingsManager.java @@ -19,6 +19,7 @@ import com.jagrosh.jmusicbot.utils.OtherUtil; import java.io.IOException; import java.nio.file.Files; +import java.nio.file.NoSuchFileException; import java.util.HashMap; import net.dv8tion.jda.api.entities.Guild; import org.json.JSONException; @@ -58,10 +59,19 @@ public SettingsManager() o.has("skip_ratio") ? o.getDouble("skip_ratio") : SKIP_RATIO)); }); } catch (NoSuchFileException e) { - // ignore, it just means no settings have been saved yet + // create an empty json file + try { + LoggerFactory.getLogger("Settings").info("serversettings.json will be created in " + OtherUtil.getPath("serversettings.json").toAbsolutePath()); + Files.write(OtherUtil.getPath("serversettings.json"), new JSONObject().toString(4).getBytes()); + } catch(IOException ex) { + LoggerFactory.getLogger("Settings").warn("Failed to create new settings file: "+ex); + } + return; } catch(IOException | JSONException e) { LoggerFactory.getLogger("Settings").warn("Failed to load server settings: "+e); } + + LoggerFactory.getLogger("Settings").info("serversettings.json loaded from " + OtherUtil.getPath("serversettings.json").toAbsolutePath()); } /** From ff1ede9d128974ca7f9243989facece3c1b107fd Mon Sep 17 00:00:00 2001 From: Michail Date: Wed, 28 Feb 2024 21:33:45 +0100 Subject: [PATCH 07/24] Log "loaded config" message again after successfully initializing the GUI --- src/main/java/com/jagrosh/jmusicbot/JMusicBot.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java b/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java index 69248fc88..d11f6ac8a 100644 --- a/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java +++ b/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java @@ -165,8 +165,10 @@ else if(config.getGame().getName().equalsIgnoreCase("none")) GUI gui = new GUI(bot); bot.setGUI(gui); gui.init(); - } - catch(Exception e) + + LOG.info("Loaded config from " + config.getConfigLocation()); + } + catch(Exception e) { LOG.error("Could not start GUI. If you are " + "running on a server or in a location where you cannot display a " From fa5e33e2a526894e1bfbf60eab3d451bd65f2c5e Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 1 Mar 2024 17:53:08 -0500 Subject: [PATCH 08/24] fix formatting and nulls in metadata --- src/main/java/com/jagrosh/jmusicbot/audio/QueuedTrack.java | 4 ++-- src/main/java/com/jagrosh/jmusicbot/queue/FairQueue.java | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/jagrosh/jmusicbot/audio/QueuedTrack.java b/src/main/java/com/jagrosh/jmusicbot/audio/QueuedTrack.java index 02ae1559c..546d62ef4 100644 --- a/src/main/java/com/jagrosh/jmusicbot/audio/QueuedTrack.java +++ b/src/main/java/com/jagrosh/jmusicbot/audio/QueuedTrack.java @@ -37,13 +37,13 @@ public QueuedTrack(AudioTrack track, User owner) public QueuedTrack(AudioTrack track, RequestMetadata rm) { this.track = track; - this.track.setUserData(rm); + this.track.setUserData(rm == null ? RequestMetadata.EMPTY : rm); } @Override public long getIdentifier() { - return track.getUserData(RequestMetadata.class).getOwner(); + return track.getUserData() == null ? 0L : track.getUserData(RequestMetadata.class).getOwner(); } public AudioTrack getTrack() diff --git a/src/main/java/com/jagrosh/jmusicbot/queue/FairQueue.java b/src/main/java/com/jagrosh/jmusicbot/queue/FairQueue.java index 66106178a..b19eb44c2 100644 --- a/src/main/java/com/jagrosh/jmusicbot/queue/FairQueue.java +++ b/src/main/java/com/jagrosh/jmusicbot/queue/FairQueue.java @@ -25,7 +25,8 @@ * @author John Grosh (jagrosh) * @param */ -public class FairQueue { +public class FairQueue +{ private final List list = new ArrayList<>(); private final Set set = new HashSet<>(); @@ -33,7 +34,7 @@ public int add(T item) { int lastIndex; for(lastIndex=list.size()-1; lastIndex>-1; lastIndex--) - if(list.get(lastIndex).getIdentifier()==item.getIdentifier()) + if(list.get(lastIndex).getIdentifier() == item.getIdentifier()) break; lastIndex++; set.clear(); From a52103620a8ae7d9d1c87703edaebe9805827167 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 1 Mar 2024 18:00:02 -0500 Subject: [PATCH 09/24] update version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7568e16cf..baddabf54 100644 --- a/pom.xml +++ b/pom.xml @@ -66,7 +66,7 @@ com.dunctebot sourcemanagers - 1.8.1 + 1.9.0 From c5ecf89852d3d6f310e34bc9595aaa0bd4ba7460 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 1 Mar 2024 18:04:26 -0500 Subject: [PATCH 10/24] switch to java 11 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index baddabf54..04f5444ae 100644 --- a/pom.xml +++ b/pom.xml @@ -145,7 +145,7 @@ UTF-8 - 1.8 - 1.8 + 11 + 11 From 4f926baf76590e8947d5e1715fb035a58c7456df Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 1 Mar 2024 18:08:46 -0500 Subject: [PATCH 11/24] update circleci settings --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 84e8cc3ee..4db8c6045 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -7,7 +7,7 @@ jobs: build: docker: # specify the version you desire here - - image: circleci/openjdk:8u171-jdk + - image: cimg/openjdk:11.0 # Specify service dependencies here if necessary # CircleCI maintains a library of pre-built images From 4c8ff655d8fe9444e1a4779126ce16c7d7d3d297 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 1 Mar 2024 18:26:10 -0500 Subject: [PATCH 12/24] update github actions to jdk 11 --- .github/workflows/make-release.yml | 4 ++-- .github/workflows/test.yml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/make-release.yml b/.github/workflows/make-release.yml index dc71379f5..ce1f58be9 100644 --- a/.github/workflows/make-release.yml +++ b/.github/workflows/make-release.yml @@ -18,10 +18,10 @@ jobs: steps: - name: Checkout uses: actions/checkout@v2 - - name: Set up JDK 8 + - name: Set up JDK 11 uses: actions/setup-java@v2 with: - java-version: '8' + java-version: '11' distribution: 'adopt' cache: maven - name: Set Version diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 9ac3377bb..12fbc4bb7 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -9,10 +9,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - name: Set up JDK 8 + - name: Set up JDK 11 uses: actions/setup-java@v2 with: - java-version: '8' + java-version: '11' distribution: 'adopt' cache: maven - name: Build with Maven From 18bf6ac0f633e2883ceb1da0d11568c28b989322 Mon Sep 17 00:00:00 2001 From: Michaili K Date: Sat, 2 Mar 2024 01:19:18 +0100 Subject: [PATCH 13/24] Remove channel topic info (#1485) * Remove channel topic info As Discord has severely increased the ratelimits for updating the channel topic, updating the channel topic has become not viable for bots. * fix compilation error --------- Co-authored-by: unknown --- src/main/java/com/jagrosh/jmusicbot/Bot.java | 1 - .../java/com/jagrosh/jmusicbot/JMusicBot.java | 2 +- .../jagrosh/jmusicbot/audio/AudioHandler.java | 24 ++--------- .../jmusicbot/audio/NowplayingHandler.java | 40 +------------------ 4 files changed, 6 insertions(+), 61 deletions(-) diff --git a/src/main/java/com/jagrosh/jmusicbot/Bot.java b/src/main/java/com/jagrosh/jmusicbot/Bot.java index b2f8f33e4..de6d6f756 100644 --- a/src/main/java/com/jagrosh/jmusicbot/Bot.java +++ b/src/main/java/com/jagrosh/jmusicbot/Bot.java @@ -139,7 +139,6 @@ public void shutdown() { ah.stopAndClear(); ah.getPlayer().destroy(); - nowplaying.updateTopic(g.getIdLong(), ah, true); } }); jda.shutdown(); diff --git a/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java b/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java index d11f6ac8a..7879b9244 100644 --- a/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java +++ b/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java @@ -47,7 +47,7 @@ public class JMusicBot public final static Logger LOG = LoggerFactory.getLogger(JMusicBot.class); public final static Permission[] RECOMMENDED_PERMS = {Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, Permission.MESSAGE_HISTORY, Permission.MESSAGE_ADD_REACTION, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_ATTACH_FILES, Permission.MESSAGE_MANAGE, Permission.MESSAGE_EXT_EMOJI, - Permission.MANAGE_CHANNEL, Permission.VOICE_CONNECT, Permission.VOICE_SPEAK, Permission.NICKNAME_CHANGE}; + Permission.VOICE_CONNECT, Permission.VOICE_SPEAK, Permission.NICKNAME_CHANGE}; public final static GatewayIntent[] INTENTS = {GatewayIntent.DIRECT_MESSAGES, GatewayIntent.GUILD_MESSAGES, GatewayIntent.GUILD_MESSAGE_REACTIONS, GatewayIntent.GUILD_VOICE_STATES}; /** diff --git a/src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java b/src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java index b2ca7179d..fc1902b7d 100644 --- a/src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java +++ b/src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java @@ -15,7 +15,6 @@ */ package com.jagrosh.jmusicbot.audio; -import com.jagrosh.jmusicbot.JMusicBot; import com.jagrosh.jmusicbot.playlist.PlaylistLoader.Playlist; import com.jagrosh.jmusicbot.settings.RepeatMode; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; @@ -175,7 +174,7 @@ public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason { if(!playFromDefault()) { - manager.getBot().getNowplayingHandler().onTrackUpdate(guildId, null, this); + manager.getBot().getNowplayingHandler().onTrackUpdate(null); if(!manager.getBot().getConfig().getStay()) manager.getBot().closeAudioConnection(guildId); // unpause, in the case when the player was paused and the track has been skipped. @@ -194,7 +193,7 @@ public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason public void onTrackStart(AudioPlayer player, AudioTrack track) { votes.clear(); - manager.getBot().getNowplayingHandler().onTrackUpdate(guildId, track, this); + manager.getBot().getNowplayingHandler().onTrackUpdate(track); } @@ -258,24 +257,7 @@ public Message getNoMusicPlaying(JDA jda) .setColor(guild.getSelfMember().getColor()) .build()).build(); } - - public String getTopicFormat(JDA jda) - { - if(isMusicPlaying(jda)) - { - long userid = getRequestMetadata().getOwner(); - AudioTrack track = audioPlayer.getPlayingTrack(); - String title = track.getInfo().title; - if(title==null || title.equals("Unknown Title")) - title = track.getInfo().uri; - return "**"+title+"** ["+(userid==0 ? "autoplay" : "<@"+userid+">")+"]" - + "\n" + getStatusEmoji() + " " - + "[" + FormatUtil.formatTime(track.getDuration()) + "] " - + FormatUtil.volumeIcon(audioPlayer.getVolume()); - } - else return "No music playing " + STOP_EMOJI + " " + FormatUtil.volumeIcon(audioPlayer.getVolume()); - } - + public String getStatusEmoji() { return audioPlayer.isPaused() ? PAUSE_EMOJI : PLAY_EMOJI; diff --git a/src/main/java/com/jagrosh/jmusicbot/audio/NowplayingHandler.java b/src/main/java/com/jagrosh/jmusicbot/audio/NowplayingHandler.java index 5d96e7df9..e09e3e643 100644 --- a/src/main/java/com/jagrosh/jmusicbot/audio/NowplayingHandler.java +++ b/src/main/java/com/jagrosh/jmusicbot/audio/NowplayingHandler.java @@ -98,42 +98,9 @@ private void updateAll() } toRemove.forEach(id -> lastNP.remove(id)); } - - public void updateTopic(long guildId, AudioHandler handler, boolean wait) - { - Guild guild = bot.getJDA().getGuildById(guildId); - if(guild==null) - return; - Settings settings = bot.getSettingsManager().getSettings(guildId); - TextChannel tchan = settings.getTextChannel(guild); - if(tchan!=null && guild.getSelfMember().hasPermission(tchan, Permission.MANAGE_CHANNEL)) - { - String otherText; - String topic = tchan.getTopic(); - if(topic==null || topic.isEmpty()) - otherText = "\u200B"; - else if(topic.contains("\u200B")) - otherText = topic.substring(topic.lastIndexOf("\u200B")); - else - otherText = "\u200B\n "+topic; - String text = handler.getTopicFormat(bot.getJDA()) + otherText; - if(!text.equals(tchan.getTopic())) - { - try - { - // normally here if 'wait' was false, we'd want to queue, however, - // new discord ratelimits specifically limiting changing channel topics - // mean we don't want a backlog of changes piling up, so if we hit a - // ratelimit, we just won't change the topic this time - tchan.getManager().setTopic(text).complete(wait); - } - catch(PermissionException | RateLimitedException ignore) {} - } - } - } - + // "event"-based methods - public void onTrackUpdate(long guildId, AudioTrack track, AudioHandler handler) + public void onTrackUpdate(AudioTrack track) { // update bot status if applicable if(bot.getConfig().getSongInStatus()) @@ -143,9 +110,6 @@ public void onTrackUpdate(long guildId, AudioTrack track, AudioHandler handler) else bot.resetGame(); } - - // update channel topic if applicable - updateTopic(guildId, handler, false); } public void onMessageDelete(Guild guild, long messageId) From 23c2dfa78e402b5737cbc4b2c8ca9faa0fc74ed3 Mon Sep 17 00:00:00 2001 From: Michaili K Date: Sat, 2 Mar 2024 01:26:58 +0100 Subject: [PATCH 14/24] Make JMusicBot error & shut down if ran in an unsupported manner (#1486) * Make JMusicBot error & shut down if ran in an unsupported manner * add info about message content intent * five second rule --------- Co-authored-by: unknown --- .../java/com/jagrosh/jmusicbot/JMusicBot.java | 20 +++++++++++++++++++ .../jagrosh/jmusicbot/utils/OtherUtil.java | 20 +++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java b/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java index 7879b9244..f4dea7121 100644 --- a/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java +++ b/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java @@ -189,6 +189,26 @@ else if(config.getGame().getName().equalsIgnoreCase("none")) .setBulkDeleteSplittingEnabled(true) .build(); bot.setJDA(jda); + + // check if something about the current startup is not supported + String unsupportedReason = OtherUtil.getUnsupportedBotReason(jda); + if (unsupportedReason != null) + { + prompt.alert(Prompt.Level.ERROR, "JMusicBot", "JMusicBot cannot be run on this Discord bot: " + unsupportedReason); + try{ Thread.sleep(5000);}catch(InterruptedException ignored){} // this is awful but until we have a better way... + jda.shutdown(); + System.exit(1); + } + + // other check that will just be a warning now but may be required in the future + // check if the user has changed the prefix and provide info about the + // message content intent + if(!"@mention".equals(config.getPrefix())) + { + prompt.alert(Prompt.Level.INFO, "JMusicBot", "You currently have a custom prefix set. " + + "If your prefix is not working, make sure that the 'MESSAGE CONTENT INTENT' is Enabled " + + "on https://discord.com/developers/applications/" + jda.getSelfUser().getId() + "/bot"); + } } catch (LoginException ex) { diff --git a/src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java b/src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java index 67abe4ee8..63c39ce4b 100644 --- a/src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java +++ b/src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java @@ -23,8 +23,12 @@ import java.net.URLConnection; import java.nio.file.Path; import java.nio.file.Paths; + +import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.OnlineStatus; import net.dv8tion.jda.api.entities.Activity; +import net.dv8tion.jda.api.entities.ApplicationInfo; +import net.dv8tion.jda.api.entities.User; import okhttp3.*; import org.json.JSONException; import org.json.JSONObject; @@ -207,4 +211,20 @@ public static String getLatestVersion() return null; } } + + /** + * Checks if the bot JMusicBot is being run on is supported & returns the reason if it is not. + * @return A string with the reason, or null if it is supported. + */ + public static String getUnsupportedBotReason(JDA jda) + { + if (jda.getSelfUser().getFlags().contains(User.UserFlag.VERIFIED_BOT)) + return "The bot is verified. Using JMusicBot in a verified bot is not supported."; + + ApplicationInfo info = jda.retrieveApplicationInfo().complete(); + if (info.isBotPublic()) + return "\"Public Bot\" is enabled. Using JMusicBot as a public bot is not supported. Please disable it in the Developer Dashboard."; + + return null; + } } From 8a1066cc8718d72ddc5bf8c8b6f60e79deca4859 Mon Sep 17 00:00:00 2001 From: Kevin S Date: Fri, 1 Mar 2024 16:42:39 -0800 Subject: [PATCH 15/24] Allow configurable default skip ratio (#1140) * Allow configurable default skip ratio Revert "Allow configurable default skip ratio" This reverts commit 10e38b4132ee2b28fb583603d69e6228da211ecd. * FIX: Use -1 to denote a guild has not set a skip ratio, and opted to use the bot default. --- src/main/java/com/jagrosh/jmusicbot/BotConfig.java | 7 +++++++ .../com/jagrosh/jmusicbot/commands/music/SkipCmd.java | 8 ++++++-- .../com/jagrosh/jmusicbot/settings/SettingsManager.java | 8 ++++---- src/main/resources/reference.conf | 7 +++++++ 4 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/jagrosh/jmusicbot/BotConfig.java b/src/main/java/com/jagrosh/jmusicbot/BotConfig.java index 1e1b6c100..53a155b31 100644 --- a/src/main/java/com/jagrosh/jmusicbot/BotConfig.java +++ b/src/main/java/com/jagrosh/jmusicbot/BotConfig.java @@ -43,6 +43,7 @@ public class BotConfig successEmoji, warningEmoji, errorEmoji, loadingEmoji, searchingEmoji; private boolean stayInChannel, songInGame, npImages, updatealerts, useEval, dbots; private long owner, maxSeconds, aloneTimeUntilStop; + private double skipratio; private OnlineStatus status; private Activity game; private Config aliases, transforms; @@ -91,6 +92,7 @@ public void load() playlistsFolder = config.getString("playlistsfolder"); aliases = config.getConfig("aliases"); transforms = config.getConfig("transforms"); + skipratio = config.getDouble("skipratio"); dbots = owner == 113156185389092864L; // we may need to write a new config file @@ -231,6 +233,11 @@ public String getToken() return token; } + public double getSkipRatio() + { + return skipratio; + } + public long getOwnerId() { return owner; diff --git a/src/main/java/com/jagrosh/jmusicbot/commands/music/SkipCmd.java b/src/main/java/com/jagrosh/jmusicbot/commands/music/SkipCmd.java index ec08ab02d..3992287c8 100644 --- a/src/main/java/com/jagrosh/jmusicbot/commands/music/SkipCmd.java +++ b/src/main/java/com/jagrosh/jmusicbot/commands/music/SkipCmd.java @@ -42,7 +42,11 @@ public void doCommand(CommandEvent event) { AudioHandler handler = (AudioHandler)event.getGuild().getAudioManager().getSendingHandler(); RequestMetadata rm = handler.getRequestMetadata(); - if(event.getAuthor().getIdLong() == rm.getOwner()) + double skipRatio = bot.getSettingsManager().getSettings(event.getGuild()).getSkipRatio(); + if(skipRatio == -1) { + skipRatio = bot.getConfig().getSkipRatio(); + } + if(event.getAuthor().getIdLong() == rm.getOwner() || skipRatio == 0) { event.reply(event.getClient().getSuccess()+" Skipped **"+handler.getPlayer().getPlayingTrack().getInfo().title+"**"); handler.getPlayer().stopTrack(); @@ -61,7 +65,7 @@ public void doCommand(CommandEvent event) } int skippers = (int)event.getSelfMember().getVoiceState().getChannel().getMembers().stream() .filter(m -> handler.getVotes().contains(m.getUser().getId())).count(); - int required = (int)Math.ceil(listeners * bot.getSettingsManager().getSettings(event.getGuild()).getSkipRatio()); + int required = (int)Math.ceil(listeners * skipRatio); msg += skippers + " votes, " + required + "/" + listeners + " needed]`"; if(skippers>=required) { diff --git a/src/main/java/com/jagrosh/jmusicbot/settings/SettingsManager.java b/src/main/java/com/jagrosh/jmusicbot/settings/SettingsManager.java index 3cd02cf59..27a198b46 100644 --- a/src/main/java/com/jagrosh/jmusicbot/settings/SettingsManager.java +++ b/src/main/java/com/jagrosh/jmusicbot/settings/SettingsManager.java @@ -32,12 +32,12 @@ */ public class SettingsManager implements GuildSettingsManager { - private final static double SKIP_RATIO = .55; private final HashMap settings; public SettingsManager() { this.settings = new HashMap<>(); + try { JSONObject loadedSettings = new JSONObject(new String(Files.readAllBytes(OtherUtil.getPath("serversettings.json")))); loadedSettings.keySet().forEach((id) -> { @@ -56,7 +56,7 @@ public SettingsManager() o.has("default_playlist")? o.getString("default_playlist") : null, o.has("repeat_mode") ? o.getEnum(RepeatMode.class, "repeat_mode"): RepeatMode.OFF, o.has("prefix") ? o.getString("prefix") : null, - o.has("skip_ratio") ? o.getDouble("skip_ratio") : SKIP_RATIO)); + o.has("skip_ratio") ? o.getDouble("skip_ratio") : -1)); }); } catch (NoSuchFileException e) { // create an empty json file @@ -93,7 +93,7 @@ public Settings getSettings(long guildId) private Settings createDefaultSettings() { - return new Settings(this, 0, 0, 0, 100, null, RepeatMode.OFF, null, SKIP_RATIO); + return new Settings(this, 0, 0, 0, 100, null, RepeatMode.OFF, null, -1); } protected void writeSettings() @@ -116,7 +116,7 @@ protected void writeSettings() o.put("repeat_mode", s.getRepeatMode()); if(s.getPrefix() != null) o.put("prefix", s.getPrefix()); - if(s.getSkipRatio() != SKIP_RATIO) + if(s.getSkipRatio() != -1) o.put("skip_ratio", s.getSkipRatio()); obj.put(Long.toString(key), o); }); diff --git a/src/main/resources/reference.conf b/src/main/resources/reference.conf index b74103b3e..e48403f54 100644 --- a/src/main/resources/reference.conf +++ b/src/main/resources/reference.conf @@ -99,6 +99,13 @@ stayinchannel = false maxtime = 0 +// This sets the ratio of users that must vote to skip the currently playing song. +// Guild owners can define their own skip ratios, but this will be used if a guild +// has not defined their own skip ratio. + +skipratio = 0.55 + + // This sets the amount of seconds the bot will stay alone on a voice channel until it // automatically leaves the voice channel and clears the queue. If not set or set // to any number less than or equal to zero, the bot won't leave when alone. From bb53bad1ff95b2d14c65f5591581a5fbd602bb8a Mon Sep 17 00:00:00 2001 From: John Grosh Date: Fri, 1 Mar 2024 20:11:30 -0500 Subject: [PATCH 16/24] Update test.yml --- .github/workflows/test.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 12fbc4bb7..e6207fa0f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -3,6 +3,9 @@ on: push: branches: - master + pull_request: + branches: + - master jobs: build: From 1ad16181d07f2827d70b4d4b75494c1d51cf1179 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maoyue=20=E8=B2=93=E6=9C=88?= <95519633+MagicTeaMC@users.noreply.github.com> Date: Sun, 3 Mar 2024 08:39:16 +0800 Subject: [PATCH 17/24] Support new Discord username (#1397) * Support new username * Support new username, again * Make a separate username formatting function * Add some missing usage * switch away from using static imports, add shortcuts for jda User and metadata UserInfo, add null check --------- Co-authored-by: unknown --- .../jagrosh/jmusicbot/audio/AudioHandler.java | 4 ++-- .../jmusicbot/commands/dj/ForceRemoveCmd.java | 3 ++- .../jmusicbot/commands/dj/ForceskipCmd.java | 3 ++- .../jmusicbot/commands/music/SkipCmd.java | 3 ++- .../jagrosh/jmusicbot/utils/FormatUtil.java | 24 +++++++++++++++++++ 5 files changed, 32 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java b/src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java index fc1902b7d..8878b4166 100644 --- a/src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java +++ b/src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java @@ -213,9 +213,9 @@ public Message getNowPlaying(JDA jda) { User u = guild.getJDA().getUserById(rm.user.id); if(u==null) - eb.setAuthor(rm.user.username + "#" + rm.user.discrim, null, rm.user.avatar); + eb.setAuthor(FormatUtil.formatUsername(rm.user), null, rm.user.avatar); else - eb.setAuthor(u.getName() + "#" + u.getDiscriminator(), null, u.getEffectiveAvatarUrl()); + eb.setAuthor(FormatUtil.formatUsername(u), null, u.getEffectiveAvatarUrl()); } try diff --git a/src/main/java/com/jagrosh/jmusicbot/commands/dj/ForceRemoveCmd.java b/src/main/java/com/jagrosh/jmusicbot/commands/dj/ForceRemoveCmd.java index 53594cda0..897b1c4bd 100644 --- a/src/main/java/com/jagrosh/jmusicbot/commands/dj/ForceRemoveCmd.java +++ b/src/main/java/com/jagrosh/jmusicbot/commands/dj/ForceRemoveCmd.java @@ -21,6 +21,7 @@ import com.jagrosh.jmusicbot.Bot; import com.jagrosh.jmusicbot.audio.AudioHandler; import com.jagrosh.jmusicbot.commands.DJCommand; +import com.jagrosh.jmusicbot.utils.FormatUtil; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.User; @@ -113,7 +114,7 @@ private void removeAllEntries(User target, CommandEvent event) } else { - event.replySuccess("Successfully removed `"+count+"` entries from **"+target.getName()+"**#"+target.getDiscriminator()+"."); + event.replySuccess("Successfully removed `"+count+"` entries from "+FormatUtil.formatUsername(target)+"."); } } } diff --git a/src/main/java/com/jagrosh/jmusicbot/commands/dj/ForceskipCmd.java b/src/main/java/com/jagrosh/jmusicbot/commands/dj/ForceskipCmd.java index f17ba9ea1..29b42a138 100644 --- a/src/main/java/com/jagrosh/jmusicbot/commands/dj/ForceskipCmd.java +++ b/src/main/java/com/jagrosh/jmusicbot/commands/dj/ForceskipCmd.java @@ -20,6 +20,7 @@ import com.jagrosh.jmusicbot.audio.AudioHandler; import com.jagrosh.jmusicbot.audio.RequestMetadata; import com.jagrosh.jmusicbot.commands.DJCommand; +import com.jagrosh.jmusicbot.utils.FormatUtil; /** * @@ -42,7 +43,7 @@ public void doCommand(CommandEvent event) AudioHandler handler = (AudioHandler)event.getGuild().getAudioManager().getSendingHandler(); RequestMetadata rm = handler.getRequestMetadata(); event.reply(event.getClient().getSuccess()+" Skipped **"+handler.getPlayer().getPlayingTrack().getInfo().title - +"** "+(rm.getOwner() == 0L ? "(autoplay)" : "(requested by **" + rm.user.username + "**)")); + +"** "+(rm.getOwner() == 0L ? "(autoplay)" : "(requested by **" + FormatUtil.formatUsername(rm.user) + "**)")); handler.getPlayer().stopTrack(); } } diff --git a/src/main/java/com/jagrosh/jmusicbot/commands/music/SkipCmd.java b/src/main/java/com/jagrosh/jmusicbot/commands/music/SkipCmd.java index 3992287c8..875d21299 100644 --- a/src/main/java/com/jagrosh/jmusicbot/commands/music/SkipCmd.java +++ b/src/main/java/com/jagrosh/jmusicbot/commands/music/SkipCmd.java @@ -20,6 +20,7 @@ import com.jagrosh.jmusicbot.audio.AudioHandler; import com.jagrosh.jmusicbot.audio.RequestMetadata; import com.jagrosh.jmusicbot.commands.MusicCommand; +import com.jagrosh.jmusicbot.utils.FormatUtil; /** * @@ -70,7 +71,7 @@ public void doCommand(CommandEvent event) if(skippers>=required) { msg += "\n" + event.getClient().getSuccess() + " Skipped **" + handler.getPlayer().getPlayingTrack().getInfo().title - + "** " + (rm.getOwner() == 0L ? "(autoplay)" : "(requested by **" + rm.user.username + "**)"); + + "** " + (rm.getOwner() == 0L ? "(autoplay)" : "(requested by **" + FormatUtil.formatUsername(rm.user) + "**)"); handler.getPlayer().stopTrack(); } event.reply(msg); diff --git a/src/main/java/com/jagrosh/jmusicbot/utils/FormatUtil.java b/src/main/java/com/jagrosh/jmusicbot/utils/FormatUtil.java index 53d7d0401..709be7437 100644 --- a/src/main/java/com/jagrosh/jmusicbot/utils/FormatUtil.java +++ b/src/main/java/com/jagrosh/jmusicbot/utils/FormatUtil.java @@ -15,9 +15,11 @@ */ package com.jagrosh.jmusicbot.utils; +import com.jagrosh.jmusicbot.audio.RequestMetadata.UserInfo; import java.util.List; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.TextChannel; +import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.VoiceChannel; /** @@ -37,6 +39,28 @@ public static String formatTime(long duration) seconds %= 60; return (hours>0 ? hours+":" : "") + (minutes<10 ? "0"+minutes : minutes) + ":" + (seconds<10 ? "0"+seconds : seconds); } + + public static String formatUsername(String username, String discrim) + { + if(discrim == null || discrim.equals("0000")) + { + return username; + } + else + { + return username + "#" + discrim; + } + } + + public static String formatUsername(UserInfo userinfo) + { + return formatUsername(userinfo.username, userinfo.discrim); + } + + public static String formatUsername(User user) + { + return formatUsername(user.getName(), user.getDiscriminator()); + } public static String progressBar(double percent) { From 2e9dd5df499f4c794f29d6f685af8fbb84ba1c0e Mon Sep 17 00:00:00 2001 From: Wolfgang Schwendtbauer Date: Tue, 5 Mar 2024 00:49:01 +0100 Subject: [PATCH 18/24] add LinearQueue (#1194) * add LinearQueue * rework queueType to be server-specific * rework QueueType enum and command * add QueueType supplier * fix queue type formatting * add QueueSupplier util * fix code issues * Fix unit tests * add suggested changes on PR --------- Co-authored-by: Michaili K Co-authored-by: Michail --- .../java/com/jagrosh/jmusicbot/JMusicBot.java | 3 +- .../jagrosh/jmusicbot/audio/AudioHandler.java | 16 ++- .../commands/admin/QueueTypeCmd.java | 75 ++++++++++ .../jmusicbot/commands/dj/MoveTrackCmd.java | 6 +- .../commands/general/SettingsCmd.java | 4 + .../jmusicbot/commands/music/QueueCmd.java | 9 +- .../jmusicbot/queue/AbstractQueue.java | 130 ++++++++++++++++++ .../jagrosh/jmusicbot/queue/FairQueue.java | 109 ++------------- .../jagrosh/jmusicbot/queue/LinearQueue.java | 37 +++++ .../jmusicbot/queue/QueueSupplier.java | 26 ++++ .../jagrosh/jmusicbot/settings/QueueType.java | 69 ++++++++++ .../jagrosh/jmusicbot/settings/Settings.java | 18 ++- .../jmusicbot/settings/SettingsManager.java | 24 ++-- src/main/resources/reference.conf | 1 + .../com/jagrosh/jmusicbot/FairQueueTest.java | 4 +- 15 files changed, 405 insertions(+), 126 deletions(-) create mode 100644 src/main/java/com/jagrosh/jmusicbot/commands/admin/QueueTypeCmd.java create mode 100644 src/main/java/com/jagrosh/jmusicbot/queue/AbstractQueue.java create mode 100644 src/main/java/com/jagrosh/jmusicbot/queue/LinearQueue.java create mode 100644 src/main/java/com/jagrosh/jmusicbot/queue/QueueSupplier.java create mode 100644 src/main/java/com/jagrosh/jmusicbot/settings/QueueType.java diff --git a/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java b/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java index f4dea7121..a32a51048 100644 --- a/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java +++ b/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java @@ -129,11 +129,12 @@ private static void startBot() new VolumeCmd(bot), new PrefixCmd(bot), + new QueueTypeCmd(bot), new SetdjCmd(bot), new SkipratioCmd(bot), new SettcCmd(bot), new SetvcCmd(bot), - + new AutoplaylistCmd(bot), new DebugCmd(bot), new PlaylistCmd(bot), diff --git a/src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java b/src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java index 8878b4166..310389dbe 100644 --- a/src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java +++ b/src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java @@ -16,6 +16,8 @@ package com.jagrosh.jmusicbot.audio; import com.jagrosh.jmusicbot.playlist.PlaylistLoader.Playlist; +import com.jagrosh.jmusicbot.queue.AbstractQueue; +import com.jagrosh.jmusicbot.settings.QueueType; import com.jagrosh.jmusicbot.settings.RepeatMode; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; import com.sedmelluq.discord.lavaplayer.player.event.AudioEventAdapter; @@ -26,7 +28,6 @@ import java.util.LinkedList; import java.util.List; import java.util.Set; -import com.jagrosh.jmusicbot.queue.FairQueue; import com.jagrosh.jmusicbot.settings.Settings; import com.jagrosh.jmusicbot.utils.FormatUtil; import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioTrack; @@ -48,8 +49,7 @@ public class AudioHandler extends AudioEventAdapter implements AudioSendHandler public final static String PLAY_EMOJI = "\u25B6"; // ▶ public final static String PAUSE_EMOJI = "\u23F8"; // ⏸ public final static String STOP_EMOJI = "\u23F9"; // ⏹ - - private final FairQueue queue = new FairQueue<>(); + private final List defaultQueue = new LinkedList<>(); private final Set votes = new HashSet<>(); @@ -58,12 +58,20 @@ public class AudioHandler extends AudioEventAdapter implements AudioSendHandler private final long guildId; private AudioFrame lastFrame; + private AbstractQueue queue; protected AudioHandler(PlayerManager manager, Guild guild, AudioPlayer player) { this.manager = manager; this.audioPlayer = player; this.guildId = guild.getIdLong(); + + this.setQueueType(manager.getBot().getSettingsManager().getSettings(guildId).getQueueType()); + } + + public void setQueueType(QueueType type) + { + queue = type.createInstance(queue); } public int addTrackToFront(QueuedTrack qtrack) @@ -91,7 +99,7 @@ public int addTrack(QueuedTrack qtrack) return queue.add(qtrack); } - public FairQueue getQueue() + public AbstractQueue getQueue() { return queue; } diff --git a/src/main/java/com/jagrosh/jmusicbot/commands/admin/QueueTypeCmd.java b/src/main/java/com/jagrosh/jmusicbot/commands/admin/QueueTypeCmd.java new file mode 100644 index 000000000..798e620e6 --- /dev/null +++ b/src/main/java/com/jagrosh/jmusicbot/commands/admin/QueueTypeCmd.java @@ -0,0 +1,75 @@ +/* + * Copyright 2022 John Grosh . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.jagrosh.jmusicbot.commands.admin; + +import com.jagrosh.jdautilities.command.CommandEvent; +import com.jagrosh.jmusicbot.Bot; +import com.jagrosh.jmusicbot.audio.AudioHandler; +import com.jagrosh.jmusicbot.commands.AdminCommand; +import com.jagrosh.jmusicbot.settings.QueueType; +import com.jagrosh.jmusicbot.settings.Settings; + +/** + * + * @author Wolfgang Schwendtbauer + */ +public class QueueTypeCmd extends AdminCommand +{ + public QueueTypeCmd(Bot bot) + { + super(); + this.name = "queuetype"; + this.help = "changes the queue type"; + this.arguments = "[" + String.join("|", QueueType.getNames()) + "]"; + this.aliases = bot.getConfig().getAliases(this.name); + } + + @Override + protected void execute(CommandEvent event) + { + String args = event.getArgs(); + QueueType value; + Settings settings = event.getClient().getSettingsFor(event.getGuild()); + + if (args.isEmpty()) + { + QueueType currentType = settings.getQueueType(); + event.reply(currentType.getEmoji() + " Current queue type is: `" + currentType.getUserFriendlyName() + "`."); + return; + } + + try + { + value = QueueType.valueOf(args.toUpperCase()); + } + catch (IllegalArgumentException e) + { + event.replyError("Invalid queue type. Valid types are: [" + String.join("|", QueueType.getNames()) + "]"); + return; + } + + if (settings.getQueueType() != value) + { + settings.setQueueType(value); + + AudioHandler handler = (AudioHandler) event.getGuild().getAudioManager().getSendingHandler(); + if (handler != null) + handler.setQueueType(value); + } + + event.reply(value.getEmoji() + " Queue type was set to `" + value.getUserFriendlyName() + "`."); + } +} diff --git a/src/main/java/com/jagrosh/jmusicbot/commands/dj/MoveTrackCmd.java b/src/main/java/com/jagrosh/jmusicbot/commands/dj/MoveTrackCmd.java index 7c652f903..9199be01d 100644 --- a/src/main/java/com/jagrosh/jmusicbot/commands/dj/MoveTrackCmd.java +++ b/src/main/java/com/jagrosh/jmusicbot/commands/dj/MoveTrackCmd.java @@ -6,7 +6,7 @@ import com.jagrosh.jmusicbot.audio.AudioHandler; import com.jagrosh.jmusicbot.audio.QueuedTrack; import com.jagrosh.jmusicbot.commands.DJCommand; -import com.jagrosh.jmusicbot.queue.FairQueue; +import com.jagrosh.jmusicbot.queue.AbstractQueue; /** * Command that provides users the ability to move a track in the playlist. @@ -57,7 +57,7 @@ public void doCommand(CommandEvent event) // Validate that from and to are available AudioHandler handler = (AudioHandler) event.getGuild().getAudioManager().getSendingHandler(); - FairQueue queue = handler.getQueue(); + AbstractQueue queue = handler.getQueue(); if (isUnavailablePosition(queue, from)) { String reply = String.format("`%d` is not a valid position in the queue!", from); @@ -78,7 +78,7 @@ public void doCommand(CommandEvent event) event.replySuccess(reply); } - private static boolean isUnavailablePosition(FairQueue queue, int position) + private static boolean isUnavailablePosition(AbstractQueue queue, int position) { return (position < 1 || position > queue.size()); } diff --git a/src/main/java/com/jagrosh/jmusicbot/commands/general/SettingsCmd.java b/src/main/java/com/jagrosh/jmusicbot/commands/general/SettingsCmd.java index 94c411d88..a01398308 100644 --- a/src/main/java/com/jagrosh/jmusicbot/commands/general/SettingsCmd.java +++ b/src/main/java/com/jagrosh/jmusicbot/commands/general/SettingsCmd.java @@ -18,6 +18,7 @@ import com.jagrosh.jdautilities.command.Command; import com.jagrosh.jdautilities.command.CommandEvent; import com.jagrosh.jmusicbot.Bot; +import com.jagrosh.jmusicbot.settings.QueueType; import com.jagrosh.jmusicbot.settings.RepeatMode; import com.jagrosh.jmusicbot.settings.Settings; import com.jagrosh.jmusicbot.utils.FormatUtil; @@ -63,6 +64,9 @@ protected void execute(CommandEvent event) + "\nRepeat Mode: " + (s.getRepeatMode() == RepeatMode.OFF ? s.getRepeatMode().getUserFriendlyName() : "**"+s.getRepeatMode().getUserFriendlyName()+"**") + + "\nQueue Type: " + (s.getQueueType() == QueueType.FAIR + ? s.getQueueType().getUserFriendlyName() + : "**"+s.getQueueType().getUserFriendlyName()+"**") + "\nDefault Playlist: " + (s.getDefaultPlaylist() == null ? "None" : "**" + s.getDefaultPlaylist() + "**") ) .setFooter(event.getJDA().getGuilds().size() + " servers | " diff --git a/src/main/java/com/jagrosh/jmusicbot/commands/music/QueueCmd.java b/src/main/java/com/jagrosh/jmusicbot/commands/music/QueueCmd.java index 475d27410..2b18aaf4f 100644 --- a/src/main/java/com/jagrosh/jmusicbot/commands/music/QueueCmd.java +++ b/src/main/java/com/jagrosh/jmusicbot/commands/music/QueueCmd.java @@ -20,10 +20,10 @@ import com.jagrosh.jdautilities.command.CommandEvent; import com.jagrosh.jdautilities.menu.Paginator; import com.jagrosh.jmusicbot.Bot; -import com.jagrosh.jmusicbot.JMusicBot; import com.jagrosh.jmusicbot.audio.AudioHandler; import com.jagrosh.jmusicbot.audio.QueuedTrack; import com.jagrosh.jmusicbot.commands.MusicCommand; +import com.jagrosh.jmusicbot.settings.QueueType; import com.jagrosh.jmusicbot.settings.RepeatMode; import com.jagrosh.jmusicbot.settings.Settings; import com.jagrosh.jmusicbot.utils.FormatUtil; @@ -95,7 +95,7 @@ public void doCommand(CommandEvent event) } Settings settings = event.getClient().getSettingsFor(event.getGuild()); long fintotal = total; - builder.setText((i1,i2) -> getQueueTitle(ah, event.getClient().getSuccess(), songs.length, fintotal, settings.getRepeatMode())) + builder.setText((i1,i2) -> getQueueTitle(ah, event.getClient().getSuccess(), songs.length, fintotal, settings.getRepeatMode(), settings.getQueueType())) .setItems(songs) .setUsers(event.getAuthor()) .setColor(event.getSelfMember().getColor()) @@ -103,7 +103,7 @@ public void doCommand(CommandEvent event) builder.build().paginate(event.getChannel(), pagenum); } - private String getQueueTitle(AudioHandler ah, String success, int songslength, long total, RepeatMode repeatmode) + private String getQueueTitle(AudioHandler ah, String success, int songslength, long total, RepeatMode repeatmode, QueueType queueType) { StringBuilder sb = new StringBuilder(); if(ah.getPlayer().getPlayingTrack()!=null) @@ -113,6 +113,7 @@ private String getQueueTitle(AudioHandler ah, String success, int songslength, l } return FormatUtil.filter(sb.append(success).append(" Current Queue | ").append(songslength) .append(" entries | `").append(FormatUtil.formatTime(total)).append("` ") - .append(repeatmode.getEmoji() != null ? "| "+repeatmode.getEmoji() : "").toString()); + .append("| ").append(queueType.getEmoji()).append(" `").append(queueType.getUserFriendlyName()).append('`') + .append(repeatmode.getEmoji() != null ? " | "+repeatmode.getEmoji() : "").toString()); } } diff --git a/src/main/java/com/jagrosh/jmusicbot/queue/AbstractQueue.java b/src/main/java/com/jagrosh/jmusicbot/queue/AbstractQueue.java new file mode 100644 index 000000000..0d3b06705 --- /dev/null +++ b/src/main/java/com/jagrosh/jmusicbot/queue/AbstractQueue.java @@ -0,0 +1,130 @@ +/* + * Copyright 2022 John Grosh (jagrosh). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.jagrosh.jmusicbot.queue; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +/** + * + * @author Wolfgang Schwendtbauer + * @param + */ +public abstract class AbstractQueue +{ + protected AbstractQueue(AbstractQueue queue) + { + this.list = queue != null ? queue.getList() : new LinkedList<>(); + } + + protected final List list; + + public abstract int add(T item); + + public void addAt(int index, T item) + { + if(index >= list.size()) + list.add(item); + else + list.add(index, item); + } + + public int size() { + return list.size(); + } + + public T pull() { + return list.remove(0); + } + + public boolean isEmpty() + { + return list.isEmpty(); + } + + public List getList() + { + return list; + } + + public T get(int index) { + return list.get(index); + } + + public T remove(int index) + { + return list.remove(index); + } + + public int removeAll(long identifier) + { + int count = 0; + for(int i=list.size()-1; i>=0; i--) + { + if(list.get(i).getIdentifier()==identifier) + { + list.remove(i); + count++; + } + } + return count; + } + + public void clear() + { + list.clear(); + } + + public int shuffle(long identifier) + { + List iset = new ArrayList<>(); + for(int i=0; i 0) { + list.subList(0, number).clear(); + } + } + + /** + * Move an item to a different position in the list + * @param from The position of the item + * @param to The new position of the item + * @return the moved item + */ + public T moveItem(int from, int to) + { + T item = list.remove(from); + list.add(to, item); + return item; + } +} diff --git a/src/main/java/com/jagrosh/jmusicbot/queue/FairQueue.java b/src/main/java/com/jagrosh/jmusicbot/queue/FairQueue.java index b19eb44c2..2c79d1095 100644 --- a/src/main/java/com/jagrosh/jmusicbot/queue/FairQueue.java +++ b/src/main/java/com/jagrosh/jmusicbot/queue/FairQueue.java @@ -15,9 +15,7 @@ */ package com.jagrosh.jmusicbot.queue; -import java.util.ArrayList; import java.util.HashSet; -import java.util.List; import java.util.Set; /** @@ -25,11 +23,16 @@ * @author John Grosh (jagrosh) * @param */ -public class FairQueue +public class FairQueue extends AbstractQueue { - private final List list = new ArrayList<>(); - private final Set set = new HashSet<>(); - + public FairQueue(AbstractQueue queue) + { + super(queue); + } + + protected final Set set = new HashSet<>(); + + @Override public int add(T item) { int lastIndex; @@ -47,99 +50,5 @@ public int add(T item) list.add(lastIndex, item); return lastIndex; } - - public void addAt(int index, T item) - { - if(index >= list.size()) - list.add(item); - else - list.add(index, item); - } - - public int size() - { - return list.size(); - } - - public T pull() - { - return list.remove(0); - } - - public boolean isEmpty() - { - return list.isEmpty(); - } - - public List getList() - { - return list; - } - - public T get(int index) - { - return list.get(index); - } - - public T remove(int index) - { - return list.remove(index); - } - - public int removeAll(long identifier) - { - int count = 0; - for(int i=list.size()-1; i>=0; i--) - { - if(list.get(i).getIdentifier()==identifier) - { - list.remove(i); - count++; - } - } - return count; - } - - public void clear() - { - list.clear(); - } - - public int shuffle(long identifier) - { - List iset = new ArrayList<>(); - for(int i=0; i + */ +public class LinearQueue extends AbstractQueue +{ + public LinearQueue(AbstractQueue queue) + { + super(queue); + } + + @Override + public int add(T item) + { + list.add(item); + return list.size() - 1; + } + +} diff --git a/src/main/java/com/jagrosh/jmusicbot/queue/QueueSupplier.java b/src/main/java/com/jagrosh/jmusicbot/queue/QueueSupplier.java new file mode 100644 index 000000000..06ac52b46 --- /dev/null +++ b/src/main/java/com/jagrosh/jmusicbot/queue/QueueSupplier.java @@ -0,0 +1,26 @@ +/* + * Copyright 2022 John Grosh . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.jagrosh.jmusicbot.queue; + +/** + * + * @author Wolfgang Schwendtbauer + */ +@FunctionalInterface +public interface QueueSupplier +{ + AbstractQueue apply(AbstractQueue queue); +} diff --git a/src/main/java/com/jagrosh/jmusicbot/settings/QueueType.java b/src/main/java/com/jagrosh/jmusicbot/settings/QueueType.java new file mode 100644 index 000000000..1f1404fdd --- /dev/null +++ b/src/main/java/com/jagrosh/jmusicbot/settings/QueueType.java @@ -0,0 +1,69 @@ +/* + * Copyright 2022 John Grosh . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.jagrosh.jmusicbot.settings; + +import com.jagrosh.jmusicbot.queue.AbstractQueue; +import com.jagrosh.jmusicbot.queue.FairQueue; +import com.jagrosh.jmusicbot.queue.LinearQueue; +import com.jagrosh.jmusicbot.queue.Queueable; +import com.jagrosh.jmusicbot.queue.QueueSupplier; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +/** + * + * @author Wolfgang Schwendtbauer + */ +public enum QueueType +{ + LINEAR("\u23E9", "Linear", LinearQueue::new), // ⏩ + FAIR("\uD83D\uDD22", "Fair", FairQueue::new); // 🔢 + + private final String userFriendlyName; + private final String emoji; + private final QueueSupplier supplier; + + QueueType(final String emoji, final String userFriendlyName, QueueSupplier supplier) + { + this.userFriendlyName = userFriendlyName; + this.emoji = emoji; + this.supplier = supplier; + } + + public static List getNames() + { + return Arrays.stream(QueueType.values()) + .map(type -> type.name().toLowerCase()) + .collect(Collectors.toList()); + } + + public AbstractQueue createInstance(AbstractQueue previous) + { + return supplier.apply(previous); + } + + public String getUserFriendlyName() + { + return userFriendlyName; + } + + public String getEmoji() + { + return emoji; + } +} diff --git a/src/main/java/com/jagrosh/jmusicbot/settings/Settings.java b/src/main/java/com/jagrosh/jmusicbot/settings/Settings.java index 6f1ea6879..d9fb84545 100644 --- a/src/main/java/com/jagrosh/jmusicbot/settings/Settings.java +++ b/src/main/java/com/jagrosh/jmusicbot/settings/Settings.java @@ -36,10 +36,11 @@ public class Settings implements GuildSettingsProvider private int volume; private String defaultPlaylist; private RepeatMode repeatMode; + private QueueType queueType; private String prefix; private double skipRatio; - public Settings(SettingsManager manager, String textId, String voiceId, String roleId, int volume, String defaultPlaylist, RepeatMode repeatMode, String prefix, double skipRatio) + public Settings(SettingsManager manager, String textId, String voiceId, String roleId, int volume, String defaultPlaylist, RepeatMode repeatMode, String prefix, double skipRatio, QueueType queueType) { this.manager = manager; try @@ -71,9 +72,10 @@ public Settings(SettingsManager manager, String textId, String voiceId, String r this.repeatMode = repeatMode; this.prefix = prefix; this.skipRatio = skipRatio; + this.queueType = queueType; } - public Settings(SettingsManager manager, long textId, long voiceId, long roleId, int volume, String defaultPlaylist, RepeatMode repeatMode, String prefix, double skipRatio) + public Settings(SettingsManager manager, long textId, long voiceId, long roleId, int volume, String defaultPlaylist, RepeatMode repeatMode, String prefix, double skipRatio, QueueType queueType) { this.manager = manager; this.textId = textId; @@ -84,6 +86,7 @@ public Settings(SettingsManager manager, long textId, long voiceId, long roleId, this.repeatMode = repeatMode; this.prefix = prefix; this.skipRatio = skipRatio; + this.queueType = queueType; } // Getters @@ -127,6 +130,11 @@ public double getSkipRatio() return skipRatio; } + public QueueType getQueueType() + { + return queueType; + } + @Override public Collection getPrefixes() { @@ -181,4 +189,10 @@ public void setSkipRatio(double skipRatio) this.skipRatio = skipRatio; this.manager.writeSettings(); } + + public void setQueueType(QueueType queueType) + { + this.queueType = queueType; + this.manager.writeSettings(); + } } diff --git a/src/main/java/com/jagrosh/jmusicbot/settings/SettingsManager.java b/src/main/java/com/jagrosh/jmusicbot/settings/SettingsManager.java index 27a198b46..72f744c0e 100644 --- a/src/main/java/com/jagrosh/jmusicbot/settings/SettingsManager.java +++ b/src/main/java/com/jagrosh/jmusicbot/settings/SettingsManager.java @@ -32,14 +32,15 @@ */ public class SettingsManager implements GuildSettingsManager { + private final static String SETTINGS_FILE = "serversettings.json"; private final HashMap settings; public SettingsManager() { this.settings = new HashMap<>(); - + try { - JSONObject loadedSettings = new JSONObject(new String(Files.readAllBytes(OtherUtil.getPath("serversettings.json")))); + JSONObject loadedSettings = new JSONObject(new String(Files.readAllBytes(OtherUtil.getPath(SETTINGS_FILE)))); loadedSettings.keySet().forEach((id) -> { JSONObject o = loadedSettings.getJSONObject(id); @@ -56,7 +57,8 @@ public SettingsManager() o.has("default_playlist")? o.getString("default_playlist") : null, o.has("repeat_mode") ? o.getEnum(RepeatMode.class, "repeat_mode"): RepeatMode.OFF, o.has("prefix") ? o.getString("prefix") : null, - o.has("skip_ratio") ? o.getDouble("skip_ratio") : -1)); + o.has("skip_ratio") ? o.getDouble("skip_ratio") : -1, + o.has("queue_type") ? o.getEnum(QueueType.class, "queue_type") : QueueType.FAIR)); }); } catch (NoSuchFileException e) { // create an empty json file @@ -73,10 +75,10 @@ public SettingsManager() LoggerFactory.getLogger("Settings").info("serversettings.json loaded from " + OtherUtil.getPath("serversettings.json").toAbsolutePath()); } - + /** * Gets non-null settings for a Guild - * + * * @param guild the guild to get settings for * @return the existing settings, or new settings for that guild */ @@ -85,17 +87,17 @@ public Settings getSettings(Guild guild) { return getSettings(guild.getIdLong()); } - + public Settings getSettings(long guildId) { return settings.computeIfAbsent(guildId, id -> createDefaultSettings()); } - + private Settings createDefaultSettings() { - return new Settings(this, 0, 0, 0, 100, null, RepeatMode.OFF, null, -1); + return new Settings(this, 0, 0, 0, 100, null, RepeatMode.OFF, null, -1, QueueType.FAIR); } - + protected void writeSettings() { JSONObject obj = new JSONObject(); @@ -118,10 +120,12 @@ protected void writeSettings() o.put("prefix", s.getPrefix()); if(s.getSkipRatio() != -1) o.put("skip_ratio", s.getSkipRatio()); + if(s.getQueueType() != QueueType.FAIR) + o.put("queue_type", s.getQueueType().name()); obj.put(Long.toString(key), o); }); try { - Files.write(OtherUtil.getPath("serversettings.json"), obj.toString(4).getBytes()); + Files.write(OtherUtil.getPath(SETTINGS_FILE), obj.toString(4).getBytes()); } catch(IOException ex){ LoggerFactory.getLogger("Settings").warn("Failed to write to file: "+ex); } diff --git a/src/main/resources/reference.conf b/src/main/resources/reference.conf index e48403f54..5e6e4ac27 100644 --- a/src/main/resources/reference.conf +++ b/src/main/resources/reference.conf @@ -174,6 +174,7 @@ aliases { movetrack = [ move ] pause = [] playnext = [] + queuetype = [] repeat = [] skipto = [ jumpto ] stop = [ leave ] diff --git a/src/test/java/com/jagrosh/jmusicbot/FairQueueTest.java b/src/test/java/com/jagrosh/jmusicbot/FairQueueTest.java index 0cfda2272..3dbe6869b 100644 --- a/src/test/java/com/jagrosh/jmusicbot/FairQueueTest.java +++ b/src/test/java/com/jagrosh/jmusicbot/FairQueueTest.java @@ -29,7 +29,7 @@ public class FairQueueTest @Test public void differentIdentifierSize() { - FairQueue queue = new FairQueue<>(); + FairQueue queue = new FairQueue<>(null); int size = 100; for(int i=0; i queue = new FairQueue<>(); + FairQueue queue = new FairQueue<>(null); int size = 100; for(int i=0; i Date: Tue, 5 Mar 2024 01:08:27 +0100 Subject: [PATCH 19/24] Always self-deafen (#1491) --- src/main/java/com/jagrosh/jmusicbot/commands/MusicCommand.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/jagrosh/jmusicbot/commands/MusicCommand.java b/src/main/java/com/jagrosh/jmusicbot/commands/MusicCommand.java index 9740a7af7..e03f073af 100644 --- a/src/main/java/com/jagrosh/jmusicbot/commands/MusicCommand.java +++ b/src/main/java/com/jagrosh/jmusicbot/commands/MusicCommand.java @@ -86,6 +86,7 @@ protected void execute(CommandEvent event) try { event.getGuild().getAudioManager().openAudioConnection(userState.getChannel()); + event.getGuild().getAudioManager().setSelfDeafened(true); } catch(PermissionException ex) { From bb17c984a23a6bc9e28719258d984a647ff09fd8 Mon Sep 17 00:00:00 2001 From: John Grosh Date: Mon, 4 Mar 2024 19:35:17 -0500 Subject: [PATCH 20/24] Codefactor Fixes (#1493) * codefactor fixes * anotha one --- scripts/run_jmusicbot.sh | 2 +- .../java/com/jagrosh/jmusicbot/BotConfig.java | 5 + .../java/com/jagrosh/jmusicbot/JMusicBot.java | 157 ++++++++++-------- .../java/com/jagrosh/jmusicbot/Listener.java | 2 +- .../jagrosh/jmusicbot/utils/OtherUtil.java | 4 +- 5 files changed, 93 insertions(+), 77 deletions(-) diff --git a/scripts/run_jmusicbot.sh b/scripts/run_jmusicbot.sh index 70a6874fe..75b94fa46 100644 --- a/scripts/run_jmusicbot.sh +++ b/scripts/run_jmusicbot.sh @@ -11,7 +11,7 @@ LOOP=true download() { if [ $DOWNLOAD == true ]; then URL=$(curl -s https://api.github.com/repos/jagrosh/MusicBot/releases/latest \ - | grep -i browser_download_url.*\.jar \ + | grep -i "browser_download_url.*\.jar" \ | sed 's/.*\(http.*\)"/\1/') FILENAME=$(echo $URL | sed 's/.*\/\([^\/]*\)/\1/') if [ -f $FILENAME ]; then diff --git a/src/main/java/com/jagrosh/jmusicbot/BotConfig.java b/src/main/java/com/jagrosh/jmusicbot/BotConfig.java index 53a155b31..a95556f8a 100644 --- a/src/main/java/com/jagrosh/jmusicbot/BotConfig.java +++ b/src/main/java/com/jagrosh/jmusicbot/BotConfig.java @@ -273,6 +273,11 @@ public Activity getGame() return game; } + public boolean isGameNone() + { + return game != null && game.getName().equalsIgnoreCase("none"); + } + public OnlineStatus getStatus() { return status; diff --git a/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java b/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java index a32a51048..67cff1475 100644 --- a/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java +++ b/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java @@ -15,6 +15,7 @@ */ package com.jagrosh.jmusicbot; +import com.jagrosh.jdautilities.command.CommandClient; import com.jagrosh.jdautilities.command.CommandClientBuilder; import com.jagrosh.jdautilities.commons.waiter.EventWaiter; import com.jagrosh.jdautilities.examples.command.*; @@ -86,78 +87,8 @@ private static void startBot() EventWaiter waiter = new EventWaiter(); SettingsManager settings = new SettingsManager(); Bot bot = new Bot(waiter, config, settings); + CommandClient client = createCommandClient(config, settings, bot); - AboutCommand aboutCommand = new AboutCommand(Color.BLUE.brighter(), - "a music bot that is [easy to host yourself!](https://github.com/jagrosh/MusicBot) (v" + OtherUtil.getCurrentVersion() + ")", - new String[]{"High-quality music playback", "FairQueue™ Technology", "Easy to host yourself"}, - RECOMMENDED_PERMS); - aboutCommand.setIsAuthor(false); - aboutCommand.setReplacementCharacter("\uD83C\uDFB6"); // 🎶 - - // set up the command client - CommandClientBuilder cb = new CommandClientBuilder() - .setPrefix(config.getPrefix()) - .setAlternativePrefix(config.getAltPrefix()) - .setOwnerId(Long.toString(config.getOwnerId())) - .setEmojis(config.getSuccess(), config.getWarning(), config.getError()) - .setHelpWord(config.getHelp()) - .setLinkedCacheSize(200) - .setGuildSettingsManager(settings) - .addCommands(aboutCommand, - new PingCommand(), - new SettingsCmd(bot), - - new LyricsCmd(bot), - new NowplayingCmd(bot), - new PlayCmd(bot), - new PlaylistsCmd(bot), - new QueueCmd(bot), - new RemoveCmd(bot), - new SearchCmd(bot), - new SCSearchCmd(bot), - new ShuffleCmd(bot), - new SkipCmd(bot), - - new ForceRemoveCmd(bot), - new ForceskipCmd(bot), - new MoveTrackCmd(bot), - new PauseCmd(bot), - new PlaynextCmd(bot), - new RepeatCmd(bot), - new SkiptoCmd(bot), - new StopCmd(bot), - new VolumeCmd(bot), - - new PrefixCmd(bot), - new QueueTypeCmd(bot), - new SetdjCmd(bot), - new SkipratioCmd(bot), - new SettcCmd(bot), - new SetvcCmd(bot), - - new AutoplaylistCmd(bot), - new DebugCmd(bot), - new PlaylistCmd(bot), - new SetavatarCmd(bot), - new SetgameCmd(bot), - new SetnameCmd(bot), - new SetstatusCmd(bot), - new ShutdownCmd(bot) - ); - if(config.useEval()) - cb.addCommand(new EvalCmd(bot)); - boolean nogame = false; - if(config.getStatus()!=OnlineStatus.UNKNOWN) - cb.setStatus(config.getStatus()); - if(config.getGame()==null) - cb.useDefaultGame(); - else if(config.getGame().getName().equalsIgnoreCase("none")) - { - cb.setActivity(null); - nogame = true; - } - else - cb.setActivity(config.getGame()); if(!prompt.isNoGUI()) { @@ -183,10 +114,10 @@ else if(config.getGame().getName().equalsIgnoreCase("none")) JDA jda = JDABuilder.create(config.getToken(), Arrays.asList(INTENTS)) .enableCache(CacheFlag.MEMBER_OVERRIDES, CacheFlag.VOICE_STATE) .disableCache(CacheFlag.ACTIVITY, CacheFlag.CLIENT_STATUS, CacheFlag.EMOTE, CacheFlag.ONLINE_STATUS) - .setActivity(nogame ? null : Activity.playing("loading...")) + .setActivity(config.isGameNone() ? null : Activity.playing("loading...")) .setStatus(config.getStatus()==OnlineStatus.INVISIBLE || config.getStatus()==OnlineStatus.OFFLINE ? OnlineStatus.INVISIBLE : OnlineStatus.DO_NOT_DISTURB) - .addEventListeners(cb.build(), waiter, new Listener(bot)) + .addEventListeners(client, waiter, new Listener(bot)) .setBulkDeleteSplittingEnabled(true) .build(); bot.setJDA(jda); @@ -231,4 +162,84 @@ else if(config.getGame().getName().equalsIgnoreCase("none")) System.exit(1); } } + + private static CommandClient createCommandClient(BotConfig config, SettingsManager settings, Bot bot) + { + // instantiate about command + AboutCommand aboutCommand = new AboutCommand(Color.BLUE.brighter(), + "a music bot that is [easy to host yourself!](https://github.com/jagrosh/MusicBot) (v" + OtherUtil.getCurrentVersion() + ")", + new String[]{"High-quality music playback", "FairQueue™ Technology", "Easy to host yourself"}, + RECOMMENDED_PERMS); + aboutCommand.setIsAuthor(false); + aboutCommand.setReplacementCharacter("\uD83C\uDFB6"); // 🎶 + + // set up the command client + CommandClientBuilder cb = new CommandClientBuilder() + .setPrefix(config.getPrefix()) + .setAlternativePrefix(config.getAltPrefix()) + .setOwnerId(Long.toString(config.getOwnerId())) + .setEmojis(config.getSuccess(), config.getWarning(), config.getError()) + .setHelpWord(config.getHelp()) + .setLinkedCacheSize(200) + .setGuildSettingsManager(settings) + .addCommands(aboutCommand, + new PingCommand(), + new SettingsCmd(bot), + + new LyricsCmd(bot), + new NowplayingCmd(bot), + new PlayCmd(bot), + new PlaylistsCmd(bot), + new QueueCmd(bot), + new RemoveCmd(bot), + new SearchCmd(bot), + new SCSearchCmd(bot), + new ShuffleCmd(bot), + new SkipCmd(bot), + + new ForceRemoveCmd(bot), + new ForceskipCmd(bot), + new MoveTrackCmd(bot), + new PauseCmd(bot), + new PlaynextCmd(bot), + new RepeatCmd(bot), + new SkiptoCmd(bot), + new StopCmd(bot), + new VolumeCmd(bot), + + new PrefixCmd(bot), + new QueueTypeCmd(bot), + new SetdjCmd(bot), + new SkipratioCmd(bot), + new SettcCmd(bot), + new SetvcCmd(bot), + + new AutoplaylistCmd(bot), + new DebugCmd(bot), + new PlaylistCmd(bot), + new SetavatarCmd(bot), + new SetgameCmd(bot), + new SetnameCmd(bot), + new SetstatusCmd(bot), + new ShutdownCmd(bot) + ); + + // enable eval if applicable + if(config.useEval()) + cb.addCommand(new EvalCmd(bot)); + + // set status if set in config + if(config.getStatus() != OnlineStatus.UNKNOWN) + cb.setStatus(config.getStatus()); + + // set game + if(config.getGame() == null) + cb.useDefaultGame(); + else if(config.isGameNone()) + cb.setActivity(null); + else + cb.setActivity(config.getGame()); + + return cb.build(); + } } diff --git a/src/main/java/com/jagrosh/jmusicbot/Listener.java b/src/main/java/com/jagrosh/jmusicbot/Listener.java index 1134cafc1..2e50b793a 100644 --- a/src/main/java/com/jagrosh/jmusicbot/Listener.java +++ b/src/main/java/com/jagrosh/jmusicbot/Listener.java @@ -82,7 +82,7 @@ public void onReady(ReadyEvent event) owner.openPrivateChannel().queue(pc -> pc.sendMessage(msg).queue()); } } - catch(Exception ex) {} // ignored + catch(Exception ignored) {} // ignored }, 0, 24, TimeUnit.HOURS); } } diff --git a/src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java b/src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java index 63c39ce4b..9b6294933 100644 --- a/src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java +++ b/src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java @@ -64,7 +64,7 @@ public static Path getPath(String path) { result = Paths.get(new File(JMusicBot.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile().getPath() + File.separator + path); } - catch(URISyntaxException ex) {} + catch(URISyntaxException ignored) {} } return result; } @@ -84,7 +84,7 @@ public static String loadResource(Object clazz, String name) reader.lines().forEach(line -> sb.append("\r\n").append(line)); return sb.toString().trim(); } - catch(IOException ex) + catch(IOException ignored) { return null; } From 6752695b4359a1c108d95ec55ebed7be3e7a2a2c Mon Sep 17 00:00:00 2001 From: John Grosh Date: Mon, 4 Mar 2024 19:35:32 -0500 Subject: [PATCH 21/24] rename github action file and update readme (#1494) --- .github/workflows/{test.yml => build-and-test.yml} | 4 ++-- README.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) rename .github/workflows/{test.yml => build-and-test.yml} (86%) diff --git a/.github/workflows/test.yml b/.github/workflows/build-and-test.yml similarity index 86% rename from .github/workflows/test.yml rename to .github/workflows/build-and-test.yml index e6207fa0f..f5b4631e7 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/build-and-test.yml @@ -1,4 +1,4 @@ -name: Test +name: Build and Test on: push: branches: @@ -18,5 +18,5 @@ jobs: java-version: '11' distribution: 'adopt' cache: maven - - name: Build with Maven + - name: Build and Test with Maven run: mvn --batch-mode --update-snapshots verify diff --git a/README.md b/README.md index bf5c985c9..8fc533ddc 100644 --- a/README.md +++ b/README.md @@ -7,8 +7,8 @@ [![Release](https://img.shields.io/github/release/jagrosh/MusicBot.svg)](https://github.com/jagrosh/MusicBot/releases/latest) [![License](https://img.shields.io/github/license/jagrosh/MusicBot.svg)](https://github.com/jagrosh/MusicBot/blob/master/LICENSE) [![Discord](https://discordapp.com/api/guilds/147698382092238848/widget.png)](https://discord.gg/0p9LSGoRLu6Pet0k)
-[![CircleCI](https://img.shields.io/circleci/project/github/jagrosh/MusicBot/master.svg)](https://circleci.com/gh/jagrosh/MusicBot) -[![AppVeyor](https://ci.appveyor.com/api/projects/status/gdu6nyte5psj6xfk/branch/master?svg=true)](https://ci.appveyor.com/project/jagrosh/musicbot/branch/master) +[![CircleCI](https://dl.circleci.com/status-badge/img/gh/jagrosh/MusicBot/tree/master.svg?style=svg)](https://dl.circleci.com/status-badge/redirect/gh/jagrosh/MusicBot/tree/master) +[![Build and Test](https://github.com/jagrosh/MusicBot/actions/workflows/build-and-test.yml/badge.svg)](https://github.com/jagrosh/MusicBot/actions/workflows/build-and-test.yml) [![CodeFactor](https://www.codefactor.io/repository/github/jagrosh/musicbot/badge)](https://www.codefactor.io/repository/github/jagrosh/musicbot) A cross-platform Discord music bot with a clean interface, and that is easy to set up and run yourself! From 49c3ec79607bef5b15096ebd7b3645ba5a5b2095 Mon Sep 17 00:00:00 2001 From: Michaili K Date: Tue, 5 Mar 2024 01:38:04 +0100 Subject: [PATCH 22/24] Switch to lavalink's lavaplayer fork (#1490) * Switch to lavalink's lavaplayer fork * Create logback turbofilter to suppress YouTube auth tokens warning * added license header --------- Co-authored-by: unknown --- pom.xml | 21 +++++---- .../jmusicbot/utils/LogBackTurboFilter.java | 44 +++++++++++++++++++ src/main/resources/logback.xml | 2 + 3 files changed, 56 insertions(+), 11 deletions(-) create mode 100644 src/main/java/com/jagrosh/jmusicbot/utils/LogBackTurboFilter.java diff --git a/pom.xml b/pom.xml index 04f5444ae..699eeb5c1 100644 --- a/pom.xml +++ b/pom.xml @@ -30,6 +30,11 @@ m2-duncte123 https://m2.duncte123.dev/releases + + arbjergDev-snapshots + Lavalink Repository + https://maven.lavalink.dev/snapshots + @@ -47,17 +52,11 @@
- - - com.github.jagrosh - lavaplayer - jmusicbot-SNAPSHOT - + dev.arbjerg + lavaplayer + 727959e9f621fc457b3a5adafcfffb55fdeaa538-SNAPSHOT +
com.github.jagrosh JLyrics @@ -68,7 +67,7 @@ sourcemanagers 1.9.0 - + ch.qos.logback diff --git a/src/main/java/com/jagrosh/jmusicbot/utils/LogBackTurboFilter.java b/src/main/java/com/jagrosh/jmusicbot/utils/LogBackTurboFilter.java new file mode 100644 index 000000000..c991a07ec --- /dev/null +++ b/src/main/java/com/jagrosh/jmusicbot/utils/LogBackTurboFilter.java @@ -0,0 +1,44 @@ +/* + * Copyright 2024 John Grosh . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.jagrosh.jmusicbot.utils; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.turbo.TurboFilter; +import ch.qos.logback.core.spi.FilterReply; +import org.slf4j.Marker; + +/** + * A TurboFilter, currently only used to suppress specific log messages from libraries. + * + * @author Michaili K. + */ +public class LogBackTurboFilter extends TurboFilter +{ + @Override + public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) + { + // Suppresses the auth token warning from the YoutubeAudioSourceManager + // https://github.com/jagrosh/MusicBot/pull/1490#issuecomment-1974070225 + if (logger.getName().equals("com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAccessTokenTracker") + && format.equals("YouTube auth tokens can't be retrieved because email and password is not set in YoutubeAudioSourceManager, age restricted videos will throw exceptions.") + ) { + return FilterReply.DENY; + } + + return FilterReply.NEUTRAL; + } +} diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml index 4a7033f5d..1d03fcc22 100644 --- a/src/main/resources/logback.xml +++ b/src/main/resources/logback.xml @@ -14,4 +14,6 @@ + + From 801b3769a1a498866273b582ca6807db368e5658 Mon Sep 17 00:00:00 2001 From: John Grosh Date: Sat, 30 Mar 2024 15:18:52 -0400 Subject: [PATCH 23/24] Fix startup message type and add URL to message (#1521) * fix * add URL to error message --- src/main/java/com/jagrosh/jmusicbot/JMusicBot.java | 2 +- src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java b/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java index 67cff1475..d66c35190 100644 --- a/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java +++ b/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java @@ -137,7 +137,7 @@ private static void startBot() // message content intent if(!"@mention".equals(config.getPrefix())) { - prompt.alert(Prompt.Level.INFO, "JMusicBot", "You currently have a custom prefix set. " + LOG.info("JMusicBot", "You currently have a custom prefix set. " + "If your prefix is not working, make sure that the 'MESSAGE CONTENT INTENT' is Enabled " + "on https://discord.com/developers/applications/" + jda.getSelfUser().getId() + "/bot"); } diff --git a/src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java b/src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java index 9b6294933..a22175d02 100644 --- a/src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java +++ b/src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java @@ -223,7 +223,8 @@ public static String getUnsupportedBotReason(JDA jda) ApplicationInfo info = jda.retrieveApplicationInfo().complete(); if (info.isBotPublic()) - return "\"Public Bot\" is enabled. Using JMusicBot as a public bot is not supported. Please disable it in the Developer Dashboard."; + return "\"Public Bot\" is enabled. Using JMusicBot as a public bot is not supported. Please disable it in the " + + "Developer Dashboard at https://discord.com/developers/applications/" + jda.getSelfUser().getId() + "/bot."; return null; } From b3ffbdba7ddac143250dd566679bc96d78f791e2 Mon Sep 17 00:00:00 2001 From: Michaili K Date: Sat, 30 Mar 2024 20:34:46 +0100 Subject: [PATCH 24/24] Add log level configuration (#1156) * Add loglevel config * Change order of fields --------- Co-authored-by: John Grosh --- src/main/java/com/jagrosh/jmusicbot/BotConfig.java | 10 ++++++++-- src/main/java/com/jagrosh/jmusicbot/JMusicBot.java | 5 +++++ src/main/resources/reference.conf | 9 +++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/jagrosh/jmusicbot/BotConfig.java b/src/main/java/com/jagrosh/jmusicbot/BotConfig.java index a95556f8a..9a57beff9 100644 --- a/src/main/java/com/jagrosh/jmusicbot/BotConfig.java +++ b/src/main/java/com/jagrosh/jmusicbot/BotConfig.java @@ -39,7 +39,7 @@ public class BotConfig private final static String END_TOKEN = "/// END OF JMUSICBOT CONFIG ///"; private Path path = null; - private String token, prefix, altprefix, helpWord, playlistsFolder, + private String token, prefix, altprefix, helpWord, playlistsFolder, logLevel, successEmoji, warningEmoji, errorEmoji, loadingEmoji, searchingEmoji; private boolean stayInChannel, songInGame, npImages, updatealerts, useEval, dbots; private long owner, maxSeconds, aloneTimeUntilStop; @@ -86,6 +86,7 @@ public void load() songInGame = config.getBoolean("songinstatus"); npImages = config.getBoolean("npimages"); updatealerts = config.getBoolean("updatealerts"); + logLevel = config.getString("loglevel"); useEval = config.getBoolean("eval"); maxSeconds = config.getLong("maxtime"); aloneTimeUntilStop = config.getLong("alonetimeuntilstop"); @@ -312,7 +313,12 @@ public boolean useUpdateAlerts() { return updatealerts; } - + + public String getLogLevel() + { + return logLevel; + } + public boolean useEval() { return useEval; diff --git a/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java b/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java index d66c35190..66071a1fa 100644 --- a/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java +++ b/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java @@ -38,6 +38,7 @@ import net.dv8tion.jda.api.exceptions.ErrorResponseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import ch.qos.logback.classic.Level; /** * @@ -82,6 +83,10 @@ private static void startBot() if(!config.isValid()) return; LOG.info("Loaded config from " + config.getConfigLocation()); + + // set log level from config + ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).setLevel( + Level.toLevel(config.getLogLevel(), Level.INFO)); // set up the listener EventWaiter waiter = new EventWaiter(); diff --git a/src/main/resources/reference.conf b/src/main/resources/reference.conf index 5e6e4ac27..19206d3ab 100644 --- a/src/main/resources/reference.conf +++ b/src/main/resources/reference.conf @@ -182,6 +182,15 @@ aliases { } +// This sets the logging verbosity. +// Available levels: off, error, warn, info, debug, trace, all +// +// It is recommended to leave this at info. Debug log levels might help with troubleshooting, +// but can contain sensitive data. + +loglevel = info + + // Transforms are used to modify specific play inputs and convert them to different kinds of inputs // These are quite complicated to use, and have limited use-cases, but in theory allow for rough // whitelists or blacklists, roundabout loading from some sources, and customization of how things are