Skip to content

Commit

Permalink
update deps, minor code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
jagrosh committed Apr 6, 2022
1 parent 85aebe8 commit c4e11d6
Show file tree
Hide file tree
Showing 12 changed files with 116 additions and 68 deletions.
1 change: 1 addition & 0 deletions .github/workflows/make-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ jobs:
artifacts: "*.jar"
body: |
${{ github.event.inputs.info }}
---
### Setup
https://jmusicbot.com/setup
Expand Down
33 changes: 19 additions & 14 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,28 @@
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
</repositories>

<dependencies>
<!-- Discord Dependencies -->
<dependency>
<groupId>net.dv8tion</groupId>
<artifactId>JDA</artifactId>
<version>4.3.0_324</version>
<version>4.4.0_352</version>
</dependency>
<dependency>
<groupId>com.jagrosh</groupId>
<artifactId>jda-utilities</artifactId>
<version>3.0.5</version>
<type>pom</type>
</dependency>

<!-- Music Dependencies -->
<!-- using a fork of this to fix some issues faster -->
<!-- dependency>
<groupId>com.sedmelluq</groupId>
Expand All @@ -46,23 +59,13 @@
<artifactId>lavaplayer-natives-extra</artifactId>
<version>1.3.13</version>
</dependency-->
<dependency>
<groupId>com.jagrosh</groupId>
<artifactId>jda-utilities</artifactId>
<version>3.0.5</version>
<type>pom</type>
</dependency>
<!-- jitpack for now, we need to version this correctly later -->
<dependency>
<groupId>com.github.jagrosh</groupId>
<artifactId>JLyrics</artifactId>
<version>-SNAPSHOT</version>
<version>master-SNAPSHOT</version>
</dependency>
<!--dependency>
<groupId>com.jagrosh</groupId>
<artifactId>JLyrics</artifactId>
<version>0.6</version>
</dependency-->

<!-- Misc Internal Dependencies -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
Expand All @@ -78,6 +81,8 @@
<artifactId>jsoup</artifactId>
<version>1.14.2</version>
</dependency>

<!-- Testing Dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
Expand Down
58 changes: 39 additions & 19 deletions src/main/java/com/jagrosh/jmusicbot/BotConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;

Expand Down Expand Up @@ -63,13 +62,7 @@ public void load()
try
{
// get the path to the config, default config.txt
path = OtherUtil.getPath(System.getProperty("config.file", System.getProperty("config", "config.txt")));
if(path.toFile().exists())
{
if(System.getProperty("config.file") == null)
System.setProperty("config.file", System.getProperty("config", path.toAbsolutePath().toString()));
ConfigFactory.invalidateCaches();
}
path = getConfigPath();

// load in the config file, plus the default values
//Config config = ConfigFactory.parseFile(path.toFile()).withFallback(ConfigFactory.load());
Expand Down Expand Up @@ -161,19 +154,9 @@ public void load()

private void writeToFile()
{
String original = OtherUtil.loadResource(this, "/reference.conf");
byte[] bytes;
if(original==null)
{
bytes = ("token = "+token+"\r\nowner = "+owner).getBytes();
}
else
{
bytes = original.substring(original.indexOf(START_TOKEN)+START_TOKEN.length(), original.indexOf(END_TOKEN))
.replace("BOT_TOKEN_HERE", token)
byte[] bytes = loadDefaultConfig().replace("BOT_TOKEN_HERE", token)
.replace("0 // OWNER ID", Long.toString(owner))
.trim().getBytes();
}
try
{
Files.write(path, bytes);
Expand All @@ -186,6 +169,43 @@ private void writeToFile()
}
}

private static String loadDefaultConfig()
{
String original = OtherUtil.loadResource(new JMusicBot(), "/reference.conf");
return original==null
? "token = BOT_TOKEN_HERE\r\nowner = 0 // OWNER ID"
: original.substring(original.indexOf(START_TOKEN)+START_TOKEN.length(), original.indexOf(END_TOKEN)).trim();
}

private static Path getConfigPath()
{
Path path = OtherUtil.getPath(System.getProperty("config.file", System.getProperty("config", "config.txt")));
if(path.toFile().exists())
{
if(System.getProperty("config.file") == null)
System.setProperty("config.file", System.getProperty("config", path.toAbsolutePath().toString()));
ConfigFactory.invalidateCaches();
}
return path;
}

public static void writeDefaultConfig()
{
Prompt prompt = new Prompt(null, null, true, true);
prompt.alert(Prompt.Level.INFO, "JMusicBot Config", "Generating default config file");
Path path = BotConfig.getConfigPath();
byte[] bytes = BotConfig.loadDefaultConfig().getBytes();
try
{
prompt.alert(Prompt.Level.INFO, "JMusicBot Config", "Writing default config file to " + path.toAbsolutePath().toString());
Files.write(path, bytes);
}
catch(Exception ex)
{
prompt.alert(Prompt.Level.ERROR, "JMusicBot Config", "An error occurred writing the default config file: " + ex.getMessage());
}
}

public boolean isValid()
{
return valid;
Expand Down
39 changes: 22 additions & 17 deletions src/main/java/com/jagrosh/jmusicbot/JMusicBot.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,44 +43,51 @@
*/
public class JMusicBot
{
public final static String PLAY_EMOJI = "\u25B6"; // ▶
public final static String PAUSE_EMOJI = "\u23F8"; // ⏸
public final static String STOP_EMOJI = "\u23F9"; // ⏹
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};
public final static GatewayIntent[] INTENTS = {GatewayIntent.DIRECT_MESSAGES, GatewayIntent.GUILD_MESSAGES, GatewayIntent.GUILD_MESSAGE_REACTIONS, GatewayIntent.GUILD_VOICE_STATES};

/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
// startup log
Logger log = LoggerFactory.getLogger("Startup");

if(args.length > 0)
switch(args[0].toLowerCase())
{
case "generate-config":
BotConfig.writeDefaultConfig();
return;
default:
}
startBot();
}

private static void startBot()
{
// create prompt to handle startup
Prompt prompt = new Prompt("JMusicBot", "Switching to nogui mode. You can manually start in nogui mode by including the -Dnogui=true flag.");

// get and check latest version
String version = OtherUtil.checkVersion(prompt);
Prompt prompt = new Prompt("JMusicBot");

// check for valid java version
if(!System.getProperty("java.vm.name").contains("64"))
prompt.alert(Prompt.Level.WARNING, "Java Version", "It appears that you may not be using a supported Java version. Please use 64-bit java.");
// startup checks
OtherUtil.checkVersion(prompt);
OtherUtil.checkJavaVersion(prompt);

// load config
BotConfig config = new BotConfig(prompt);
config.load();
if(!config.isValid())
return;
LOG.info("Loaded config from " + config.getConfigLocation());

// set up the listener
EventWaiter waiter = new EventWaiter();
SettingsManager settings = new SettingsManager();
Bot bot = new Bot(waiter, config, settings);

AboutCommand aboutCommand = new AboutCommand(Color.BLUE.brighter(),
"a music bot that is [easy to host yourself!](https://github.com/jagrosh/MusicBot) (v"+version+")",
"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);
Expand Down Expand Up @@ -160,14 +167,12 @@ else if(config.getGame().getName().equalsIgnoreCase("none"))
}
catch(Exception e)
{
log.error("Could not start GUI. If you are "
LOG.error("Could not start GUI. If you are "
+ "running on a server or in a location where you cannot display a "
+ "window, please run in nogui mode using the -Dnogui=true flag.");
}
}

log.info("Loaded config from " + config.getConfigLocation());

// attempt to log in and start
try
{
Expand Down
21 changes: 15 additions & 6 deletions src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@
*/
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<QueuedTrack> queue = new FairQueue<>();
private final List<AudioTrack> defaultQueue = new LinkedList<>();
private final Set<String> votes = new HashSet<>();
Expand Down Expand Up @@ -233,12 +237,12 @@ public Message getNowPlaying(JDA jda)
eb.setFooter("Source: " + track.getInfo().author, null);

double progress = (double)audioPlayer.getPlayingTrack().getPosition()/track.getDuration();
eb.setDescription((audioPlayer.isPaused() ? JMusicBot.PAUSE_EMOJI : JMusicBot.PLAY_EMOJI)
eb.setDescription(getStatusEmoji()
+ " "+FormatUtil.progressBar(progress)
+ " `[" + FormatUtil.formatTime(track.getPosition()) + "/" + FormatUtil.formatTime(track.getDuration()) + "]` "
+ FormatUtil.volumeIcon(audioPlayer.getVolume()));

return mb.setEmbed(eb.build()).build();
return mb.setEmbeds(eb.build()).build();
}
else return null;
}
Expand All @@ -248,9 +252,9 @@ public Message getNoMusicPlaying(JDA jda)
Guild guild = guild(jda);
return new MessageBuilder()
.setContent(FormatUtil.filter(manager.getBot().getConfig().getSuccess()+" **Now Playing...**"))
.setEmbed(new EmbedBuilder()
.setEmbeds(new EmbedBuilder()
.setTitle("No music playing")
.setDescription(JMusicBot.STOP_EMOJI+" "+FormatUtil.progressBar(-1)+" "+FormatUtil.volumeIcon(audioPlayer.getVolume()))
.setDescription(STOP_EMOJI+" "+FormatUtil.progressBar(-1)+" "+FormatUtil.volumeIcon(audioPlayer.getVolume()))
.setColor(guild.getSelfMember().getColor())
.build()).build();
}
Expand All @@ -265,11 +269,16 @@ public String getTopicFormat(JDA jda)
if(title==null || title.equals("Unknown Title"))
title = track.getInfo().uri;
return "**"+title+"** ["+(userid==0 ? "autoplay" : "<@"+userid+">")+"]"
+ "\n" + (audioPlayer.isPaused() ? JMusicBot.PAUSE_EMOJI : JMusicBot.PLAY_EMOJI) + " "
+ "\n" + getStatusEmoji() + " "
+ "[" + FormatUtil.formatTime(track.getDuration()) + "] "
+ FormatUtil.volumeIcon(audioPlayer.getVolume());
}
else return "No music playing " + JMusicBot.STOP_EMOJI + " " + 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;
}

// Audio Send Handler methods
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers;
import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager;
import com.typesafe.config.Config;
import net.dv8tion.jda.api.entities.Guild;

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ protected void execute(CommandEvent event)
.setFooter(event.getJDA().getGuilds().size() + " servers | "
+ event.getJDA().getGuilds().stream().filter(g -> g.getSelfMember().getVoiceState().inVoiceChannel()).count()
+ " audio connections", null);
event.getChannel().sendMessage(builder.setEmbed(ebuilder.build()).build()).queue();
event.getChannel().sendMessage(builder.setEmbeds(ebuilder.build()).build()).queue();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,12 @@ else if (playlist.getSelectedTrack()!=null)
else
{
int count = loadPlaylist(playlist, null);
if(count==0)
if(playlist.getTracks().size() == 0)
{
m.editMessage(FormatUtil.filter(event.getClient().getWarning()+" The playlist "+(playlist.getName()==null ? "" : "(**"+playlist.getName()
+"**) ")+" could not be loaded or contained 0 entries")).queue();
}
else if(count==0)
{
m.editMessage(FormatUtil.filter(event.getClient().getWarning()+" All entries in this playlist "+(playlist.getName()==null ? "" : "(**"+playlist.getName()
+"**) ")+"were longer than the allowed maximum (`"+bot.getConfig().getMaxTime()+"`)")).queue();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public void doCommand(CommandEvent event)
Message nonowp = ah.getNoMusicPlaying(event.getJDA());
Message built = new MessageBuilder()
.setContent(event.getClient().getWarning() + " There is no music in the queue!")
.setEmbed((nowp==null ? nonowp : nowp).getEmbeds().get(0)).build();
.setEmbeds((nowp==null ? nonowp : nowp).getEmbeds().get(0)).build();
event.reply(built, m ->
{
if(nowp!=null)
Expand Down Expand Up @@ -108,7 +108,7 @@ private String getQueueTitle(AudioHandler ah, String success, int songslength, l
StringBuilder sb = new StringBuilder();
if(ah.getPlayer().getPlayingTrack()!=null)
{
sb.append(ah.getPlayer().isPaused() ? JMusicBot.PAUSE_EMOJI : JMusicBot.PLAY_EMOJI).append(" **")
sb.append(ah.getStatusEmoji()).append(" **")
.append(ah.getPlayer().getPlayingTrack().getInfo().title).append("**\n");
}
return FormatUtil.filter(sb.append(success).append(" Current Queue | ").append(songslength)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public List<String> getPlaylistNames()
else
{
createFolder();
return Collections.EMPTY_LIST;
return Collections.emptyList();
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/jagrosh/jmusicbot/settings/Settings.java
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ public double getSkipRatio()
@Override
public Collection<String> getPrefixes()
{
return prefix == null ? Collections.EMPTY_SET : Collections.singleton(prefix);
return prefix == null ? Collections.emptySet() : Collections.singleton(prefix);
}

// Setters
Expand Down
14 changes: 9 additions & 5 deletions src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,14 @@ public static OnlineStatus parseStatus(String status)
return st == null ? OnlineStatus.ONLINE : st;
}

public static String checkVersion(Prompt prompt)
public static void checkJavaVersion(Prompt prompt)
{
if(!System.getProperty("java.vm.name").contains("64"))
prompt.alert(Prompt.Level.WARNING, "Java Version",
"It appears that you may not be using a supported Java version. Please use 64-bit java.");
}

public static void checkVersion(Prompt prompt)
{
// Get current version number
String version = getCurrentVersion();
Expand All @@ -160,11 +167,8 @@ public static String checkVersion(Prompt prompt)

if(latestVersion!=null && !latestVersion.equals(version))
{
prompt.alert(Prompt.Level.WARNING, "Version", String.format(NEW_VERSION_AVAILABLE, version, latestVersion));
prompt.alert(Prompt.Level.WARNING, "JMusicBot Version", String.format(NEW_VERSION_AVAILABLE, version, latestVersion));
}

// Return the current version
return version;
}

public static String getCurrentVersion()
Expand Down

0 comments on commit c4e11d6

Please sign in to comment.