Reformat code.
This commit is contained in:
parent
b8b7a99a8d
commit
ed610ebdae
|
@ -38,34 +38,34 @@ import net.dv8tion.jda.api.utils.cache.CacheFlag;
|
||||||
public class Main extends ListenerAdapter
|
public class Main extends ListenerAdapter
|
||||||
{
|
{
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param args the command line arguments
|
* @param args the command line arguments
|
||||||
*/
|
*/
|
||||||
public static void main(String[] args) throws LoginException
|
public static void main(String[] args) throws LoginException
|
||||||
{
|
{
|
||||||
// We only need 2 gateway intents enabled for this example:
|
// We only need 2 gateway intents enabled for this example:
|
||||||
EnumSet<GatewayIntent> intents = EnumSet.of(
|
EnumSet<GatewayIntent> intents = EnumSet.of(
|
||||||
// We need messages in guilds to accept commands from users
|
// We need messages in guilds to accept commands from users
|
||||||
GatewayIntent.GUILD_MESSAGES,
|
GatewayIntent.GUILD_MESSAGES,
|
||||||
// We need voice states to connect to the voice channel
|
// We need voice states to connect to the voice channel
|
||||||
GatewayIntent.GUILD_VOICE_STATES
|
GatewayIntent.GUILD_VOICE_STATES
|
||||||
);
|
);
|
||||||
|
|
||||||
JDABuilder builder = JDABuilder.createDefault(args[0], intents);
|
JDABuilder builder = JDABuilder.createDefault(args[0], intents);
|
||||||
|
|
||||||
// Disable parts of the cache
|
// Disable parts of the cache
|
||||||
builder.disableCache(CacheFlag.MEMBER_OVERRIDES, CacheFlag.VOICE_STATE);
|
builder.disableCache(CacheFlag.MEMBER_OVERRIDES, CacheFlag.VOICE_STATE);
|
||||||
// Enable the bulk delete event
|
// Enable the bulk delete event
|
||||||
builder.setBulkDeleteSplittingEnabled(false);
|
builder.setBulkDeleteSplittingEnabled(false);
|
||||||
// Disable compression (not recommended)
|
// Disable compression (not recommended)
|
||||||
builder.setCompression(Compression.NONE);
|
builder.setCompression(Compression.NONE);
|
||||||
// Set activity (like "playing Something")
|
// Set activity (like "playing Something")
|
||||||
builder.setActivity(Activity.playing("music!"));
|
builder.setActivity(Activity.playing("music!"));
|
||||||
|
|
||||||
builder.addEventListeners(new Main());
|
builder.addEventListeners(new Main());
|
||||||
|
|
||||||
JDA jda = builder.build();
|
JDA jda = builder.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onGuildMessageReceived(GuildMessageReceivedEvent event)
|
public void onGuildMessageReceived(GuildMessageReceivedEvent event)
|
||||||
|
@ -83,23 +83,20 @@ public class Main extends ListenerAdapter
|
||||||
{
|
{
|
||||||
String arg = content.substring("!join ".length());
|
String arg = content.substring("!join ".length());
|
||||||
onJoinCommand(event, guild, arg);
|
onJoinCommand(event, guild, arg);
|
||||||
}
|
} else if (content.equals("!join"))
|
||||||
else if (content.equals("!join"))
|
|
||||||
{
|
|
||||||
onJoinCommand(event);
|
onJoinCommand(event);
|
||||||
|
else if (content.startsWith("!play "))
|
||||||
|
{
|
||||||
|
String arg = content.substring("!join ".length());
|
||||||
|
onPlayCommand(event, guild, arg);
|
||||||
}
|
}
|
||||||
else if (content.startsWith("!play "))
|
|
||||||
{
|
|
||||||
String arg = content.substring("!join ".length());
|
|
||||||
onPlayCommand(event, guild, arg);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle command without arguments.
|
* Handle command without arguments.
|
||||||
*
|
*
|
||||||
* @param event
|
* @param event
|
||||||
* The event for this command
|
* The event for this command
|
||||||
*/
|
*/
|
||||||
private void onJoinCommand(GuildMessageReceivedEvent event)
|
private void onJoinCommand(GuildMessageReceivedEvent event)
|
||||||
{
|
{
|
||||||
|
@ -111,31 +108,27 @@ public class Main extends ListenerAdapter
|
||||||
{
|
{
|
||||||
connectTo(channel); // Join the channel of the user
|
connectTo(channel); // Join the channel of the user
|
||||||
onConnecting(channel, event.getChannel()); // Tell the user about our success
|
onConnecting(channel, event.getChannel()); // Tell the user about our success
|
||||||
}
|
} else
|
||||||
else
|
|
||||||
{
|
|
||||||
onUnknownChannel(event.getChannel(), "your voice channel"); // Tell the user about our failure
|
onUnknownChannel(event.getChannel(), "your voice channel"); // Tell the user about our failure
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle command with arguments.
|
* Handle command with arguments.
|
||||||
*
|
*
|
||||||
* @param event
|
* @param event
|
||||||
* The event for this command
|
* The event for this command
|
||||||
* @param guild
|
* @param guild
|
||||||
* The guild where its happening
|
* The guild where its happening
|
||||||
* @param arg
|
* @param arg
|
||||||
* The input argument
|
* The input argument
|
||||||
*/
|
*/
|
||||||
private void onJoinCommand(GuildMessageReceivedEvent event, Guild guild, String arg)
|
private void onJoinCommand(GuildMessageReceivedEvent event, Guild guild, String arg)
|
||||||
{
|
{
|
||||||
boolean isNumber = arg.matches("\\d+"); // This is a regular expression that ensures the input consists of digits
|
boolean isNumber = arg.matches("\\d+"); // This is a regular expression that ensures the input consists of digits
|
||||||
VoiceChannel channel = null;
|
VoiceChannel channel = null;
|
||||||
if (isNumber) // The input is an id?
|
if (isNumber) // The input is an id?
|
||||||
{
|
|
||||||
channel = guild.getVoiceChannelById(arg);
|
channel = guild.getVoiceChannelById(arg);
|
||||||
}
|
|
||||||
if (channel == null) // Then the input must be a name?
|
if (channel == null) // Then the input must be a name?
|
||||||
{
|
{
|
||||||
List<VoiceChannel> channels = guild.getVoiceChannelsByName(arg, true);
|
List<VoiceChannel> channels = guild.getVoiceChannelsByName(arg, true);
|
||||||
|
@ -153,48 +146,47 @@ public class Main extends ListenerAdapter
|
||||||
onConnecting(channel, textChannel); // Let the user know, we were successful!
|
onConnecting(channel, textChannel); // Let the user know, we were successful!
|
||||||
}
|
}
|
||||||
|
|
||||||
private void onPlayCommand(GuildMessageReceivedEvent event, Guild guild, String arg)
|
private void onPlayCommand(GuildMessageReceivedEvent event, Guild guild, String arg)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
event.getChannel().sendMessage("Downloading ...").queue();
|
event.getChannel().sendMessage("Downloading ...").queue();
|
||||||
String destination = downloadSong(arg);
|
String destination = downloadSong(arg);
|
||||||
musicHandler.addSong(new File(destination));
|
musicHandler.addSong(new File(destination));
|
||||||
event.getChannel().sendMessage("Downloaded and added to queue!").queue();
|
event.getChannel().sendMessage("Downloaded and added to queue!").queue();
|
||||||
|
|
||||||
} catch (IOException | InterruptedException | RuntimeException ex)
|
} catch (IOException | InterruptedException | RuntimeException ex)
|
||||||
{
|
{
|
||||||
event.getChannel().sendMessage("Failed to download! Reason: " + ex.getMessage()).queue();
|
event.getChannel().sendMessage("Failed to download! Reason: " + ex.getMessage()).queue();
|
||||||
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
|
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private String downloadSong(String arg) throws IOException, RuntimeException, InterruptedException
|
private String downloadSong(String arg) throws IOException, RuntimeException, InterruptedException
|
||||||
{
|
{
|
||||||
String cmd = "/usr/bin/youtube-dl -x --audio-format=wav "+arg;
|
String cmd = "/usr/bin/youtube-dl -x --audio-format=wav " + arg;
|
||||||
System.out.println("Running command: " + cmd);
|
System.out.println("Running command: " + cmd);
|
||||||
// Process exec = Runtime.getRuntime().exec().split(" "));
|
// Process exec = Runtime.getRuntime().exec().split(" "));
|
||||||
Process exec = new ProcessBuilder(cmd.split(" ")).redirectOutput(ProcessBuilder.Redirect.PIPE).start();
|
Process exec = new ProcessBuilder(cmd.split(" ")).redirectOutput(ProcessBuilder.Redirect.PIPE).start();
|
||||||
exec.waitFor(10000, TimeUnit.MILLISECONDS);
|
exec.waitFor(10000, TimeUnit.MILLISECONDS);
|
||||||
InputStream in = exec.getInputStream();
|
InputStream in = exec.getInputStream();
|
||||||
String output = new String(in.readAllBytes(), Charset.defaultCharset());
|
String output = new String(in.readAllBytes(), Charset.defaultCharset());
|
||||||
System.out.println(output);
|
System.out.println(output);
|
||||||
if (exec.exitValue() != 0)
|
if (exec.exitValue() != 0)
|
||||||
throw new RuntimeException("youtube-dl failed with error " + exec.exitValue());
|
throw new RuntimeException("youtube-dl failed with error " + exec.exitValue());
|
||||||
Matcher matcher = Pattern.compile("Destination: (.*\\.wav)").matcher(output);
|
Matcher matcher = Pattern.compile("Destination: (.*\\.wav)").matcher(output);
|
||||||
matcher.find();
|
matcher.find();
|
||||||
String destination = matcher.group(1);
|
String destination = matcher.group(1);
|
||||||
return destination;
|
return destination;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Inform user about successful connection.
|
* Inform user about successful connection.
|
||||||
*
|
*
|
||||||
* @param channel
|
* @param channel
|
||||||
* The voice channel we connected to
|
* The voice channel we connected to
|
||||||
* @param textChannel
|
* @param textChannel
|
||||||
* The text channel to send the message in
|
* The text channel to send the message in
|
||||||
*/
|
*/
|
||||||
private void onConnecting(VoiceChannel channel, TextChannel textChannel)
|
private void onConnecting(VoiceChannel channel, TextChannel textChannel)
|
||||||
{
|
{
|
||||||
|
@ -205,9 +197,10 @@ public class Main extends ListenerAdapter
|
||||||
* The channel to connect to is not known to us.
|
* The channel to connect to is not known to us.
|
||||||
*
|
*
|
||||||
* @param channel
|
* @param channel
|
||||||
* The message channel (text channel abstraction) to send failure information to
|
* The message channel (text channel abstraction) to send failure
|
||||||
|
* information to
|
||||||
* @param comment
|
* @param comment
|
||||||
* The information of this channel
|
* The information of this channel
|
||||||
*/
|
*/
|
||||||
private void onUnknownChannel(MessageChannel channel, String comment)
|
private void onUnknownChannel(MessageChannel channel, String comment)
|
||||||
{
|
{
|
||||||
|
@ -218,19 +211,18 @@ public class Main extends ListenerAdapter
|
||||||
* Connect to requested channel and start echo handler
|
* Connect to requested channel and start echo handler
|
||||||
*
|
*
|
||||||
* @param channel
|
* @param channel
|
||||||
* The channel to connect to
|
* The channel to connect to
|
||||||
*/
|
*/
|
||||||
private void connectTo(VoiceChannel channel)
|
private void connectTo(VoiceChannel channel)
|
||||||
{
|
{
|
||||||
Guild guild = channel.getGuild();
|
Guild guild = channel.getGuild();
|
||||||
// Get an audio manager for this guild, this will be created upon first use for each guild
|
// Get an audio manager for this guild, this will be created upon first use for each guild
|
||||||
AudioManager audioManager = guild.getAudioManager();
|
AudioManager audioManager = guild.getAudioManager();
|
||||||
musicHandler = new MusicHandler();
|
musicHandler = new MusicHandler();
|
||||||
// Create our Send/Receive handler for the audio connection
|
// Create our Send/Receive handler for the audio connection
|
||||||
// EchoHandler handler = new EchoHandler();
|
// EchoHandler handler = new EchoHandler();
|
||||||
|
|
||||||
// The order of the following instructions does not matter!
|
// The order of the following instructions does not matter!
|
||||||
|
|
||||||
// Set the sending handler to our echo system
|
// Set the sending handler to our echo system
|
||||||
audioManager.setSendingHandler(musicHandler);
|
audioManager.setSendingHandler(musicHandler);
|
||||||
// Set the receiving handler to the same echo system, otherwise we can't echo anything
|
// Set the receiving handler to the same echo system, otherwise we can't echo anything
|
||||||
|
@ -238,6 +230,6 @@ public class Main extends ListenerAdapter
|
||||||
// Connect to the voice channel
|
// Connect to the voice channel
|
||||||
audioManager.openAudioConnection(channel);
|
audioManager.openAudioConnection(channel);
|
||||||
}
|
}
|
||||||
private MusicHandler musicHandler;
|
private MusicHandler musicHandler;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -26,115 +26,115 @@ import net.dv8tion.jda.api.audio.AudioSendHandler;
|
||||||
public class MusicHandler implements AudioSendHandler, Closeable
|
public class MusicHandler implements AudioSendHandler, Closeable
|
||||||
{
|
{
|
||||||
|
|
||||||
private final Queue<File> songQueue = new ConcurrentLinkedQueue<>();
|
private final Queue<File> songQueue = new ConcurrentLinkedQueue<>();
|
||||||
private File currentSong;
|
private File currentSong;
|
||||||
private AudioInputStream din = null;
|
private AudioInputStream din = null;
|
||||||
private final Queue<byte[]> queue = new ConcurrentLinkedQueue<>();
|
private final Queue<byte[]> queue = new ConcurrentLinkedQueue<>();
|
||||||
private int byteCount;
|
private int byteCount;
|
||||||
|
|
||||||
public MusicHandler()
|
public MusicHandler()
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addSong(File file)
|
public void addSong(File file)
|
||||||
{
|
{
|
||||||
System.out.println("Song added to queue: " + file.getAbsolutePath());
|
System.out.println("Song added to queue: " + file.getAbsolutePath());
|
||||||
songQueue.add(file);
|
songQueue.add(file);
|
||||||
if (!canProvide())
|
if (!canProvide())
|
||||||
nextSong();
|
nextSong();
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean nextSong()
|
private boolean nextSong()
|
||||||
{
|
{
|
||||||
AudioInputStream in = null;
|
AudioInputStream in = null;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (din != null)
|
if (din != null)
|
||||||
{
|
{
|
||||||
din.close();
|
din.close();
|
||||||
din = null;
|
din = null;
|
||||||
}
|
}
|
||||||
if (currentSong != null)
|
if (currentSong != null)
|
||||||
{
|
{
|
||||||
currentSong.delete();
|
currentSong.delete();
|
||||||
currentSong = null;
|
currentSong = null;
|
||||||
}
|
}
|
||||||
currentSong = songQueue.poll();
|
currentSong = songQueue.poll();
|
||||||
if (currentSong == null)
|
if (currentSong == null)
|
||||||
return false;
|
return false;
|
||||||
System.out.println("Playing song " + currentSong.getAbsolutePath());
|
System.out.println("Playing song " + currentSong.getAbsolutePath());
|
||||||
in = AudioSystem.getAudioInputStream(currentSong);
|
in = AudioSystem.getAudioInputStream(currentSong);
|
||||||
AudioFormat decodedFormat = AudioSendHandler.INPUT_FORMAT;
|
AudioFormat decodedFormat = AudioSendHandler.INPUT_FORMAT;
|
||||||
din = AudioSystem.getAudioInputStream(decodedFormat, in);
|
din = AudioSystem.getAudioInputStream(decodedFormat, in);
|
||||||
byteCount = 3840;
|
byteCount = 3840;
|
||||||
while (queue.size() < 500)
|
while (queue.size() < 500)
|
||||||
if (!readData())
|
if (!readData())
|
||||||
break;
|
break;
|
||||||
System.out.println("Queue filled to " + queue.size());
|
System.out.println("Queue filled to " + queue.size());
|
||||||
return true;
|
return true;
|
||||||
} catch (UnsupportedAudioFileException | IOException ex)
|
} catch (UnsupportedAudioFileException | IOException ex)
|
||||||
{
|
{
|
||||||
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
|
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
|
||||||
} finally
|
} finally
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean canProvide()
|
public boolean canProvide()
|
||||||
{
|
{
|
||||||
// If we have something in our buffer we can provide it to the send system
|
// If we have something in our buffer we can provide it to the send system
|
||||||
return !queue.isEmpty();
|
return !queue.isEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ByteBuffer provide20MsAudio()
|
public ByteBuffer provide20MsAudio()
|
||||||
{
|
{
|
||||||
// use what we have in our buffer to send audio as PCM
|
// use what we have in our buffer to send audio as PCM
|
||||||
while (queue.size() < 500)
|
while (queue.size() < 500)
|
||||||
if (!readData())
|
if (!readData())
|
||||||
if (!nextSong())
|
if (!nextSong())
|
||||||
break;
|
break;
|
||||||
byte[] data = queue.poll();
|
byte[] data = queue.poll();
|
||||||
return data == null ? null : ByteBuffer.wrap(data); // Wrap this in a java.nio.ByteBuffer
|
return data == null ? null : ByteBuffer.wrap(data); // Wrap this in a java.nio.ByteBuffer
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean readData()
|
private boolean readData()
|
||||||
{
|
{
|
||||||
if (din == null)
|
if (din == null)
|
||||||
return false;
|
return false;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// if (din.available() == 0)
|
// if (din.available() == 0)
|
||||||
// return false;
|
// return false;
|
||||||
int bytesToRead = byteCount;
|
int bytesToRead = byteCount;
|
||||||
if (din.available() > 0 && din.available() < bytesToRead)
|
if (din.available() > 0 && din.available() < bytesToRead)
|
||||||
bytesToRead = din.available();
|
bytesToRead = din.available();
|
||||||
byte[] bytes = new byte[bytesToRead];
|
byte[] bytes = new byte[bytesToRead];
|
||||||
// byte[] bytes = din.readNBytes(bytesToRead);
|
// byte[] bytes = din.readNBytes(bytesToRead);
|
||||||
int read = din.read(bytes);
|
int read = din.read(bytes);
|
||||||
if (read < 0)
|
if (read < 0)
|
||||||
return false;
|
return false;
|
||||||
queue.add(bytes);
|
queue.add(bytes);
|
||||||
} catch (IOException ex)
|
} catch (IOException ex)
|
||||||
{
|
{
|
||||||
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
|
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isOpus()
|
public boolean isOpus()
|
||||||
{
|
{
|
||||||
return false; //To change body of generated methods, choose Tools | Templates.
|
return false; //To change body of generated methods, choose Tools | Templates.
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void close() throws IOException
|
public void close() throws IOException
|
||||||
{
|
{
|
||||||
din.close();
|
din.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue