Discord bot that plays music from every website ever via youtube-dl
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Chords/src/main/java/moe/nekojimi/chords/Main.java

323 lines
12 KiB

3 years ago
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package moe.nekojimi.chords;
import java.net.MalformedURLException;
import java.net.URL;
3 years ago
import java.util.*;
import javax.security.auth.login.LoginException;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.managers.AudioManager;
import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.utils.Compression;
import net.dv8tion.jda.api.utils.cache.CacheFlag;
/**
*
* @author jimj316
*/
public class Main extends ListenerAdapter
{
private MusicHandler musicHandler;
private Downloader downloader;
private JDA jda;
3 years ago
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws LoginException
{
// We only need 2 gateway intents enabled for this example:
3 years ago
EnumSet<GatewayIntent> intents = EnumSet.of(
3 years ago
// We need messages in guilds to accept commands from users
GatewayIntent.GUILD_MESSAGES,
// We need voice states to connect to the voice channel
GatewayIntent.GUILD_VOICE_STATES
3 years ago
);
3 years ago
JDABuilder builder = JDABuilder.createDefault(args[0], intents);
3 years ago
3 years ago
// Disable parts of the cache
builder.disableCache(CacheFlag.MEMBER_OVERRIDES, CacheFlag.VOICE_STATE);
// Enable the bulk delete event
builder.setBulkDeleteSplittingEnabled(false);
// Disable compression (not recommended)
builder.setCompression(Compression.NONE);
// Set activity (like "playing Something")
builder.setActivity(Activity.playing("music!"));
3 years ago
final Main listener = new Main();
builder.addEventListeners(listener);
3 years ago
3 years ago
JDA jda = builder.build();
listener.setJda(jda);
}
public Main()
{
downloader = new Downloader();
downloader.setMessageHandler((Song song, Exception ex) ->
{
TextChannel channel = jda.getTextChannelById(song.getRequestedIn());
if (channel != null)
if (ex == null)
if (song.getLocation() != null)
channel.sendMessage("Finished downloading track for " + song.getRequestedBy() + ", added to queue!").queue();
else
channel.sendMessage("Now downloading track for " + song.getRequestedBy() + " ...").queue();
else
channel.sendMessage("Failed to download track for " + song.getRequestedBy() + "! Reason: " + ex.getMessage()).queue();
});
}
public void setJda(JDA jda)
{
this.jda = jda;
3 years ago
}
3 years ago
@Override
public void onGuildMessageReceived(GuildMessageReceivedEvent event)
{
Message message = event.getMessage();
User author = message.getAuthor();
String content = message.getContentRaw();
Guild guild = event.getGuild();
// Ignore message if bot
if (author.isBot())
return;
try
3 years ago
{
String arg = "";
if (content.contains(" "))
arg = content.split(" ", 2)[1];
if (content.startsWith("!join "))
onJoinCommand(event, guild, arg);
else if (content.equals("!join"))
onJoinCommand(event);
else if (content.startsWith("!play "))
onPlayCommand(event, guild, arg);
else if (content.startsWith("!queue"))
onQueueCommand(event, guild);
else if (content.startsWith("!remove "))
onRemoveCommand(event, guild, arg);
else if (content.startsWith("!restart"))
onRestartCommand(event);
else if (content.startsWith("!skip"))
onSkipCommand(event);
else if (content.startsWith("!"))
onHelpCommand(event);
} catch (Exception ex)
3 years ago
{
event.getChannel().sendMessage("Error in command! " + ex.getMessage()).queue();
3 years ago
}
}
/**
* Handle command without arguments.
*
* @param event
3 years ago
* The event for this command
3 years ago
*/
private void onJoinCommand(GuildMessageReceivedEvent event)
{
// Note: None of these can be null due to our configuration with the JDABuilder!
Member member = event.getMember(); // Member is the context of the user for the specific guild, containing voice state and roles
GuildVoiceState voiceState = member.getVoiceState(); // Check the current voice state of the user
VoiceChannel channel = voiceState.getChannel(); // Use the channel the user is currently connected to
// if (channel != null)
// {
// connectTo(channel); // Join the channel of the user
// onConnecting(channel, event.getChannel()); // Tell the user about our success
// } else
// onUnknownChannel(event.getChannel(), "your voice channel"); // Tell the user about our failure
onJoinCommand(event, member.getGuild(), channel.getId());
3 years ago
}
/**
* Handle command with arguments.
*
* @param event
3 years ago
* The event for this command
3 years ago
* @param guild
3 years ago
* The guild where its happening
3 years ago
* @param arg
3 years ago
* The input argument
3 years ago
*/
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
VoiceChannel channel = null;
3 years ago
if (isNumber) // The input is an id?
3 years ago
channel = guild.getVoiceChannelById(arg);
if (channel == null) // Then the input must be a name?
{
List<VoiceChannel> channels = guild.getVoiceChannelsByName(arg, true);
if (!channels.isEmpty()) // Make sure we found at least one exact match
channel = channels.get(0); // We found a channel! This cannot be null.
}
TextChannel textChannel = event.getChannel();
if (channel == null) // I have no idea what you want mr user
{
onUnknownChannel(textChannel, arg); // Let the user know about our failure
return;
}
connectTo(channel); // We found a channel to connect to!
onConnecting(channel, textChannel); // Let the user know, we were successful!
}
3 years ago
private void onPlayCommand(GuildMessageReceivedEvent event, Guild guild, String arg)
{
try
{
Song song = new Song(new URL(arg));
song.setRequestedBy(event.getAuthor().getName());
song.setRequestedIn(event.getChannel().getId());
// event.getChannel().sendMessage("Downloading ...").queue();
downloader.accept(song);
// boolean ok = downloadSong(song);
// if (ok)
// {
// musicHandler.addSong(song);
// if (musicHandler.isPlaying())
// musicHandler.setPlaying(true);
// event.getChannel().sendMessage("Downloaded and added to queue!").queue();
// }
} catch (MalformedURLException ex)
{
event.getChannel().sendMessage("That's not a valid URL you idiot! " + ex.getMessage()).queue();
3 years ago
}
}
3 years ago
private void onRestartCommand(GuildMessageReceivedEvent event)
{
// TODO: this needs to clear the current data queue
boolean ok = musicHandler.restartSong();
if (ok)
event.getChannel().sendMessage("Restarted current song!").queue();
else
event.getChannel().sendMessage("Cannot restart!").queue();
}
private void onSkipCommand(GuildMessageReceivedEvent event)
{
boolean ok = musicHandler.nextSong(true);
if (ok)
event.getChannel().sendMessage("Skipped to next song!").queue();
else
event.getChannel().sendMessage("There's no more songs!").queue();
}
private void onQueueCommand(GuildMessageReceivedEvent event, Guild guild)
{
Queue<Song> songQueue = musicHandler.getSongQueue();
String message = new String();
int i = 1;
message += "Now playing: " + musicHandler.getCurrentSong() + "\n";
message += "---\n";
for (Song song : songQueue)
message += (i) + ": " + song + "\n";
event.getChannel().sendMessage(message).queue();
}
private void onRemoveCommand(GuildMessageReceivedEvent event, Guild guild, String arg)
{
try
{
int i = Integer.parseInt(arg);
boolean removed = musicHandler.removeSong(i - 1);
final int size = musicHandler.getSongQueue().size();
if (removed)
event.getChannel().sendMessage("Song removed.").queue();
else if (size > 1)
event.getChannel().sendMessage("That's not a number between 1 and " + size + "!").queue();
else if (size == 1)
event.getChannel().sendMessage("There's only one song to remove and that's not one of them!").queue();
} catch (NumberFormatException ex)
{
event.getChannel().sendMessage(arg + " isn't a number!").queue();
}
}
private void onHelpCommand(GuildMessageReceivedEvent event)
{
String help = "Commands available:\n"
+ "!join <Channel> - Joins a voice channel\n"
+ "!play <URL> - Downloads the track at that URL and adds it to the queue.\n"
+ "!queue - Show the songs currently playing and the current queue.\n"
+ "!remove <Index> - Remove the song at position <Index> from the queue.\n"
+ "!skip - Skip the current song and play the next one.\n"
+ "!restart - Try playing the current song again in case it goes wrong.\n";
event.getChannel().sendMessage(help).queue();
}
3 years ago
/**
* Inform user about successful connection.
*
* @param channel
3 years ago
* The voice channel we connected to
3 years ago
* @param textChannel
3 years ago
* The text channel to send the message in
3 years ago
*/
private void onConnecting(VoiceChannel channel, TextChannel textChannel)
{
textChannel.sendMessage("Connecting to " + channel.getName()).queue(); // never forget to queue()!
}
/**
* The channel to connect to is not known to us.
*
* @param channel
3 years ago
* The message channel (text channel abstraction) to send failure
* information to
3 years ago
* @param comment
3 years ago
* The information of this channel
3 years ago
*/
private void onUnknownChannel(MessageChannel channel, String comment)
{
channel.sendMessage("Unable to connect to ``" + comment + "``, no such channel!").queue(); // never forget to queue()!
}
/**
* Connect to requested channel and start echo handler
*
* @param channel
3 years ago
* The channel to connect to
3 years ago
*/
private void connectTo(VoiceChannel channel)
{
Guild guild = channel.getGuild();
// Get an audio manager for this guild, this will be created upon first use for each guild
AudioManager audioManager = guild.getAudioManager();
3 years ago
musicHandler = new MusicHandler();
downloader.setNext(musicHandler);
3 years ago
// Create our Send/Receive handler for the audio connection
// EchoHandler handler = new EchoHandler();
// The order of the following instructions does not matter!
// Set the sending handler to our echo system
audioManager.setSendingHandler(musicHandler);
// Set the receiving handler to the same echo system, otherwise we can't echo anything
// audioManager.setReceivingHandler(handler);
// Connect to the voice channel
audioManager.openAudioConnection(channel);
}
}