Command usage done, start implementing configure command, refactor music manager

This commit is contained in:
anthorob committed 2022-02-18 17:18:59 -05:00
1 parent d849b80b7b
commit f68d778c0c
22 files changed
+299 -236

No files matched your search

+6 -10
View File
@@ -25,9 +25,9 @@ import java.util.concurrent.ConcurrentHashMap;
public class GuildManager {
public enum GuildSetting {
MUSIC_ROLE("music.role", null),
MUSIC_CHANNEL("music.channel", null),
BLACKLIST_CHANNELS("blacklist.exclude.channels", null);
MUSIC_ROLE("MUSIC_ROLE", ""),
MUSIC_CHANNEL("MUSIC_CHANNEL", ""),
BLACKLIST_CHANNELS("BLACKLIST_EXCLUDE_CHANNELS", "");
private final String setting;
private final String defaultValue;
@@ -57,7 +57,7 @@ public class GuildManager {
public static final Logger logger = LoggerFactory.getLogger(GuildManager.class);
private static final Map<String, GuildManager> managers = new ConcurrentHashMap<>();
private final Guild guild;
private final OGuild guildEntity;
private OGuild guildEntity;
private final IMessageRateLimiter rateLimiter;
private GuildManager(Guild guild) {
@@ -65,7 +65,6 @@ public class GuildManager {
handleJoinEvent();
this.guildEntity = new OGuild(guild.getId());
this.rateLimiter = new MessageRateLimiterImpl();
managers.put(guild.getId(), this);
}
@@ -124,16 +123,12 @@ public class GuildManager {
}
public static boolean reloadSettingsForGuild(Guild guild) {
if (managers.containsKey(guild.getId())) {
GuildManager manager = GuildManager.getManager(guild.getId());
manager.reloadSettings();
return true;
}
return false;
}
public void checkAndLogMessage(Message message, Member member, TextChannel channel) {
//((DBMessage) DBController.get("message")).log(guild, channel, member, message);
}
@@ -148,7 +143,8 @@ public class GuildManager {
}
public void reloadSettings() {
guildEntity.reloadSettings();
logger.debug("Reloading guild entity: " + guild.getId());
this.guildEntity = new OGuild(guild.getId());
}
public void handleJoinEvent() {
@@ -5,34 +5,6 @@ import net.dv8tion.jda.api.entities.Member;
public abstract class AbstractCommand implements ICommand {
/**
* @return if the command needs administrator privilege
*/
public abstract boolean needAdmin();
/**
* @return if the command should be loaded at runtime
*/
public abstract boolean isEnabled();
/**
* The command name that a user will write in a channel
*
* @return the name of the command.
*/
public abstract String getCommandName();
/**
* @return all the aliases the command has
*/
public abstract String[] getAlias();
public abstract String getUsage();
public abstract String getDescription();
public abstract CommandType getType();
@Override
public boolean canBeExecutedBy(Guild guild, Member member) {
return true;
@@ -7,6 +7,7 @@ package netneutrality.command;
*/
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import netneutrality.ThreadManager;
@@ -133,13 +134,17 @@ public class CommandContext {
}
public void replyPrivate(String msg) {
user.openPrivateChannel().flatMap(channel -> channel.sendMessage(msg)).queue();
replyPrivate(new MessageBuilder().append(msg).build());
}
public void replyPrivate(Message msg) {
user.openPrivateChannel().flatMap(channel -> channel.sendMessage(msg)).queue();
}
public void replyPrivate(MessageEmbed embed, MessageEmbed... embeds) {
user.openPrivateChannel().flatMap(channel -> channel.sendMessageEmbeds(embed, embeds)).queue();
}
public void replyPrivate(Collection<? extends MessageEmbed> embeds) {
user.openPrivateChannel().flatMap(channel -> channel.sendMessageEmbeds(embeds)).queue();
}
@@ -5,6 +5,7 @@ package netneutrality.command;/*
* https://discord.gg/CdFcyQ
*/
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
@@ -17,13 +18,25 @@ public class CommandUsage {
}
private final Type type;
private final String[] values;
private final String description;
public Argument(Type t, String desc) {
public Argument(Type t, String[] values, String desc) {
if (t == Type.REQUIRED && (values == null || values.length == 0))
throw new IllegalArgumentException("Command usage: values can't be null if type is required");
if (t == Type.OPTIONAL && (desc == null || desc.isEmpty()))
throw new IllegalArgumentException("Command usage: description can't be null if type is optional");
this.type = t;
this.values = values;
this.description = desc;
}
public String[] getValues() {
return values;
}
public String getDescription() {
return description;
}
@@ -39,11 +52,35 @@ public class CommandUsage {
Collections.addAll(args, arguments);
}
public CommandUsage addArgument(Argument argument) {
args.add(argument);
return this;
}
public static CommandUsage create(Argument... arguments) {
return new CommandUsage(arguments);
}
public Set<Argument> getArguments() {
return args;
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Available arguments: ").append(args.size()).append("\n");
for (Argument arg : args) {
sb.append("<");
if (arg.getType() == Argument.Type.OPTIONAL)
sb.append("Optional argument: ").append(arg.getDescription());
if (arg.getType() == Argument.Type.REQUIRED) {
sb.append("required: ").append(Arrays.toString(arg.getValues()));
if (arg.getDescription() != null && !arg.getDescription().isEmpty())
sb.append(": ").append(arg.getDescription());
}
sb.append("> ");
}
return sb.toString();
}
}
@@ -12,6 +12,34 @@ import netneutrality.exceptions.CommandExecutionException;
public interface ICommand {
/**
* @return if the command needs administrator privilege
*/
boolean needAdmin();
/**
* @return if the command should be loaded at runtime
*/
boolean isEnabled();
/**
* The command name that a user will write in a channel
*
* @return the name of the command.
*/
String getCommandName();
/**
* @return all the aliases the command has
*/
String[] getAlias();
String getUsage();
String getDescription();
CommandType getType();
boolean canBeExecutedBy(Guild guild, Member member);
/**
@@ -8,10 +8,7 @@ package netneutrality.command.basic;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.MessageEmbed;
import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandManager;
import netneutrality.command.CommandType;
import netneutrality.command.*;
import netneutrality.utils.MessageFunction;
import netneutrality.utils.UserFunction;
@@ -56,9 +53,32 @@ public class HelpCommand extends AbstractCommand {
@Override
public void execute(CommandContext context) {
List<MessageEmbed> help = MessageFunction.buildHelpMessage(CommandManager.commands, CommandManager.commandsAlias, UserFunction.isAdmin(context.getGuildUser()));
if (context.getArgumentsAsArray().length == 0) {
List<MessageEmbed> help = MessageFunction.buildHelpMessage(CommandManager.commands, UserFunction.isAdmin(context.getGuildUser()));
context.reply(new MessageBuilder().append(context.getDiscordUser()).append(" help has been sent your way!").build());
context.replyPrivate(help);
}
if (context.getArgumentsAsArray().length == 1) {
String cmd = context.getArg(0);
if (CommandManager.commands.containsKey(cmd) || CommandManager.commandsAlias.containsKey(cmd)) {
AbstractCommand c = CommandManager.commands.containsKey(cmd) ? CommandManager.commands.get(cmd) : CommandManager.commandsAlias.get(cmd);
if (c.needAdmin() && !UserFunction.isAdmin(context.getGuildUser())) {
context.replyPrivate("Command [" + c.getCommandName() + "] requires admin privileges");
}
System.out.println(CommandUsage.create(new CommandUsage.Argument(CommandUsage.Argument.Type.REQUIRED, new String[] {"get", "add"}, "")));
MessageEmbed help = MessageFunction.buildHelpMessage(c);
context.reply(new MessageBuilder().append(context.getDiscordUser()).append(" help has been sent your way!").build());
context.replyPrivate(help);
}
}
}
}
@@ -6,9 +6,15 @@ package netneutrality.command.bot;
* https://discord.gg/CdFcyQ
*/
import net.dv8tion.jda.api.entities.Role;
import netneutrality.GuildManager;
import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType;
import netneutrality.db.DBController;
import netneutrality.db.MysqlDatabase;
import java.util.List;
public class ConfigureCommand extends AbstractCommand {
@Override
@@ -48,6 +54,42 @@ public class ConfigureCommand extends AbstractCommand {
@Override
public void execute(CommandContext context) {
String[] args = context.getArgumentsAsArray();
MysqlDatabase database = DBController.get();
if (args.length > 0) {
if (context.getArg(0).equals("musicrole")) {
if (args.length == 1) {
String roleDb = GuildManager.getManager(context.getGuild()).getSetting(GuildManager.GuildSetting.MUSIC_ROLE);
Role role = null;
if (!roleDb.isEmpty()) {
role = context.getGuild().getRoleById(roleDb);
}
context.reply("Current role needed to use music commands (default is anyone): %s", (role == null ? "Everyone" : role.getName()));
}
if (args.length == 2) {
List<Role> roles = context.getMessage().getMentionedRoles();
if (roles.size() == 1) {
Role role = roles.get(0);
if (role.getGuild().getId().equals(context.getGuild().getId())) {
database.prepareAndExecuteAsync("UPDATE guild_settings SET music_role = ? WHERE guild_id = ?", role.getId(), context.getGuild().getId()).blocking();
context.reply("Successfully set %s as the role needed for music command", role.getAsMention());
}
}
if (context.getArg(1).equals("reset")) {
database.prepareAndExecuteAsync("UPDATE guild_settings SET music_role = null WHERE guild_id = ?", context.getGuild().getId()).blocking();
context.reply("Successful reset of the role");
}
}
}
}
}
}
@@ -14,6 +14,8 @@ import netneutrality.db.controllers.DBBlacklist;
import netneutrality.db.models.MBlacklist;
import netneutrality.exceptions.CommandExecutionException;
import java.util.ArrayList;
public class BlacklistCommand extends AbstractCommand {
@Override
@@ -69,13 +71,12 @@ public class BlacklistCommand extends AbstractCommand {
context.getChannel().sendMessage("Retrieving list, please wait...").queue(t -> {
StringBuilder sb = new StringBuilder();
controller.getBlacklistFromServer(context.getGuild().getId(), mBlacklists -> {
for (MBlacklist bl : mBlacklists) {
ArrayList<MBlacklist> blacklists = controller.getBlacklistFromServer(context.getGuild().getId());
for (MBlacklist bl : blacklists) {
sb.append(bl.getWord()).append(" -> ").append(bl.isEnabled() ? "enabled" : "disabled").append("\n");
}
t.editMessage("List of blacklisted words for this server [" + context.getGuild().getName() + "] :\n" + (mBlacklists.isEmpty() ? "No word found" : sb.toString())).queue();
});
t.editMessage("List of blacklisted words for this server [" + context.getGuild().getName() + "] :\n" + (blacklists.isEmpty() ? "No word found" : sb.toString())).queue();
});
@@ -11,13 +11,9 @@ import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.CommandContext;
import netneutrality.music.MusicManager;
import netneutrality.utils.MusicUtils;
import netneutrality.utils.UserFunction;
public class SkipCommand extends AbstractMusicCommand {
@Override
public boolean needAdmin() {
return true;
}
@Override
public boolean isEnabled() {
return true;
@@ -40,7 +36,7 @@ public class SkipCommand extends AbstractMusicCommand {
@Override
public String getDescription() {
return "Used to skip to the next track in the queue (requires admin privileges)";
return "Used to skip to the next track in the queue (if no admin privileges, vote skip instead)";
}
@Override
@@ -48,11 +44,15 @@ public class SkipCommand extends AbstractMusicCommand {
MusicManager player = MusicManager.get(context.getGuild());
MusicUtils.checkIfConnected(player, context);
if (context.getArgumentsAsArray().length > 0) {
// Combined fonctionality of vote skip
if (context.getArgumentsAsArray().length > 0 && UserFunction.isAdmin(context.getGuildUser())) {
int skips = Integer.parseInt(context.getArg(0));
player.skip(skips);
} else {
if (UserFunction.isAdmin(context.getGuildUser()))
player.skip(1);
else
player.voteSkip(context);
}
}
@@ -51,18 +51,14 @@ public class AsyncMySqlAction {
}
public MTableModel blocking() {
MTableModel table = new MTableModel();
MTableModel table;
try {
table = switch (type) {
case INSERT -> executor.submit(() -> new MTableModel(db.insert(this.sqlString, this.params))).get();
case UPDATE -> executor.submit(() -> new MTableModel(db.update(this.sqlString, this.params))).get();
case DELETE -> executor.submit(() -> new MTableModel(db.delete(this.sqlString, this.params))).get();
case SELECT -> executor.submit(() -> db.prepareAndExecute(this.sqlString, this.tableName, this.params)).get();
case INSERT -> new MTableModel(db.insert(this.sqlString, this.params));
case UPDATE -> new MTableModel(db.update(this.sqlString, this.params));
case DELETE -> new MTableModel(db.delete(this.sqlString, this.params));
case SELECT -> db.prepareAndExecute(this.sqlString, this.tableName, this.params);
};
} catch (InterruptedException | ExecutionException e) {
return table;
}
return table;
}
@@ -46,23 +46,6 @@ public class DBBlacklist extends AbstractController {
return false;
}
public void getBlacklistFromServer(String serverId, Consumer<ArrayList<MBlacklist>> success) {
database.prepareAndExecuteAsync("SELECT * FROM blacklist WHERE guild_id = ? AND enabled = 1", serverId).async(model -> {
ArrayList<MBlacklist> output = new ArrayList<>();
if (model.getNbRows() > 0) {
for (int row = 0; row < model.getNbRows(); row++) {
MBlacklist bl = new MBlacklist(model.getRow(row));
output.add(bl);
}
}
success.accept(output);
});
}
public ArrayList<MBlacklist> getBlacklistFromServer(String serverId) {
MTableModel model = database.prepareAndExecuteAsync("SELECT * FROM blacklist WHERE guild_id = ? AND enabled = 1", serverId).blocking();
@@ -7,30 +7,11 @@ package netneutrality.db.controllers;
* https://discord.gg/CdFcyQ
*/
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.TextChannel;
import netneutrality.MusicBot;
import netneutrality.ThreadManager;
import netneutrality.db.AbstractController;
import netneutrality.db.DBController;
import netneutrality.db.models.MTableModel;
import netneutrality.handler.LogHandler;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.function.Consumer;
public class DBLogging extends AbstractController {
public void getLoggingChannel(String serverId, Consumer<TextChannel> success) {
database.prepareAndExecuteAsync("SELECT channelId FROM logging WHERE guild_id = ?", serverId).async((table) -> {
TextChannel txt = MusicBot.getJDA().getGuildById(serverId).getTextChannelById((String) table.getRow(0).get(0));
success.accept(txt);
});
}
public void setupLog(String serverId, String channelId) {
database.prepareAndExecuteAsync("INSERT INTO logging VALUES(?,?,?)", serverId, channelId, true).blocking();
}
@@ -42,7 +23,7 @@ public class DBLogging extends AbstractController {
public boolean isLoggingEnabled(String serverId, String channelId) {
MTableModel table = database.prepareAndExecuteAsync("SELECT enabled FROM logging WHERE guild_id = ? AND channelId = ?", serverId, channelId).blocking();
return Boolean.parseBoolean((String) table.getRow(0).get(0));
return (Boolean) table.getRow(0).get(0);
}
@Override
@@ -28,18 +28,18 @@ public class DBMessage extends AbstractController {
}
public void log(Guild guild, TextChannel channel, Member author, Message message) {
String serverid = guild.getId();
String channelid = channel.getId();
String userid = author.getId();
Date datesent = new Date(message.getTimeCreated().toInstant().toEpochMilli());
String messageid = message.getId();
String guildId = guild.getId();
String channelId = channel.getId();
String authorId = author.getId();
Date dateSent = new Date(message.getTimeCreated().toInstant().toEpochMilli());
String messageId = message.getId();
String msg = message.getContentRaw().trim();
database.prepareAndExecuteAsync("INSERT INTO log_message VALUES(?,?,?,?,?,?,?)", serverid, channelid, userid, datesent, messageid, msg, null).async();
database.prepareAndExecuteAsync("INSERT INTO log_message VALUES(?,?,?,?,?,?,?)", guildId, channelId, authorId, dateSent, messageId, msg, null).blocking();
}
public void logEdit(String messageId, String newMessage) {
database.prepareAndExecuteAsync("UPDATE log_message SET edited_message = ? WHERE message_id = ?", newMessage, messageId).async();
database.prepareAndExecuteAsync("UPDATE log_message SET edited_message = ? WHERE message_id = ?", newMessage, messageId).blocking();
}
@@ -52,26 +52,10 @@ public class DBMessage extends AbstractController {
return null;
}
public void getMessagesFromUser(String username, String serverName, int max, Consumer<ArrayList<MMessage>> success) {
database.prepareAndExecuteAsync("SELECT * FROM log_message WHERE user_id = ? AND server_id = ? ORDER BY dateSent DESC LIMIT ?", username, serverName, max).async(table -> {
ArrayList<MMessage> messages = new ArrayList<>();
if (table.getNbRows() > 0) {
for (int row = 0; row < max; row++) {
messages.add(new MMessage(table.getRowModel(row)));
}
}
success.accept(messages);
});
}
@Deprecated
public ArrayList<MMessage> getMessagesFromUser(String username, String serverName, int max) {
ArrayList<MMessage> messages = new ArrayList<>();
MTableModel table = database.prepareAndExecuteAsync("SELECT * FROM log_message WHERE user_id = ? AND server_id = ? ORDER BY date_sent DESC LIMIT ?", username, serverName, max).blocking();;
MTableModel table = database.prepareAndExecuteAsync("SELECT * FROM log_message WHERE user_id = ? AND guild_id = ? ORDER BY date_sent DESC LIMIT ?", username, serverName, max).blocking();
if (table.getNbRows() > 0) {
for (int row = 0; row < max; row++) {
messages.add(new MMessage(table.getRowModel(row)));
@@ -8,19 +8,6 @@ import netneutrality.db.models.MTableModel;
public class DBSettings extends AbstractController {
public void getSettingsByKey(String key, Consumer<Object> success) {
database.prepareAndExecuteAsync("SELECT value FROM settings WHERE skey = ?", key).async(table -> {
Object value = null;
if (table.getNbRows() == 1) {
value = table.getRowModel(0).getItem(0);
}
success.accept(value);
});
}
@Deprecated
public String getSettingsByKey(String key) {
@@ -61,7 +61,7 @@ public class OGuildSetting extends AbstractEntity {
for (int i = 0; i < columns.size(); i++) {
if (i == 0) continue;
String key = columns.get(i).replace('_', '.');
String key = columns.get(i).toUpperCase();
String value = (row.getItem(i) == null ? "" : row.getItem(i).toString());
settings.put(key, value);
@@ -0,0 +1,37 @@
package netneutrality.handler.hooks.voice;/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceJoinEvent;
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceLeaveEvent;
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceMoveEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.jetbrains.annotations.NotNull;
public class VoiceEventHandler extends ListenerAdapter {
@Override
public void onGuildVoiceJoin(@NotNull GuildVoiceJoinEvent event) {
super.onGuildVoiceJoin(event);
}
@Override
public void onGuildVoiceMove(@NotNull GuildVoiceMoveEvent event) {
super.onGuildVoiceMove(event);
}
@Override
public void onGuildVoiceLeave(@NotNull GuildVoiceLeaveEvent event) {
super.onGuildVoiceLeave(event);
}
}
@@ -6,6 +6,7 @@ package netneutrality.http.server;/*
*/
import com.sun.net.httpserver.HttpExchange;
import net.dv8tion.jda.api.entities.Guild;
import netneutrality.GuildManager;
import netneutrality.MusicBot;
import netneutrality.http.WebModule;
@@ -63,9 +64,16 @@ public class ActionHandler extends AbstractHandler {
if (path.startsWith("/actions/settings/reload/")) {
TreeMap<String, String> json = new TreeMap<>();
String[] args = exchange.getRequestURI().toString().split("/");
String guild = args[args.length - 1];
String guildId = args[args.length - 1];
json.put("status", String.valueOf(GuildManager.reloadSettingsForGuild(MusicBot.getJDA().getGuildById(guild))));
Guild guild = MusicBot.getJDA().getGuildById(guildId);
boolean ok;
if (guild == null)
ok = GuildManager.reloadSettingsForGuild(guildId);
else
ok = GuildManager.reloadSettingsForGuild(guild);
json.put("status", String.valueOf(ok));
sendJsonResponse(exchange, WebModule.createJson(json));
return;
@@ -1,77 +0,0 @@
package netneutrality.music;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler;
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException;
import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.TextChannel;
import netneutrality.handler.LogHandler;
import netneutrality.utils.MessageFunction;
public class LoadResultHandler implements AudioLoadResultHandler {
private final TextChannel channel;
private final Member user;
private final TrackScheduler scheduler;
private final String identifier;
private final boolean silent;
public LoadResultHandler(String identifier, TextChannel channel, Member user, TrackScheduler scheduler, boolean silent) {
if (user == null)
silent = true;
this.identifier = identifier;
this.channel = channel;
this.user = user;
this.scheduler = scheduler;
this.silent = silent;
}
@Override
public void trackLoaded(AudioTrack audioTrack) {
if (!silent) {
channel.sendMessageEmbeds(MessageFunction.buildAddingTrackMessage(audioTrack, user, identifier)).queue();
}
scheduler.queue(audioTrack, user);
}
@Override
public void playlistLoaded(AudioPlaylist audioPlaylist) {
if (identifier.startsWith("ytsearch:")) {
AudioTrack track = audioPlaylist.getTracks().get(0);
if (!silent)
channel.sendMessageEmbeds(MessageFunction.buildAddingTrackMessage(track, user, String.format("https://youtu.be/%s", track.getIdentifier()))).queue();
scheduler.queue(track, user);
} else {
if (!silent)
channel.sendMessageEmbeds(MessageFunction.buildAddingPlaylistMessage(audioPlaylist, user, identifier)).queue();
for (AudioTrack track : audioPlaylist.getTracks()) {
scheduler.queue(track, user);
}
}
}
@Override
public void noMatches() {
channel.sendMessage("No matches found").queue();
}
@Override
public void loadFailed(FriendlyException e) {
channel.sendMessage(e.getMessage()).queue();
LogHandler.log(e);
}
}
@@ -7,11 +7,14 @@ package netneutrality.music;
* https://discord.gg/CdFcyQ
*/
import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers;
import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeHttpContextFilter;
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException;
import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
@@ -20,7 +23,9 @@ import net.dv8tion.jda.api.entities.VoiceChannel;
import netneutrality.ThreadManager;
import netneutrality.command.CommandContext;
import netneutrality.exceptions.CommandErrorException;
import netneutrality.handler.LogHandler;
import netneutrality.thread.MusicPlayerAutoDisconnectThread;
import netneutrality.utils.MessageFunction;
import netneutrality.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -96,6 +101,10 @@ public class MusicManager {
public Member getRequesterOfCurrentTrack() {
TrackScheduler.TrackInfo info = scheduler.getQueue().peek();
if (info == null)
return null;
return info.getRequester();
}
@@ -148,11 +157,55 @@ public class MusicManager {
}
String identifier = SourceFinder.getIdentifier(url);
logger.debug(identifier);
scheduler.setTextChannel(channel);
if (identifier != null) {
playerManager.loadItem(identifier, new LoadResultHandler(identifier, channel, member, scheduler, silent));
playerManager.loadItem(identifier, new AudioLoadResultHandler() {
@Override
public void trackLoaded(AudioTrack audioTrack) {
logger.debug("Starting track on guild {}: {}", guild.getId(), identifier);
if (!silent) {
channel.sendMessageEmbeds(MessageFunction.buildAddingTrackMessage(audioTrack, member, identifier)).queue();
}
scheduler.queue(audioTrack, member);
}
@Override
public void playlistLoaded(AudioPlaylist audioPlaylist) {
if (identifier.startsWith("ytsearch:")) {
AudioTrack track = audioPlaylist.getTracks().get(0);
logger.debug("Starting track on guild {}: {}", guild.getId(), identifier);
if (!silent)
channel.sendMessageEmbeds(MessageFunction.buildAddingTrackMessage(track, member, String.format("https://youtu.be/%s", track.getIdentifier()))).queue();
scheduler.queue(track, member);
} else {
logger.debug("Starting playlist on guild {}: {}", guild.getId(), identifier);
if (!silent)
channel.sendMessageEmbeds(MessageFunction.buildAddingPlaylistMessage(audioPlaylist, member, identifier)).queue();
for (AudioTrack track : audioPlaylist.getTracks()) {
scheduler.queue(track, member);
}
}
}
@Override
public void noMatches() {
context.reply("No matches found");
}
@Override
public void loadFailed(FriendlyException e) {
context.reply("Failed to load track: " + e.getMessage());
LogHandler.log(e);
}
});
} else {
throw new CommandErrorException("No source found to play the given url", context, null);
}
@@ -137,6 +137,8 @@ public class TrackScheduler extends AudioEventAdapter {
TrackInfo current = queue.peek();
if (current != null) {
player.startTrack(current.getTrack(), false);
} else {
player.stopTrack();
}
}
@@ -20,9 +20,9 @@ public class ShutdownThread implements Runnable {
Configurator.shutdown((LoggerContext) LogManager.getContext());
}
if (MusicBot.getJDA() != null) {
MusicBot.shutdown();
if (!UnsafeShutdown.SAFE) {
//UnsafeShutdown.saveState();
}
}
}
}
@@ -64,6 +64,7 @@ public class MessageFunction {
public static MessageEmbed buildCurrentlyPlayingMessage(MusicManager manager, Member user) {
AudioTrack current = manager.getCurrentlyPlaying();
Member requester = (manager.getRequesterOfCurrentTrack() == null ? user : manager.getRequesterOfCurrentTrack());
EmbedBuilder message = new EmbedBuilder();
message.setAuthor("Link to track", String.format("https://youtu.be/%s", current.getIdentifier()));
@@ -73,7 +74,7 @@ public class MessageFunction {
message.addField("Track title: ", current.getInfo().title, false);
message.addField("Uploaded by: ", current.getInfo().author, false);
message.addField("Duration: ", DurationFormatUtils.formatDuration(current.getPosition(), "**HH:mm:ss**", true) + " / " + DurationFormatUtils.formatDuration(current.getDuration(), "**HH:mm:ss**", true), false);
message.setFooter("Requested by " + user.getUser().getName(), user.getUser().getAvatarUrl());
message.setFooter("Requested by " + requester.getEffectiveName(), requester.getAvatarUrl());
message.setTimestamp(OffsetDateTime.now());
return message.build();
@@ -133,7 +134,19 @@ public class MessageFunction {
return message.build();
}
public static ArrayList<MessageEmbed> buildHelpMessage(HashMap<String, AbstractCommand> commands, HashMap<String, AbstractCommand> alias, boolean admin) {
public static MessageEmbed buildHelpMessage(AbstractCommand command) {
EmbedBuilder message = new EmbedBuilder();
message.setTitle(":information_source: Help for command " + command.getCommandName());
message.setColor(Color.BLUE);
message.addField("Command", command.getCommandName(), false);
message.addField("Description", command.getDescription(), false);
message.addField("Aliases", ((command.getAlias() == null || command.getAlias().length == 0) ? "None": Arrays.toString(command.getAlias()).replaceAll("[\\[\\]]", "")), false);
message.addField("Usage", (command.getUsage() == null ? "No arguments defined" : command.getUsage()), false);
return message.build();
}
public static ArrayList<MessageEmbed> buildHelpMessage(HashMap<String, AbstractCommand> commands, boolean admin) {
SortedSet<String> keys = new TreeSet<>(commands.keySet());
HashMap<CommandType, EmbedBuilder> help = new HashMap<>();
@@ -143,7 +156,6 @@ public class MessageFunction {
if (command.getType() == null)
continue;
String usage = "(no arguments required)";
String description = "No description yet";
StringBuilder availAlias = new StringBuilder();
@@ -151,9 +163,6 @@ public class MessageFunction {
if (command.getType() == CommandType.ADMINISTRATION && !admin)
continue;
if (command.getUsage() != null)
usage = command.getUsage();
if (command.getDescription() != null)
description = command.getDescription();
@@ -178,10 +187,10 @@ public class MessageFunction {
if (message.isEmpty()) {
message.setTitle(command.getType().getDescription() + " commands for NetNeutrality");
message.setColor(Color.GREEN);
message.setColor(Color.BLUE);
}
message.addField(String.format("%s%s %s %s", Settings.getInstance().get("BOT_PREFIX"), command.getCommandName(), availAlias, usage), description, false);
message.addField(String.format("%s%s %s", Settings.getInstance().get("BOT_PREFIX"), command.getCommandName(), availAlias), description, false);
}
}
@@ -209,7 +218,7 @@ public class MessageFunction {
public static void checkBlacklist(Guild guild, Message message, TextChannel channel) {
((DBBlacklist) DBController.get("blacklist")).getBlacklistFromServer(guild.getId(), mBlacklists -> {
ArrayList<MBlacklist> mBlacklists = ((DBBlacklist) DBController.get("blacklist")).getBlacklistFromServer(guild.getId());
if (!mBlacklists.isEmpty()) {
boolean found = false;
@@ -225,7 +234,6 @@ public class MessageFunction {
channel.sendMessage("Not in my christian server").queue();
}
}
});
}