Implement command context and improve logging + music manager + help command

This commit is contained in:
anthorob committed 2022-01-25 22:45:21 -05:00
1 parent 6ed956a053
commit 061a18b487
54 files changed
+1280 -1271

No files matched your search

+15 -1
View File
@@ -7,10 +7,15 @@ package netneutrality;
*/ */
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;
import netneutrality.db.DBController;
import netneutrality.db.controllers.DBMessage;
import netneutrality.db.entities.OGuild; import netneutrality.db.entities.OGuild;
import netneutrality.db.entities.OGuildSetting;
import netneutrality.handler.ratelimiter.IMessageRateLimiter; import netneutrality.handler.ratelimiter.IMessageRateLimiter;
import netneutrality.handler.ratelimiter.MessageRateLimiterImpl; import netneutrality.handler.ratelimiter.MessageRateLimiterImpl;
import netneutrality.utils.MessageFunction;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -56,6 +61,15 @@ public class GuildManager {
} }
} }
public void checkAndLogMessage(Message message, Member member, TextChannel channel) {
//((DBMessage) DBController.get("message")).log(guild, channel, member, message);
}
public void checkBlacklist(Message message, Member member, TextChannel channel) {
//TODO: per-guild
MessageFunction.checkBlacklist(guild, message, channel);
}
public String getSetting(String key) { public String getSetting(String key) {
return guildEntity.getSettings().getSettingByKey(key); return guildEntity.getSettings().getSettingByKey(key);
} }
+5 -2
View File
@@ -5,9 +5,11 @@ import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Activity; import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.requests.GatewayIntent; import net.dv8tion.jda.api.requests.GatewayIntent;
import netneutrality.command.CommandManager;
import netneutrality.db.DBController; import netneutrality.db.DBController;
import netneutrality.handler.EditHandler; import netneutrality.handler.EditHandler;
import netneutrality.handler.NewCommandListener; import netneutrality.handler.MessageReceivedHandler;
import netneutrality.handler.ServerJoinHandler;
import netneutrality.http.server.WebApi; import netneutrality.http.server.WebApi;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.Settings; import netneutrality.utils.Settings;
@@ -30,8 +32,9 @@ public class MusicBot {
initJDA(); initJDA();
CommandManager.init();
jda.getPresence().setActivity(Activity.watching("me load...")); jda.getPresence().setActivity(Activity.watching("me load..."));
jda.addEventListener(new NewCommandListener(), new EditHandler()); jda.addEventListener(new MessageReceivedHandler(), new EditHandler(), new ServerJoinHandler());
new WebApi(); new WebApi();
jda.getPresence().setActivity(Activity.watching("you")); jda.getPresence().setActivity(Activity.watching("you"));
@@ -70,7 +70,7 @@ public class ThreadManager {
try { try {
for (ExecutorService ex : executors.values()) { for (ExecutorService ex : executors.values()) {
ex.shutdown(); ex.shutdown();
ex.awaitTermination(5, TimeUnit.SECONDS); ex.awaitTermination(2, TimeUnit.SECONDS);
} }
} }
catch (InterruptedException e) { catch (InterruptedException e) {
@@ -4,39 +4,37 @@ import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
public abstract class AbstractCommand implements ICommand { public abstract class AbstractCommand implements ICommand {
/**
* @return if the command needs administrator privilege
*/
public abstract boolean needAdmin();
/**
* @return if the command is enabled
*/
public abstract boolean isEnabled();
/**
* The command name that a user will write in a channel
*
* @return the name of the command.
*/
public abstract String getCommand();
/**
* @return all the aliases the command has
*/
public abstract String[] getAlias();
public abstract String getUsage(); /**
* @return if the command needs administrator privilege
*/
public abstract boolean needAdmin();
public abstract String getDescription(); /**
* @return if the command should be loaded at runtime
*/
public abstract boolean isEnabled();
public abstract Visibility getVisibility(); /**
* The command name that a user will write in a channel
*
* @return the name of the command.
*/
public abstract String getCommand();
public abstract CommandType getType(); /**
* @return all the aliases the command has
*/
public abstract String[] getAlias();
@Override public abstract String getUsage();
public boolean canBeExecutedBy(Guild guild, Member member) {
return true; public abstract String getDescription();
}
public abstract CommandType getType();
@Override
public boolean canBeExecutedBy(Guild guild, Member member) {
return true;
}
} }
@@ -9,7 +9,6 @@ import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.Role;
import netneutrality.GuildManager; import netneutrality.GuildManager;
import netneutrality.MusicBot;
public abstract class AbstractMusicCommand extends AbstractCommand { public abstract class AbstractMusicCommand extends AbstractCommand {
@@ -26,7 +25,7 @@ public abstract class AbstractMusicCommand extends AbstractCommand {
@Override @Override
public boolean canBeExecutedBy(Guild guild, Member member) { public boolean canBeExecutedBy(Guild guild, Member member) {
String roleDb = GuildManager.getManager(guild).getSetting(GuildManager.GuildSettings.MUSIC_ROLE); String roleDb = GuildManager.getManager(guild).getSetting(GuildManager.GuildSettings.MUSIC_ROLE);
System.out.println(roleDb); //System.out.println(roleDb);
if (roleDb != null && !roleDb.isEmpty()) { if (roleDb != null && !roleDb.isEmpty()) {
Role neededRole = guild.getRoleById(roleDb); Role neededRole = guild.getRoleById(roleDb);
@@ -0,0 +1,116 @@
package netneutrality.command;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import netneutrality.ThreadManager;
import netneutrality.handler.LogHandler;
import netneutrality.utils.UserFunction;
import java.util.concurrent.ExecutorService;
public class CommandContext {
private static final ExecutorService commandExecutor = ThreadManager.getExecutor("command-execution", ThreadManager.ExecutorType.FIXED, 10);
private AbstractCommand command;
private final Message message;
private final Guild guild;
private final TextChannel channel;
private final Member member;
private final User user;
private final JDA jda;
public CommandContext(Message message, Member member, User user, Guild guild, TextChannel channel, JDA jda) {
this.message = message;
this.member = member;
this.guild = guild;
this.channel = channel;
this.user = user;
this.jda = jda;
}
public static CommandContext createContext(GuildMessageReceivedEvent event) {
Message message = event.getMessage();
Member member = event.getMember();
User user = event.getAuthor();
Guild guild = event.getGuild();
TextChannel channel = event.getChannel();
JDA jda = event.getJDA();
return new CommandContext(message, member, user, guild, channel, jda);
}
public String[] getArgumentsAsArray() {
String text = message.getContentRaw().trim();
String cmd = text.split(" ", 2)[0];
String[] args = text.replaceFirst("(" + cmd + ")(\s)?", "").split("\s");
if (args.length == 1 && args[0].isEmpty())
args = new String[0];
return args;
}
public String getMessageText() {
String text = message.getContentRaw().trim();
String cmd = text.split(" ", 2)[0];
return text.replaceFirst("(" + cmd + ")(\s)?", "");
}
public Message getMessage() {
return message;
}
public Guild getGuild() {
return guild;
}
public TextChannel getChannel() {
return channel;
}
public Member getGuildUser() {
return member;
}
public User getDiscordUser() {
return user;
}
public JDA getJDA() {
return jda;
}
public AbstractCommand getCommand() {
return command;
}
public void dispatch(AbstractCommand command) {
this.command = command;
//TODO: Add usage check
if (command.needAdmin()) {
if (!UserFunction.isAdmin(member)) {
return;
}
}
if (command.canBeExecutedBy(guild, member)) {
try {
command.execute(this);
} catch (Exception e) {
LogHandler.log(e);
}
}
}
}
@@ -6,9 +6,21 @@ package netneutrality.command;/*
*/ */
public enum CommandType { public enum CommandType {
MUSIC(1), ADMINISTRATION(0), UTILITY(5); MUSIC("Music", 1), ADMINISTRATION("Administration", 0), UTILITY("Utility", 5), CRYPTO("Crypto", 6), UNLISTED("", -1);
CommandType(int i) { private final String description;
private final int id;
CommandType(String description, int id) {
this.description = description;
this.id = id;
}
public String getDescription() {
return description;
}
public int getId() {
return id;
} }
} }
@@ -7,14 +7,19 @@ package netneutrality.command;/*
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import netneutrality.exceptions.CommandErrorException;
import netneutrality.exceptions.CommandExecutionException;
public interface ICommand { public interface ICommand {
/**
* @param args the arguments to the command
*/
String execute(MessageReceivedEvent event, String[] args);
boolean canBeExecutedBy(Guild guild, Member member); boolean canBeExecutedBy(Guild guild, Member member);
/**
* Command is executed with this function.
*
* @param context The context for the command
* @throws CommandErrorException Used to reply with a message in the text channel where the command was executed
* @throws CommandExecutionException Logs the error internally, without sending a message
*/
void execute(CommandContext context) throws CommandErrorException, CommandExecutionException;
} }
@@ -1,17 +1,21 @@
package netneutrality.command.basic; package netneutrality.command.basic;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.MessageChannel; import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandManager; import netneutrality.command.CommandManager;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.Visibility;
import netneutrality.utils.MessageFunction; import netneutrality.utils.MessageFunction;
import netneutrality.utils.UserFunction;
import java.util.HashMap; import java.util.List;
public class HelpCommand extends AbstractCommand { public class HelpCommand extends AbstractCommand {
@@ -45,24 +49,16 @@ public class HelpCommand extends AbstractCommand {
return "Get every command with its usage"; return "Get every command with its usage";
} }
@Override
public Visibility getVisibility() {
return Visibility.BOTH;
}
@Override @Override
public CommandType getType() { public CommandType getType() {
return CommandType.UTILITY; return CommandType.UTILITY;
} }
@Override @Override
public String execute(MessageReceivedEvent event, String[] args) { public void execute(CommandContext context) {
List<MessageEmbed> help = MessageFunction.buildHelpMessage(CommandManager.commands, CommandManager.commandsAlias, UserFunction.isAdmin(context.getGuildUser()));
if (event.getChannel() instanceof TextChannel) context.getChannel().sendMessage(new MessageBuilder().append(context.getDiscordUser()).append(" help has been sent your way!").build()).queue();
event.getChannel().sendMessage(new MessageBuilder().append(event.getAuthor()).append(" help has been sent your way!").build()).queue(); context.getDiscordUser().openPrivateChannel().queue(t -> t.sendMessageEmbeds(help).queue());
event.getAuthor().openPrivateChannel().queue(t -> t.sendMessageEmbeds(MessageFunction.buildHelpMessage(CommandManager.commands, CommandManager.commandsAlias)).queue());
return null;
} }
} }
@@ -1,59 +1,57 @@
package netneutrality.command.basic; package netneutrality.command.basic;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.MusicBot; import netneutrality.MusicBot;
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.Visibility;
public class PingCommand extends AbstractCommand { public class PingCommand extends AbstractCommand {
@Override @Override
public String execute(MessageReceivedEvent event, String[] args) { public boolean needAdmin() {
if (args.length == 0) return false;
event.getChannel().sendMessage("Pong! [" + MusicBot.getJDA().getGatewayPing() + " ms]").queue(); }
return null; @Override
} public boolean isEnabled() {
return true;
}
@Override @Override
public boolean needAdmin() { public String getCommand() {
return false; return "ping";
} }
@Override @Override
public boolean isEnabled() { public String[] getAlias() {
return true; return new String[0];
} }
@Override @Override
public String getCommand() { public String getUsage() {
return "ping"; return null;
} }
@Override @Override
public String[] getAlias() { public String getDescription() {
return new String[0]; return "Pong!";
} }
@Override @Override
public String getUsage() { public CommandType getType() {
return null; return CommandType.UTILITY;
} }
@Override @Override
public String getDescription() { public void execute(CommandContext context) {
return "Pong!"; if (context.getArgumentsAsArray().length == 0)
} context.getChannel().sendMessage("Pong! [" + MusicBot.getJDA().getGatewayPing() + " ms]").queue();
}
@Override
public Visibility getVisibility() {
return Visibility.BOTH;
}
@Override
public CommandType getType() {
return null;
}
} }
@@ -1,14 +1,14 @@
package netneutrality.command.bot;/* package netneutrality.command.bot;
/*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* https://xtremcommunity.com/ * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.Visibility;
public class ConfigureCommand extends AbstractCommand { public class ConfigureCommand extends AbstractCommand {
@Override @Override
@@ -28,9 +28,7 @@ public class ConfigureCommand extends AbstractCommand {
@Override @Override
public String[] getAlias() { public String[] getAlias() {
return new String[] { return new String[]{"conf"};
"conf"
};
} }
@Override @Override
@@ -43,18 +41,13 @@ public class ConfigureCommand extends AbstractCommand {
return "Used to configure the bot on this server"; return "Used to configure the bot on this server";
} }
@Override
public Visibility getVisibility() {
return Visibility.CHANNEL;
}
@Override @Override
public CommandType getType() { public CommandType getType() {
return CommandType.ADMINISTRATION; return CommandType.ADMINISTRATION;
} }
@Override @Override
public String execute(MessageReceivedEvent event, String[] args) { public void execute(CommandContext context) {
return null;
} }
} }
@@ -1,110 +1,96 @@
package netneutrality.command.crypto; package netneutrality.command.crypto;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType;
import netneutrality.exceptions.CommandErrorException;
import netneutrality.exceptions.CommandExecutionException;
import netneutrality.http.WebModule;
import org.json.JSONException;
import java.io.IOException; import java.io.IOException;
import java.util.function.Consumer; import java.text.NumberFormat;
import java.util.Locale;
import netneutrality.command.CommandType;
import netneutrality.command.Visibility;
import org.json.JSONException;
import org.json.JSONObject;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractCommand;
import netneutrality.http.WebModule;
public class BitcoinPriceCommand extends AbstractCommand { public class BitcoinPriceCommand extends AbstractCommand {
private String currency;
private final String currencyUrl = "https://api.coindesk.com/v1/bpi/currentprice/";
private String price;
public BitcoinPriceCommand() { private final String baseURL = "https://min-api.cryptocompare.com/data/price";
this.currency = "USD"; private final String crypto = "BTC";
}
private String messageBuilder(String price) {
String newPrice = price.substring(0, price.indexOf("."));
return "The current bitcoin price in " + this.currency + " is " + newPrice + "$";
}
@Override @Override
public String execute(MessageReceivedEvent event, String[] args) throws JSONException, ArrayIndexOutOfBoundsException { public boolean needAdmin() {
return false;
}
if (args.length == 1) { @Override
if (Currency.isCurrency(args[0].toUpperCase())) public boolean isEnabled() {
this.currency = args[0].toUpperCase(); return true;
else { }
event.getTextChannel().sendMessage("Please enter a valid currency").queue();
return null;
}
}
event.getTextChannel().sendMessage("Retreiving price, please wait...").queue(new Consumer<Message>() {
@Override
public void accept(Message t) {
try {
WebModule bitcoinHttp = new WebModule(currencyUrl + currency + ".json").request();
JSONObject bpi = bitcoinHttp.getAsObject().getJSONObject("bpi");
price = bpi.getJSONObject(currency.toUpperCase()).getString("rate");
} catch (IOException | RuntimeException e) {
e.printStackTrace();
t.editMessage("Error getting bitcoin price!").queue();
}
t.editMessage(messageBuilder(price)).queue();
}
});
return null;
}
@Override @Override
public boolean needAdmin() { public String getCommand() {
return false; return "bitcoin";
} }
@Override @Override
public boolean isEnabled() { public String[] getAlias() {
return true; return new String[]{"btc"};
} }
@Override @Override
public String getCommand() { public String getUsage() {
return "bitcoin"; return null;
} }
@Override @Override
public String[] getAlias() { public String getDescription() {
return new String[] {"btc"}; return "Get the price of bitcoin";
} }
@Override @Override
public String getUsage() { public CommandType getType() {
return null; return CommandType.CRYPTO;
} }
@Override @Override
public String getDescription() { public void execute(CommandContext context) {
return "Get the bitcoin price"; String[] args = context.getArgumentsAsArray();
} String currency = "USD";
@Override if (args.length == 1) {
public Visibility getVisibility() { if (Currency.isCurrency(args[0].toUpperCase()))
return Visibility.BOTH; currency = args[0].toUpperCase();
} else {
throw new CommandErrorException("Please enter a valid currency", context, null);
}
@Override }
public CommandType getType() {
return null; String finalCurrency = currency;
} context.getChannel().sendMessage("Retreiving price, please wait...").queue(t -> {
String price = "0";
Locale usa = new Locale("en", "US");
NumberFormat dollarFormat = NumberFormat.getCurrencyInstance(usa);
dollarFormat.setMaximumFractionDigits(24);
try {
WebModule http = new WebModule(String.format("%s?fsym=%s&tsyms=%s", baseURL, crypto, finalCurrency.toUpperCase())).request();
price = dollarFormat.format(http.getAsObject().getDouble(finalCurrency));
} catch (IOException | JSONException | IllegalArgumentException | ArithmeticException e) {
t.editMessage(String.format("Error getting price of %s!", crypto)).queue();
throw new CommandExecutionException("Error during web request", context, e);
}
t.editMessage(String.format("The current price of %s in %s is %s$", crypto, finalCurrency, price)).queue();
});
}
} }
@@ -1,96 +1,100 @@
package netneutrality.command.crypto; package netneutrality.command.crypto;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.Visibility; import netneutrality.exceptions.CommandErrorException;
import netneutrality.exceptions.CommandExecutionException;
import netneutrality.http.WebModule; import netneutrality.http.WebModule;
import org.json.JSONException; import org.json.JSONException;
import java.io.IOException; import java.io.IOException;
import java.text.NumberFormat;
import java.util.Locale;
public class CryptoPriceCommand extends AbstractCommand { public class CryptoPriceCommand extends AbstractCommand {
private final String baseURL = "https://min-api.cryptocompare.com/data/price"; private final String baseURL = "https://min-api.cryptocompare.com/data/price";
private String price = "";
@Override @Override
public boolean needAdmin() { public boolean needAdmin() {
return false; return false;
} }
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return true; return true;
} }
@Override @Override
public String getCommand() { public String getCommand() {
return "crypto"; return "crypto";
} }
@Override @Override
public String[] getAlias() { public String[] getAlias() {
return new String[0]; return new String[0];
} }
@Override @Override
public String getUsage() { public String getUsage() {
return "<crypto> <currency>"; return "<crypto> <currency>";
} }
@Override @Override
public String getDescription() { public String getDescription() {
return "Get the price of cryptocurrrency"; return "Get the price of cryptocurrrency";
} }
@Override @Override
public Visibility getVisibility() { public CommandType getType() {
return Visibility.CHANNEL; return CommandType.CRYPTO;
} }
@Override @Override
public CommandType getType() { public void execute(CommandContext context) {
return null; String[] args = context.getArgumentsAsArray();
} String currency = "USD";
@Override if (args.length > 0) {
public String execute(MessageReceivedEvent event, String[] args) {
String currency = "USD";
if (args.length > 0) { if (args.length == 2) {
if (Currency.isCurrency(args[1].toUpperCase()))
currency = args[1].toUpperCase();
else {
throw new CommandErrorException("Please enter a valid currency", context, null);
}
if (args.length == 2) { }
if (Currency.isCurrency(args[1].toUpperCase()))
currency = args[1].toUpperCase();
else {
event.getTextChannel().sendMessage("Please enter a valid currency").queue();
return null;
}
} String crypto = args[0].toUpperCase();
String finalCurrency = currency;
context.getChannel().sendMessage("Retreiving price, please wait...").queue(t -> {
String price = "0";
Locale usa = new Locale("en", "US");
NumberFormat dollarFormat = NumberFormat.getCurrencyInstance(usa);
dollarFormat.setMaximumFractionDigits(24);
String finalCurrency = currency; try {
event.getTextChannel().sendMessage("Retreiving price, please wait...").queue(t -> { WebModule http = new WebModule(String.format("%s?fsym=%s&tsyms=%s", baseURL, crypto, finalCurrency.toUpperCase())).request();
price = dollarFormat.format(http.getAsObject().getDouble(finalCurrency));
try { } catch (IOException | JSONException | IllegalArgumentException | ArithmeticException e) {
WebModule ethereumHttp = new WebModule(baseURL + "?fsym=" + args[0] + "&tsyms=" + finalCurrency.toUpperCase()).request(); t.editMessage(String.format("Error getting price of %s!", crypto)).queue();
price = Double.toString(ethereumHttp.getAsObject().getDouble(finalCurrency)); throw new CommandExecutionException("Error during web request", context, e);
}
if (price == null)
throw new IllegalArgumentException("Crypto doesn't exist");
} catch (IOException | JSONException | IllegalArgumentException e) {
e.printStackTrace();
t.editMessage("Error getting price!").queue();
}
t.editMessage(String.format("The current price of %s in %s is %s$", args[0].toUpperCase(), finalCurrency, price)).queue();
});
}
return null;
} t.editMessage(String.format("The current price of %s in %s is %s", crypto, finalCurrency, price)).queue();
});
}
}
} }
@@ -1,8 +1,14 @@
package netneutrality.command.crypto; package netneutrality.command.crypto;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
public enum Currency { public enum Currency {
AED("AED"), AFN("AFN"), ALL("ALL"), AMD("AMD"), ANG("ANG"), AOA("AOA"), ARS("ARS"), AUD("AUD"), AWG("AWG"), AZN("AZN"), BAM("BAM"), BBD("BBD"), AED("AED"), AFN("AFN"), ALL("ALL"), AMD("AMD"), ANG("ANG"), AOA("AOA"), ARS("ARS"), AUD("AUD"), AWG("AWG"), AZN("AZN"), BAM("BAM"), BBD("BBD"),
BDT("BDT"), BGN("BGN"), BHD("BHD"), BIF("BIF"), BMD("BMD"), BND("BND"), BOB("BOB"), BOV("BOV"), BRL("BRL"), BSD("BSD"), BTN("BTN"), BWP("BWP"), BDT("BDT"), BGN("BGN"), BHD("BHD"), BIF("BIF"), BMD("BMD"), BND("BND"), BOB("BOB"), BOV("BOV"), BRL("BRL"), BSD("BSD"), BTN("BTN"), BWP("BWP"),
BYN("BYN"), BYR("BYR"), BZD("BZD"), CAD("CAD"), CDF("CDF"), CHE("CHE"), CHF("CHF"), CHW("CHW"), CLF("CLF"), CLP("CLP"), CNY("CNY"), COP("COP"), BYN("BYN"), BYR("BYR"), BZD("BZD"), CAD("CAD"), CDF("CDF"), CHE("CHE"), CHF("CHF"), CHW("CHW"), CLF("CLF"), CLP("CLP"), CNY("CNY"), COP("COP"),
COU("COU"), CRC("CRC"), CUC("CUC"), CUP("CUP"), CVE("CVE"), CZK("CZK"), DJF("DJF"), DKK("DKK"), DOP("DOP"), DZD("DZD"), EGP("EGP"), ERN("ERN"), COU("COU"), CRC("CRC"), CUC("CUC"), CUP("CUP"), CVE("CVE"), CZK("CZK"), DJF("DJF"), DKK("DKK"), DOP("DOP"), DZD("DZD"), EGP("EGP"), ERN("ERN"),
@@ -17,24 +23,30 @@ public enum Currency {
TWD("TWD"), TZS("TZS"), UAH("UAH"), UGX("UGX"), USD("USD"), USN("USN"), UYI("UYI"), UYU("UYU"), UZS("UZS"), VEF("VEF"), VND("VND"), VUV("VUV"), TWD("TWD"), TZS("TZS"), UAH("UAH"), UGX("UGX"), USD("USD"), USN("USN"), UYI("UYI"), UYU("UYU"), UZS("UZS"), VEF("VEF"), VND("VND"), VUV("VUV"),
WST("WST"), XAF("XAF"), XAG("XAG"), XAU("XAU"), XBA("XBA"), XBB("XBB"), XBC("XBC"), XBD("XBD"), XCD("XCD"), XDR("XDR"), XFU("XFU"), XOF("XOF"), WST("WST"), XAF("XAF"), XAG("XAG"), XAU("XAU"), XBA("XBA"), XBB("XBB"), XBC("XBC"), XBD("XBD"), XCD("XCD"), XDR("XDR"), XFU("XFU"), XOF("XOF"),
XPD("XPD"), XPF("XPF"), XPT("XPT"), XSU("XSU"), XTS("XTS"), XUA("XUA"), XXX("XXX"), YER("YER"), ZAR("ZAR"), ZMW("ZMW"); XPD("XPD"), XPF("XPF"), XPT("XPT"), XSU("XSU"), XTS("XTS"), XUA("XUA"), XXX("XXX"), YER("YER"), ZAR("ZAR"), ZMW("ZMW");
private final String iso4217Code;
Currency(String code) { private final String iso4217Code;
Currency(String code) {
this.iso4217Code = code; this.iso4217Code = code;
} }
@Override public String getIso4217Code() {
public String toString() {
return iso4217Code; return iso4217Code;
} }
public static boolean isCurrency(String str) { @Override
for (Currency c : Currency.values()) { public String toString() {
if (c.name().equals(str.toUpperCase())) return "Currency{" +
return true; "iso4217Code='" + iso4217Code + '\'' +
} '}';
}
return false;
} public static boolean isCurrency(String str) {
for (Currency c : Currency.values()) {
if (c.name().equals(str.toUpperCase()))
return true;
}
return false;
}
} }
@@ -1,98 +1,96 @@
package netneutrality.command.crypto; package netneutrality.command.crypto;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import java.io.IOException; import netneutrality.command.AbstractCommand;
import java.util.function.Consumer; import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.Visibility; import netneutrality.exceptions.CommandErrorException;
import netneutrality.exceptions.CommandExecutionException;
import netneutrality.http.WebModule;
import org.json.JSONException; import org.json.JSONException;
import net.dv8tion.jda.api.entities.Message; import java.io.IOException;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import java.text.NumberFormat;
import netneutrality.command.AbstractCommand; import java.util.Locale;
import netneutrality.http.WebModule;
public class EthereumPriceCommand extends AbstractCommand { public class EthereumPriceCommand extends AbstractCommand {
private String currency;
private final String currencyUrl = "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=";
private String price = "";
public EthereumPriceCommand() { private final String baseURL = "https://min-api.cryptocompare.com/data/price";
this.currency = "USD"; private final String crypto = "ETH";
}
private String messageBuilder(String price) {
return "The current ethereum price in " + this.currency + " is " + price + "$";
}
@Override @Override
public String execute(MessageReceivedEvent event, String[] args) throws JSONException, ArrayIndexOutOfBoundsException { public boolean needAdmin() {
return false;
if (args.length == 1) { }
if (Currency.isCurrency(args[0].toUpperCase()))
this.currency = args[0].toUpperCase();
else {
event.getTextChannel().sendMessage("Please enter a valid currency").queue();
return null;
}
}
event.getTextChannel().sendMessage("Retreiving price, please wait...").queue(t -> {
try { @Override
WebModule ethereumHttp = new WebModule(currencyUrl + currency.toUpperCase()).request(); public boolean isEnabled() {
price = Double.toString(ethereumHttp.getAsObject().getDouble(currency)); return true;
}
} catch (IOException | RuntimeException e) { @Override
e.printStackTrace(); public String getCommand() {
t.editMessage("Error getting ethereum price!").queue(); return "ethereum";
} }
t.editMessage(messageBuilder(price)).queue();
});
return null; @Override
} public String[] getAlias() {
return new String[]{"eth"};
}
@Override @Override
public boolean needAdmin() { public String getUsage() {
return false; return null;
} }
@Override @Override
public boolean isEnabled() { public String getDescription() {
return true; return "Get the ethereum price";
} }
@Override @Override
public String getCommand() { public CommandType getType() {
return "ethereum"; return CommandType.CRYPTO;
} }
@Override @Override
public String[] getAlias() { public void execute(CommandContext context) {
return new String[] {"eth"}; String[] args = context.getArgumentsAsArray();
} String currency = "USD";
@Override if (args.length == 1) {
public String getUsage() { if (Currency.isCurrency(args[0].toUpperCase()))
return null; currency = args[0].toUpperCase();
} else {
throw new CommandErrorException("Please enter a valid currency", context, null);
}
@Override }
public String getDescription() {
return "Get the ethereum price";
}
@Override String finalCurrency = currency;
public Visibility getVisibility() { context.getChannel().sendMessage("Retreiving price, please wait...").queue(t -> {
return Visibility.BOTH; String price = "0";
} Locale usa = new Locale("en", "US");
NumberFormat dollarFormat = NumberFormat.getCurrencyInstance(usa);
dollarFormat.setMaximumFractionDigits(24);
@Override try {
public CommandType getType() { WebModule http = new WebModule(String.format("%s?fsym=%s&tsyms=%s", baseURL, crypto, finalCurrency.toUpperCase())).request();
return null; price = dollarFormat.format(http.getAsObject().getDouble(finalCurrency));
}
} catch (IOException | JSONException | IllegalArgumentException e) {
t.editMessage(String.format("Error getting price of %s!", crypto)).queue();
throw new CommandExecutionException("Error during web request", context, e);
}
t.editMessage(String.format("The current price of %s in %s is %s$", crypto, finalCurrency, price)).queue();
});
}
} }
@@ -1,97 +1,95 @@
package netneutrality.command.crypto; package netneutrality.command.crypto;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import java.io.IOException; import netneutrality.command.AbstractCommand;
import java.util.function.Consumer; import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.Visibility; import netneutrality.exceptions.CommandErrorException;
import netneutrality.exceptions.CommandExecutionException;
import netneutrality.http.WebModule;
import org.json.JSONException; import org.json.JSONException;
import net.dv8tion.jda.api.entities.Message; import java.io.IOException;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import java.text.NumberFormat;
import netneutrality.command.AbstractCommand; import java.util.Locale;
import netneutrality.http.WebModule;
public class LitecoinPriceCommand extends AbstractCommand { public class LitecoinPriceCommand extends AbstractCommand {
private String currency; private final String baseURL = "https://min-api.cryptocompare.com/data/price";
private final String currencyUrl = "https://min-api.cryptocompare.com/data/price?fsym=LTC&tsyms="; private final String crypto = "LTC";
private String price;
public LitecoinPriceCommand() { @Override
this.currency = "USD"; public boolean needAdmin() {
} return false;
}
private String messageBuilder(String price) {
return "The current litecoin price in " + this.currency + " is " + price + "$";
}
@Override @Override
public String execute(MessageReceivedEvent event, String[] args) throws ArrayIndexOutOfBoundsException, JSONException { public boolean isEnabled() {
return true;
if (args.length == 1) { }
if (Currency.isCurrency(args[0].toUpperCase()))
this.currency = args[0].toUpperCase();
else {
event.getTextChannel().sendMessage("Please enter a valid currency").queue();
return null;
}
}
event.getTextChannel().sendMessage("Retreiving price, please wait...").queue(t -> {
try { @Override
WebModule litecoinHttp = new WebModule(currencyUrl + currency).request(); public String getCommand() {
price = litecoinHttp.getAsArray().getJSONObject(0).getString("price_" + currency.toLowerCase()); return "litecoin";
} catch (IOException | RuntimeException e) { }
e.printStackTrace();
t.editMessage("Error getting litecoin price!").queue();
}
t.editMessage(messageBuilder(price)).queue();
}); @Override
public String[] getAlias() {
return null; return new String[]{"ltc"};
} }
@Override @Override
public boolean needAdmin() { public String getUsage() {
return false; return null;
} }
@Override @Override
public boolean isEnabled() { public String getDescription() {
return true; return "Get the litecoin price";
} }
@Override @Override
public String getCommand() { public CommandType getType() {
return "litecoin"; return CommandType.CRYPTO;
} }
@Override @Override
public String[] getAlias() { public void execute(CommandContext context) {
return new String[] {"ltc"}; String[] args = context.getArgumentsAsArray();
} String currency = "USD";
@Override if (args.length == 1) {
public String getUsage() { if (Currency.isCurrency(args[0].toUpperCase()))
return null; currency = args[0].toUpperCase();
} else {
throw new CommandErrorException("Please enter a valid currency", context, null);
}
@Override }
public String getDescription() {
return "Get the litecoin price";
}
@Override String finalCurrency = currency;
public Visibility getVisibility() { context.getChannel().sendMessage("Retreiving price, please wait...").queue(t -> {
return Visibility.BOTH; String price = "0";
} Locale usa = new Locale("en", "US");
NumberFormat dollarFormat = NumberFormat.getCurrencyInstance(usa);
dollarFormat.setMaximumFractionDigits(24);
@Override try {
public CommandType getType() { WebModule http = new WebModule(String.format("%s?fsym=%s&tsyms=%s", baseURL, crypto, finalCurrency.toUpperCase())).request();
return null; price = dollarFormat.format(http.getAsObject().getDouble(finalCurrency));
}
} catch (IOException | JSONException | IllegalArgumentException | ArithmeticException e) {
t.editMessage(String.format("Error getting price of %s!", crypto)).queue();
throw new CommandExecutionException("Error during web request", context, e);
}
t.editMessage(String.format("The current price of %s in %s is %s$", crypto, finalCurrency, price)).queue();
});
}
} }
@@ -1,9 +1,14 @@
package netneutrality.command.message; package netneutrality.command.message;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.Visibility;
import netneutrality.db.DBController; import netneutrality.db.DBController;
import netneutrality.db.controllers.DBBlacklist; import netneutrality.db.controllers.DBBlacklist;
import netneutrality.db.models.MBlacklist; import netneutrality.db.models.MBlacklist;
@@ -27,7 +32,7 @@ public class BlacklistCommand extends AbstractCommand {
@Override @Override
public String[] getAlias() { public String[] getAlias() {
return new String[] {"bl"}; return new String[]{"bl"};
} }
@Override @Override
@@ -40,18 +45,14 @@ public class BlacklistCommand extends AbstractCommand {
return "Manages the blacklist of your server."; return "Manages the blacklist of your server.";
} }
@Override
public Visibility getVisibility() {
return Visibility.CHANNEL;
}
@Override @Override
public CommandType getType() { public CommandType getType() {
return null; return CommandType.ADMINISTRATION;
} }
@Override @Override
public String execute(MessageReceivedEvent event, String[] args) { public void execute(CommandContext context) {
String[] args = context.getArgumentsAsArray();
if (args.length > 0 && args.length < 3) { if (args.length > 0 && args.length < 3) {
String word = (args.length == 2 ? args[1] : ""); String word = (args.length == 2 ? args[1] : "");
@@ -59,15 +60,15 @@ public class BlacklistCommand extends AbstractCommand {
switch (args[0]) { switch (args[0]) {
case "get": case "get":
event.getTextChannel().sendMessage("Retrieving list, please wait...").queue(t -> { context.getChannel().sendMessage("Retrieving list, please wait...").queue(t -> {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
((DBBlacklist) DBController.get("blacklist")).getBlacklistFromServer(event.getGuild().getId(), mBlacklists -> { ((DBBlacklist) DBController.get("blacklist")).getBlacklistFromServer(context.getGuild().getId(), mBlacklists -> {
for (MBlacklist bl : mBlacklists) { for (MBlacklist bl : mBlacklists) {
sb.append(bl.getWord()).append(" -> ").append(bl.isEnabled() ? "enabled" : "disabled").append("\n"); sb.append(bl.getWord()).append(" -> ").append(bl.isEnabled() ? "enabled" : "disabled").append("\n");
} }
t.editMessage("List of blacklisted words for this server [" + event.getGuild().getName() + "] :\n" + (mBlacklists.isEmpty() ? "No word found" : sb.toString())).queue(); t.editMessage("List of blacklisted words for this server [" + context.getGuild().getName() + "] :\n" + (mBlacklists.isEmpty() ? "No word found" : sb.toString())).queue();
}); });
}); });
@@ -76,22 +77,22 @@ public class BlacklistCommand extends AbstractCommand {
case "add": case "add":
((DBBlacklist) DBController.get("blacklist")).add(new MBlacklist(word, true, event.getAuthor().getId(), event.getGuild().getId()), response -> { ((DBBlacklist) DBController.get("blacklist")).add(new MBlacklist(word, true, context.getDiscordUser().getId(), context.getGuild().getId()), response -> {
if (response) { if (response) {
event.getTextChannel().sendMessage("Added the word \"" + word + "\" to the blacklist.").queue(); context.getChannel().sendMessage("Added the word \"" + word + "\" to the blacklist.").queue();
} else { } else {
event.getTextChannel().sendMessage("Error adding \"" + word + "\" to the blacklist. It's already blacklisted!").queue(); context.getChannel().sendMessage("Error adding \"" + word + "\" to the blacklist. It's already blacklisted!").queue();
} }
}); });
break; break;
case "remove": case "remove":
((DBBlacklist) DBController.get("blacklist")).delete(word, event.getGuild().getId(), success -> { ((DBBlacklist) DBController.get("blacklist")).delete(word, context.getGuild().getId(), success -> {
if (success) { if (success) {
event.getTextChannel().sendMessage("Removed the word \"" + word + "\" from the blacklist.").queue(); context.getChannel().sendMessage("Removed the word \"" + word + "\" from the blacklist.").queue();
} else { } else {
event.getTextChannel().sendMessage("Error removing \"" + word + "\" from the blacklist").queue(); context.getChannel().sendMessage("Error removing \"" + word + "\" from the blacklist").queue();
} }
}); });
@@ -99,11 +100,11 @@ public class BlacklistCommand extends AbstractCommand {
case "disable": case "disable":
((DBBlacklist) DBController.get("blacklist")).disable(word, event.getGuild().getId(), success -> { ((DBBlacklist) DBController.get("blacklist")).disable(word, context.getGuild().getId(), success -> {
if (success) { if (success) {
event.getTextChannel().sendMessage("Removed the word \"" + word + "\" from the blacklist.").queue(); context.getChannel().sendMessage("Removed the word \"" + word + "\" from the blacklist.").queue();
} else { } else {
event.getTextChannel().sendMessage("Error removing \"" + word + "\" from the blacklist").queue(); context.getChannel().sendMessage("Error removing \"" + word + "\" from the blacklist").queue();
} }
}); });
@@ -111,11 +112,11 @@ public class BlacklistCommand extends AbstractCommand {
case "enable": case "enable":
((DBBlacklist) DBController.get("blacklist")).enable(word, event.getGuild().getId(), success -> { ((DBBlacklist) DBController.get("blacklist")).enable(word, context.getGuild().getId(), success -> {
if (success) { if (success) {
event.getTextChannel().sendMessage("Removed the word \"" + word + "\" from the blacklist.").queue(); context.getChannel().sendMessage("Removed the word \"" + word + "\" from the blacklist.").queue();
} else { } else {
event.getTextChannel().sendMessage("Error removing \"" + word + "\" from the blacklist").queue(); context.getChannel().sendMessage("Error removing \"" + word + "\" from the blacklist").queue();
} }
}); });
@@ -123,8 +124,6 @@ public class BlacklistCommand extends AbstractCommand {
} }
} }
return null;
} }
} }
@@ -1,61 +1,59 @@
package netneutrality.command.message; package netneutrality.command.message;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.Visibility;
import netneutrality.utils.ChannelFunction; import netneutrality.utils.ChannelFunction;
public class PruneCommand extends AbstractCommand { public class PruneCommand extends AbstractCommand {
@Override @Override
public boolean needAdmin() { public boolean needAdmin() {
return true; return true;
} }
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return true; return true;
} }
@Override @Override
public String getCommand() { public String getCommand() {
return "prune"; return "prune";
} }
@Override @Override
public String[] getAlias() { public String[] getAlias() {
return new String[] {"purge"}; return new String[]{"purge"};
} }
@Override @Override
public String getUsage() { public String getUsage() {
return "<number of messages to delete (max 2499)>"; return "<number of messages to delete (max 2499)>";
} }
@Override @Override
public String getDescription() { public String getDescription() {
return "Delete n messages from the channel you are currently on"; return "Delete n messages from the channel you are currently on";
} }
@Override @Override
public Visibility getVisibility() { public CommandType getType() {
return Visibility.CHANNEL; return CommandType.ADMINISTRATION;
} }
@Override @Override
public CommandType getType() { public void execute(CommandContext context) {
return null; if (context.getArgumentsAsArray().length == 1)
} ChannelFunction.bulkDeleteMessage(context.getChannel(), Integer.parseInt(context.getArgumentsAsArray()[0]));
else
@Override context.getChannel().sendMessage("Failed to delete messages!").queue();
public String execute(MessageReceivedEvent event, String[] args) { }
if (args.length == 1)
ChannelFunction.bulkDeleteMessage(event.getTextChannel(), Integer.parseInt(args[0]));
else
event.getTextChannel().sendMessage("Failed to delete messages!").queue();
return null;
}
} }
@@ -3,14 +3,13 @@ package netneutrality.command.music;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.Visibility; import netneutrality.command.CommandContext;
import netneutrality.command.CommandType;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
public class BitconnectCommand extends AbstractMusicCommand { public class BitconnectCommand extends AbstractMusicCommand {
@@ -41,33 +40,15 @@ public class BitconnectCommand extends AbstractMusicCommand {
} }
@Override @Override
public Visibility getVisibility() { public CommandType getType() {
return Visibility.CHANNEL; return CommandType.UNLISTED;
} }
@Override @Override
public String execute(MessageReceivedEvent event, String[] args) { public void execute(CommandContext context) {
Member member = event.getMember(); MusicManager player = MusicManager.get(context.getGuild());
MusicManager player = MusicManager.get(event.getGuild()); player.play("https://www.youtube.com/watch?v=e5nyQmaq4k4", context, false, true);
if (member.getVoiceState().inVoiceChannel()) { context.getMessage().delete().queue();
VoiceChannel vChannel = member.getVoiceState().getChannel();
if (player.isConnected()) {
if (player.isConnectedTo(vChannel)) {
player.play("https://www.youtube.com/watch?v=e5nyQmaq4k4", event.getTextChannel(), member, true);
} else
event.getTextChannel().sendMessage("Not in your voice channel").queue();
} else {
player.connect(vChannel);
player.play("https://www.youtube.com/watch?v=e5nyQmaq4k4", event.getTextChannel(), member, true);
}
} else
event.getTextChannel().sendMessage("You are not in a voice channel").queue();
event.getMessage().delete().queue();
return null;
} }
} }
@@ -3,16 +3,16 @@ package netneutrality.command.music;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.Visibility; import netneutrality.command.CommandContext;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.MessageFunction; import netneutrality.utils.MessageFunction;
import netneutrality.utils.MusicUtils;
public class CurrentlyPlayingCommand extends AbstractMusicCommand { public class CurrentlyPlayingCommand extends AbstractMusicCommand {
@@ -42,34 +42,16 @@ public class CurrentlyPlayingCommand extends AbstractMusicCommand {
} }
@Override @Override
public Visibility getVisibility() { public void execute(CommandContext context) {
return Visibility.CHANNEL; Member member = context.getGuildUser();
} MusicManager player = MusicManager.get(context.getGuild());
MusicUtils.checkIfConnected(player, context);
@Override if (player.getCurrentlyPlaying() != null) {
public String execute(MessageReceivedEvent event, String[] args) { context.getChannel().sendMessageEmbeds(MessageFunction.buildCurrentlyPlayingMessage(player, member)).queue();
Member member = event.getMember(); } else {
context.getChannel().sendMessage("Player is not playing any tracks right now").queue();
}
if (member.getVoiceState().inVoiceChannel()) {
MusicManager player = MusicManager.get(event.getGuild());
VoiceChannel vChannel = member.getVoiceState().getChannel();
if (player.isConnected()) {
if (player.isConnectedTo(vChannel)) {
if (player.getCurrentlyPlaying() != null) {
event.getTextChannel().sendMessageEmbeds(MessageFunction.buildCurrentlyPlayingMessage(player, member)).queue();
} else {
event.getTextChannel().sendMessage("Player is not playing any track right now").queue();
}
} else
event.getTextChannel().sendMessage("Player is not in your voice channel").queue();
} else {
event.getTextChannel().sendMessage("Player is not in a voice channel").queue();
}
} else
event.getTextChannel().sendMessage("You are not in a voice channel").queue();
return null;
} }
} }
@@ -3,15 +3,14 @@ package netneutrality.command.music;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.Visibility; import netneutrality.command.CommandContext;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.MusicUtils;
public class DeleteQueueCommand extends AbstractMusicCommand { public class DeleteQueueCommand extends AbstractMusicCommand {
@Override @Override
@@ -45,36 +44,17 @@ public class DeleteQueueCommand extends AbstractMusicCommand {
} }
@Override @Override
public Visibility getVisibility() { public void execute(CommandContext context) {
return Visibility.CHANNEL; MusicManager player = MusicManager.get(context.getGuild());
} MusicUtils.checkIfConnected(player, context);
@Override int queueSize = player.getScheduler().getQueue().size();
public String execute(MessageReceivedEvent event, String[] args) { if (queueSize > 0) {
Member member = event.getMember(); player.getScheduler().getQueue().clear();
MusicManager player = MusicManager.get(event.getGuild()); context.getChannel().sendMessage("Removed " + queueSize + (queueSize > 1 ? " tracks" : "track") + " from the queue").queue();
} else {
context.getChannel().sendMessage("Queue is empty!").queue();
}
if (member.getVoiceState().inVoiceChannel()) {
VoiceChannel vChannel = member.getVoiceState().getChannel();
if (player.isConnected()) {
if (player.isConnectedTo(vChannel)) {
int queueSize = player.getScheduler().getQueue().size();
if (queueSize > 0) {
player.getScheduler().getQueue().clear();
event.getTextChannel().sendMessage("Removed " + queueSize + (queueSize > 1 ? " tracks" : "track") + " from the queue").queue();
} else {
event.getTextChannel().sendMessage("Queue is empty!").queue();
}
} else
event.getTextChannel().sendMessage("Not in your voice channel").queue();
} else {
event.getTextChannel().sendMessage("Not in a voice channel").queue();
}
} else
event.getTextChannel().sendMessage("You are not in a voice channel").queue();
return null;
} }
} }
@@ -3,15 +3,15 @@ package netneutrality.command.music;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.VoiceChannel; import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.Visibility; import netneutrality.command.CommandContext;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.MusicUtils;
public class JoinCommand extends AbstractMusicCommand { public class JoinCommand extends AbstractMusicCommand {
@@ -41,29 +41,11 @@ public class JoinCommand extends AbstractMusicCommand {
} }
@Override @Override
public Visibility getVisibility() { public void execute(CommandContext context) {
return Visibility.CHANNEL; MusicManager player = MusicManager.get(context.getGuild());
} MusicUtils.checkIfConnected(player, context);
@Override VoiceChannel vChannel = context.getGuildUser().getVoiceState().getChannel();
public String execute(MessageReceivedEvent event, String[] args) { player.connect(vChannel);
Member member = event.getMember();
if (member.getVoiceState().inVoiceChannel()) {
MusicManager player = MusicManager.get(event.getGuild());
VoiceChannel vChannel = member.getVoiceState().getChannel();
if (!player.isConnected()) {
if (!player.isConnectedTo(vChannel)) {
player.connect(vChannel);
} else
event.getTextChannel().sendMessage("Already in a voice channel").queue();
} else
event.getTextChannel().sendMessage("Already in a voice channel").queue();
} else
event.getTextChannel().sendMessage("You are not in a voice channel").queue();
return null;
} }
} }
@@ -3,15 +3,14 @@ package netneutrality.command.music;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.Visibility; import netneutrality.command.CommandContext;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.MusicUtils;
public class LeaveCommand extends AbstractMusicCommand { public class LeaveCommand extends AbstractMusicCommand {
@Override @Override
@@ -45,20 +44,10 @@ public class LeaveCommand extends AbstractMusicCommand {
} }
@Override @Override
public Visibility getVisibility() { public void execute(CommandContext context) {
return Visibility.CHANNEL; MusicManager player = MusicManager.get(context.getGuild());
} MusicUtils.checkIfConnected(player, context);
@Override player.leave();
public String execute(MessageReceivedEvent event, String[] args) {
Member member = event.getMember();
MusicManager player = MusicManager.get(event.getGuild());
VoiceChannel vChannel = member.getVoiceState().getChannel();
if (player.isConnectedTo(vChannel)) {
player.leave();
}
return null;
} }
} }
@@ -3,14 +3,12 @@ package netneutrality.command.music;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.Visibility; import netneutrality.command.CommandContext;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
public class PlayCommand extends AbstractMusicCommand { public class PlayCommand extends AbstractMusicCommand {
@@ -41,34 +39,16 @@ public class PlayCommand extends AbstractMusicCommand {
} }
@Override @Override
public Visibility getVisibility() { public void execute(CommandContext context) {
return Visibility.CHANNEL; MusicManager player = MusicManager.get(context.getGuild());
}
@Override if (context.getArgumentsAsArray().length > 0) {
public String execute(MessageReceivedEvent event, String[] args) { context.getMessage().delete().queue();
Member member = event.getMember(); player.play(context.getMessageText(), context, false, false);
MusicManager player = MusicManager.get(event.getGuild());
if (member.getVoiceState().inVoiceChannel()) { } else {
VoiceChannel vChannel = member.getVoiceState().getChannel(); context.getChannel().sendMessage("No url provided").queue();
}
if (player.isConnected()) {
if (player.isConnectedTo(vChannel)) {
event.getMessage().delete().queue();
player.play(args[0], event.getTextChannel(), event.getMember(), false);
} else
event.getTextChannel().sendMessage("Not in your voice channel").queue();
} else {
player.connect(vChannel);
event.getMessage().delete().queue();
player.play(args[0], event.getTextChannel(), event.getMember(), false);
}
} else
event.getTextChannel().sendMessage("You are not in a voice channel").queue();
return null;
} }
} }
@@ -3,15 +3,14 @@ package netneutrality.command.music;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.Visibility; import netneutrality.command.CommandContext;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.MusicUtils;
public class SkipCommand extends AbstractMusicCommand { public class SkipCommand extends AbstractMusicCommand {
@Override @Override
@@ -45,28 +44,10 @@ public class SkipCommand extends AbstractMusicCommand {
} }
@Override @Override
public Visibility getVisibility() { public void execute(CommandContext context) {
return Visibility.CHANNEL; MusicManager player = MusicManager.get(context.getGuild());
} MusicUtils.checkIfConnected(player, context);
@Override player.skip();
public String execute(MessageReceivedEvent event, String[] args) {
Member member = event.getMember();
MusicManager player = MusicManager.get(event.getGuild());
if (member.getVoiceState().inVoiceChannel()) {
VoiceChannel vChannel = member.getVoiceState().getChannel();
if (player.isConnected()) {
if (player.isConnectedTo(vChannel)) {
player.skip();
} else
event.getTextChannel().sendMessage("Not in your voice channel").queue();
} else
event.getTextChannel().sendMessage("Not in a voice channel").queue();
} else
event.getTextChannel().sendMessage("You are not in a voice channel").queue();
return null;
} }
} }
@@ -3,15 +3,14 @@ package netneutrality.command.music;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.Visibility; import netneutrality.command.CommandContext;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.MusicUtils;
public class StopCommand extends AbstractMusicCommand { public class StopCommand extends AbstractMusicCommand {
@Override @Override
@@ -45,29 +44,10 @@ public class StopCommand extends AbstractMusicCommand {
} }
@Override @Override
public Visibility getVisibility() { public void execute(CommandContext context) {
return Visibility.CHANNEL; MusicManager player = MusicManager.get(context.getGuild());
} MusicUtils.checkIfConnected(player, context);
@Override player.leave();
public String execute(MessageReceivedEvent event, String[] args) {
Member member = event.getMember();
MusicManager player = MusicManager.get(event.getGuild());
if (member.getVoiceState().inVoiceChannel()) {
VoiceChannel vChannel = member.getVoiceState().getChannel();
if (player.isConnected()) {
if (player.isConnectedTo(vChannel)) {
player.leave();
} else
event.getTextChannel().sendMessage("Not in your voice channel").queue();
} else
event.getTextChannel().sendMessage("Not in a voice channel").queue();
} else
event.getTextChannel().sendMessage("You are not in a voice channel").queue();
return null;
} }
} }
@@ -3,16 +3,16 @@ package netneutrality.command.music;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.Visibility; import netneutrality.command.CommandContext;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.MessageFunction; import netneutrality.utils.MessageFunction;
import netneutrality.utils.MusicUtils;
public class ViewQueueCommand extends AbstractMusicCommand { public class ViewQueueCommand extends AbstractMusicCommand {
@Override @Override
@@ -46,36 +46,16 @@ public class ViewQueueCommand extends AbstractMusicCommand {
} }
@Override @Override
public Visibility getVisibility() { public void execute(CommandContext context) {
return Visibility.CHANNEL; Member member = context.getGuildUser();
} MusicManager player = MusicManager.get(context.getGuild());
MusicUtils.checkIfConnected(player, context);
@Override int queueSize = player.getScheduler().getQueue().size();
public String execute(MessageReceivedEvent event, String[] args) { if (queueSize > 0) {
Member member = event.getMember(); context.getChannel().sendMessageEmbeds(MessageFunction.buildViewQueueMessage(player, member)).queue();
} else {
if (member.getVoiceState().inVoiceChannel()) { context.getChannel().sendMessage("Queue is empty!").queue();
MusicManager player = MusicManager.get(event.getGuild()); }
VoiceChannel vChannel = member.getVoiceState().getChannel();
if (player.isConnected()) {
if (player.isConnectedTo(vChannel)) {
int queueSize = player.getScheduler().getQueue().size();
if (queueSize > 0) {
event.getTextChannel().sendMessageEmbeds(MessageFunction.buildViewQueueMessage(player, member)).queue();
} else {
event.getTextChannel().sendMessage("Queue is empty!").queue();
}
} else
event.getTextChannel().sendMessage("Not in your voice channel").queue();
} else {
event.getTextChannel().sendMessage("Player is not connected").queue();
}
} else
event.getTextChannel().sendMessage("You are not in a voice channel").queue();
return null;
} }
} }
@@ -3,15 +3,15 @@ package netneutrality.command.music;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.Visibility; import netneutrality.command.CommandContext;
import netneutrality.exceptions.CommandErrorException;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.MusicUtils;
public class VolumeCommand extends AbstractMusicCommand { public class VolumeCommand extends AbstractMusicCommand {
@Override @Override
@@ -45,36 +45,16 @@ public class VolumeCommand extends AbstractMusicCommand {
} }
@Override @Override
public Visibility getVisibility() { public void execute(CommandContext context) {
return Visibility.CHANNEL; MusicManager player = MusicManager.get(context.getGuild());
} MusicUtils.checkIfConnected(player, context);
@Override try {
public String execute(MessageReceivedEvent event, String[] args) { int volume = Integer.parseInt(context.getArgumentsAsArray()[0]);
Member member = event.getMember(); player.setVolume(volume);
MusicManager player = MusicManager.get(event.getGuild()); } catch (NumberFormatException e) {
throw new CommandErrorException("Please enter a value from 0 to 100", context, null);
}
if (member.getVoiceState().inVoiceChannel()) {
VoiceChannel vChannel = member.getVoiceState().getChannel();
if (player.isConnected()) {
if (player.isConnectedTo(vChannel)) {
try {
int volume = Integer.parseInt(args[0]);
player.setVolume(volume);
} catch (NumberFormatException e) {
e.printStackTrace();
}
} else
event.getTextChannel().sendMessage("Not in your voice channel").queue();
} else
event.getTextChannel().sendMessage("Not in a voice channel").queue();
} else
event.getTextChannel().sendMessage("You are not in a voice channel").queue();
return null;
} }
} }
@@ -1,13 +1,13 @@
package netneutrality.command.music;/* package netneutrality.command.music;
/*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* https://xtremcommunity.com/ * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.Visibility; import netneutrality.command.CommandContext;
public class VoteSkipCommand extends AbstractMusicCommand { public class VoteSkipCommand extends AbstractMusicCommand {
@@ -37,12 +37,7 @@ public class VoteSkipCommand extends AbstractMusicCommand {
} }
@Override @Override
public Visibility getVisibility() { public void execute(CommandContext context) {
return null;
}
@Override
public String execute(MessageReceivedEvent event, String[] args) {
return null;
} }
} }
@@ -1,117 +1,116 @@
package netneutrality.command.specific; package netneutrality.command.specific;
/*
import java.awt.Color; * Copyright (c) anthorob
import java.time.OffsetDateTime; *
import java.time.format.DateTimeFormatter; * https://xtremcommunity.com/
import java.util.ArrayList; * https://discord.gg/CdFcyQ
*/
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.Visibility;
import netneutrality.db.DBController; import netneutrality.db.DBController;
import netneutrality.db.controllers.DBMessage; import netneutrality.db.controllers.DBMessage;
import netneutrality.db.models.MMessage; import netneutrality.db.models.MMessage;
import netneutrality.utils.Settings; import netneutrality.utils.Settings;
import java.awt.*;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
public class DatabaseCommand extends AbstractCommand { public class DatabaseCommand extends AbstractCommand {
@Override @Override
public boolean needAdmin() { public boolean needAdmin() {
return true; return true;
} }
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return true; return true;
} }
@Override @Override
public String getCommand() { public String getCommand() {
return "database"; return "database";
} }
@Override @Override
public String[] getAlias() { public String[] getAlias() {
return new String[] { "db" }; return new String[]{"db"};
} }
@Override @Override
public String getUsage() { public String getUsage() {
return null; return null;
} }
@Override @Override
public String getDescription() { public String getDescription() {
return null; return null;
} }
@Override @Override
public Visibility getVisibility() { public CommandType getType() {
return Visibility.CHANNEL; return CommandType.UNLISTED;
} }
@Override @Override
public CommandType getType() { public void execute(CommandContext context) {
return null; //TODO: Clean up the mess
} String[] args = context.getArgumentsAsArray();
context.getMessage().delete().queue();
@Override if (!context.getGuildUser().getId().equals(Settings.getInstance().getCreatorId()))
public String execute(MessageReceivedEvent event, String[] args) { return;
//TODO: Clean up the mess
event.getMessage().delete().queue(); if (args.length > 0) {
switch (args[0]) {
if (!event.getAuthor().getId().equals(Settings.getInstance().getCreatorId())) case "message":
return null;
if (args.length > 0) { if (args.length > 1) {
switch (args[0]) {
case "message": MMessage message = ((DBMessage) DBController.get("message")).getMessage(args[1]);
if (message != null) {
EmbedBuilder embed = new EmbedBuilder();
embed.setColor(Color.BLUE);
embed.setTimestamp(
DateTimeFormatter.ofPattern(Settings.getInstance().DATETIMEFORMAT).parse(message.getDateSent()));
embed.setFooter("Guild : " + message.getServerId() + " | ID : " + message.getMessageId(), null);
embed.setDescription(
"Message from " + message.getSender() + " on the channel " + message.getChannelName());
embed.addField("Message: ", "" + message.getMessage(), false);
context.getChannel().sendMessageEmbeds(embed.build()).queue();
} else {
//TODO: cached user lol xd
User user = context.getJDA().getUserById(args[1]);
if (user != null) {
ArrayList<MMessage> messages = ((DBMessage) DBController.get("message"))
.getMessagesFromUser(user.getName(), context.getGuild().getName(), 10);
EmbedBuilder embed = new EmbedBuilder();
embed.setColor(Color.BLUE);
embed.setTimestamp(OffsetDateTime.now());
for (MMessage message1 : messages) {
embed.addField(
"Message in channel \"" + message1.getChannelName() + "\" sent on "
+ message1.getDateSent(),
"" + message1.getMessage(), false);
}
embed.setFooter("Guild : " + context.getGuild().getName(), null);
if (args.length > 1) { context.getDiscordUser().openPrivateChannel().queue(t -> t.sendMessageEmbeds(embed.build()).queue());
}
}
MMessage message = ((DBMessage) DBController.get("message")).getMessage(args[1]); }
if (message != null) {
EmbedBuilder embed = new EmbedBuilder();
embed.setColor(Color.BLUE);
embed.setTimestamp(
DateTimeFormatter.ofPattern(Settings.getInstance().DATETIMEFORMAT).parse(message.getDateSent()));
embed.setFooter("Guild : " + message.getServerId() + " | ID : " + message.getMessageId(), null);
embed.setDescription(
"Message from " + message.getSender() + " on the channel " + message.getChannelName());
embed.addField("Message: ", "" + message.getMessage(), false);
event.getTextChannel().sendMessageEmbeds(embed.build()).queue();
} else {
User user = event.getJDA().getUserById(args[1]);
if (user != null) {
ArrayList<MMessage> messages = ((DBMessage) DBController.get("message"))
.getMessagesFromUser(user.getName(), event.getGuild().getName(), 10);
EmbedBuilder embed = new EmbedBuilder();
embed.setColor(Color.BLUE);
embed.setTimestamp(OffsetDateTime.now());
for (MMessage message1 : messages) {
embed.addField(
"Message in channel \"" + message1.getChannelName() + "\" sent on "
+ message1.getDateSent(),
"" + message1.getMessage(), false);
}
embed.setFooter("Guild : " + event.getGuild().getName(), null);
event.getAuthor().openPrivateChannel().queue(t -> t.sendMessageEmbeds(embed.build()).queue()); break;
} }
} }
}
}
break;
}
}
return null;
}
} }
@@ -3,13 +3,14 @@ package netneutrality.command.specific;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.MessageBuilder;
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.Visibility;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.Settings; import netneutrality.utils.Settings;
@@ -36,7 +37,7 @@ public class EvalMethod extends AbstractCommand {
@Override @Override
public String[] getAlias() { public String[] getAlias() {
return new String[] {"eval"}; return new String[]{"eval"};
} }
@Override @Override
@@ -49,42 +50,38 @@ public class EvalMethod extends AbstractCommand {
return null; return null;
} }
@Override
public Visibility getVisibility() {
return Visibility.BOTH;
}
@Override @Override
public CommandType getType() { public CommandType getType() {
return null; return CommandType.UNLISTED;
} }
@Override @Override
public String execute(MessageReceivedEvent event, String[] args) { public void execute(CommandContext context) {
if (event.getAuthor().getId().equals(Settings.getInstance().getCreatorId())) { if (context.getDiscordUser().getId().equals(Settings.getInstance().getCreatorId())) {
ScriptEngine se = new ScriptEngineManager().getEngineByName("Nashorn"); ScriptEngine se = new ScriptEngineManager().getEngineByName("Nashorn");
MessageBuilder message = new MessageBuilder();
try { try {
se.eval("var imports = new JavaImporter(java.io, java.lang, java.util);"); se.eval("var imports = new JavaImporter(java.io, java.lang, java.util);");
se.put("jda", context.getJDA());
se.put("guild", context.getGuild());
se.put("channel", context.getChannel());
se.put("member", context.getGuildUser());
se.put("music", MusicManager.get(context.getGuild()));
String script = String.format("( function() { with (imports) { return %s } } )();", context.getMessageText());
message.append("Evaluated Successfully:");
message.appendCodeBlock(se.eval(script).toString(), "java");
context.getChannel().sendMessage(message.build()).queue();
} catch (ScriptException e) { } catch (ScriptException e) {
e.printStackTrace(); e.printStackTrace();
context.getChannel().sendMessage(" An exception was thrown:\n```\n" + e.getMessage() + " ```").queue();
} }
se.put("event", event);
se.put("jda", event.getJDA());
se.put("guild", event.getGuild());
se.put("channel", event.getChannel());
se.put("member", event.getMember());
se.put("music", MusicManager.get(event.getGuild()));
try {
event.getTextChannel().sendMessage(" Evaluated Successfully:\n```"+se.eval("(function() {with (imports) {\nreturn " + args + "\n}})();") + " ```").queue();
}
catch(Exception e) {
event.getTextChannel().sendMessage(" An exception was thrown:\n```\n"+e+" ```").queue();
}
} }
return null;
} }
} }
@@ -1,16 +1,17 @@
package netneutrality.command.specific; package netneutrality.command.specific;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.Visibility;
public class LoggingCommand extends AbstractCommand { public class LoggingCommand extends AbstractCommand {
public LoggingCommand() {
}
@Override @Override
public boolean needAdmin() { public boolean needAdmin() {
return true; return true;
@@ -41,20 +42,13 @@ public class LoggingCommand extends AbstractCommand {
return null; return null;
} }
@Override
public Visibility getVisibility() {
return Visibility.CHANNEL;
}
@Override @Override
public CommandType getType() { public CommandType getType() {
return null; return CommandType.UNLISTED;
} }
@Override @Override
public String execute(MessageReceivedEvent event, String[] args) { public void execute(CommandContext context) {
return null;
} }
} }
@@ -3,13 +3,13 @@ package netneutrality.command.specific;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.Visibility;
import netneutrality.db.DBController; import netneutrality.db.DBController;
import netneutrality.db.controllers.DBSettings; import netneutrality.db.controllers.DBSettings;
import netneutrality.db.models.MSellyOrder; import netneutrality.db.models.MSellyOrder;
@@ -49,19 +49,14 @@ public class SellyCommand extends AbstractCommand {
return null; return null;
} }
@Override
public Visibility getVisibility() {
return Visibility.PRIVATE;
}
@Override @Override
public CommandType getType() { public CommandType getType() {
return null; return CommandType.UNLISTED;
} }
@Override @Override
public String execute(MessageReceivedEvent event, String[] args) { public void execute(CommandContext context) {
//TODO: delete or move to custom command when implemented
String sellyEmail = ((DBSettings) DBController.get("settings")).getSettingsByKey("selly_email"); String sellyEmail = ((DBSettings) DBController.get("settings")).getSettingsByKey("selly_email");
String sellyKey = ((DBSettings) DBController.get("settings")).getSettingsByKey(""); String sellyKey = ((DBSettings) DBController.get("settings")).getSettingsByKey("");
Selly selly = new Selly(sellyEmail, sellyKey); Selly selly = new Selly(sellyEmail, sellyKey);
@@ -70,24 +65,22 @@ public class SellyCommand extends AbstractCommand {
System.out.println(selly.getProducts().toString()); System.out.println(selly.getProducts().toString());
if (args.length > 1) { if (context.getArgumentsAsArray().length > 1) {
String email = args[0]; String email = context.getArgumentsAsArray()[0];
String id = args[1]; String id = context.getArgumentsAsArray()[1];
if (orders.containsKey(id)) { if (orders.containsKey(id)) {
MSellyOrder order = orders.get(id); MSellyOrder order = orders.get(id);
if (email.equals(order.getEmail())) { if (email.equals(order.getEmail())) {
if (order.getStatus() == 100) { if (order.getStatus() == 100) {
event.getAuthor().openPrivateChannel().queue(t -> t.sendMessage("success").queue()); context.getDiscordUser().openPrivateChannel().queue(t -> t.sendMessage("success").queue());
} else } else
event.getAuthor().openPrivateChannel().queue(t -> t.sendMessage("not completed").queue()); context.getDiscordUser().openPrivateChannel().queue(t -> t.sendMessage("not completed").queue());
} else } else
event.getAuthor().openPrivateChannel().queue(t -> t.sendMessage("wrong email").queue()); context.getDiscordUser().openPrivateChannel().queue(t -> t.sendMessage("wrong email").queue());
} else } else
event.getAuthor().openPrivateChannel().queue(t -> t.sendMessage("order doesn't exist").queue()); context.getDiscordUser().openPrivateChannel().queue(t -> t.sendMessage("order doesn't exist").queue());
} else } else
event.getAuthor().openPrivateChannel().queue(t -> t.sendMessage("usage : $selly <email> <order_id>").queue()); context.getDiscordUser().openPrivateChannel().queue(t -> t.sendMessage("usage : $selly <email> <order_id>").queue());
return null;
} }
} }
@@ -1,57 +0,0 @@
package netneutrality.command.specific;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandType;
import netneutrality.command.Visibility;
public class ShutdownCommand extends AbstractCommand {
@Override
public boolean needAdmin() {
return true;
}
@Override
public boolean isEnabled() {
return false;
}
@Override
public String getCommand() {
return null;
}
@Override
public String[] getAlias() {
return null;
}
@Override
public String getUsage() {
return null;
}
@Override
public String getDescription() {
return null;
}
@Override
public Visibility getVisibility() {
return Visibility.BOTH;
}
@Override
public CommandType getType() {
return null;
}
@Override
public String execute(MessageReceivedEvent event, String[] args) {
event.getJDA().shutdown();
System.exit(0);
return null;
}
}
@@ -3,15 +3,13 @@ package netneutrality.command.specific;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.Visibility;
import netneutrality.utils.MessageFunction;
import netneutrality.utils.Settings;
public class TestCommand extends AbstractCommand { public class TestCommand extends AbstractCommand {
@@ -22,7 +20,7 @@ public class TestCommand extends AbstractCommand {
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return true; return false;
} }
@Override @Override
@@ -45,22 +43,13 @@ public class TestCommand extends AbstractCommand {
return null; return null;
} }
@Override
public Visibility getVisibility() {
return Visibility.BOTH;
}
@Override @Override
public CommandType getType() { public CommandType getType() {
return null; return CommandType.UNLISTED;
} }
@Override @Override
public String execute(MessageReceivedEvent event, String[] args) { public void execute(CommandContext context) {
if (event.getAuthor().getId().equals(Settings.getInstance().getCreatorId())) {
MessageFunction.isStartingWithMention(event.getMessage());
}
return null;
} }
} }
@@ -16,6 +16,12 @@ public class DBGuild extends AbstractController {
} }
} }
public void removeGuildInDB(Guild g) {
if (database.exists("guilds", "guild_id", g.getId())) {
database.prepareAndExecuteAsync("INSERT INTO guilds VALUES(?, ?, ?)", g.getId(), "0", null).blocking();
}
}
@Override @Override
public String getControllerName() { public String getControllerName() {
return "guild"; return "guild";
@@ -4,10 +4,7 @@ import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.function.Consumer; import java.util.function.Consumer;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.User;
import netneutrality.db.AbstractController; import netneutrality.db.AbstractController;
import netneutrality.db.DBController; import netneutrality.db.DBController;
import netneutrality.db.MysqlDatabase; import netneutrality.db.MysqlDatabase;
@@ -30,7 +27,7 @@ public class DBMessage extends AbstractController {
return database; return database;
} }
public void log(Guild guild, TextChannel channel, User author, Message message) { public void log(Guild guild, TextChannel channel, Member author, Message message) {
String serverid = guild.getId(); String serverid = guild.getId();
String channelid = channel.getId(); String channelid = channel.getId();
String userid = author.getId(); String userid = author.getId();
@@ -0,0 +1,25 @@
package netneutrality.exceptions;/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import netneutrality.command.CommandContext;
/**
* Used to reply with a message in the text channel where the command was executed
*/
public class CommandErrorException extends CommandException {
/**
* Used to reply with a message in the text channel where the command was executed
*
* @param message Message to send to the channel
* @param context The command context
*/
public CommandErrorException(String message, CommandContext context, Throwable cause) {
super(message, context, cause);
}
}
@@ -0,0 +1,23 @@
package netneutrality.exceptions;/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import netneutrality.command.CommandContext;
public abstract class CommandException extends RuntimeException {
public static String DEFAULT_MESSAGE = "Unknown error during command execution.";
private final CommandContext context;
public CommandException(String message, CommandContext context, Throwable cause) {
super(message== null ? DEFAULT_MESSAGE : message, cause);
this.context = context;
}
public CommandContext getCommandContext() {
return context;
}
}
@@ -0,0 +1,23 @@
package netneutrality.exceptions;/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import netneutrality.command.CommandContext;
/**
* Logs the error internally, without sending a message
*/
public class CommandExecutionException extends CommandException {
/**
* Logs the error internally, without sending a message
* @param context The command context
*/
public CommandExecutionException(String message, CommandContext context, Throwable cause) {
super(message, context, cause);
}
}
@@ -19,9 +19,8 @@ package netneutrality.exceptions;
import java.sql.SQLException; import java.sql.SQLException;
public class UnimplementedParameterException extends SQLException { public class UnimplementedParameterException extends SQLException {
private static final long serialVersionUID = 4721555678157694115L; private final String s;
private String s;
public UnimplementedParameterException(Object parameter) { public UnimplementedParameterException(Object parameter) {
s = "Parameter not implemented at for: " + parameter; s = "Parameter not implemented at for: " + parameter;
@@ -1,5 +1,12 @@
package netneutrality.handler; package netneutrality.handler;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import java.awt.Color; import java.awt.Color;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
@@ -12,40 +19,40 @@ import netneutrality.db.controllers.DBSettings;
import netneutrality.db.models.MTableModel; import netneutrality.db.models.MTableModel;
public class EditHandler extends ListenerAdapter { public class EditHandler extends ListenerAdapter {
@Override
public void onMessageUpdate(MessageUpdateEvent event) {
if (event.getAuthor().isBot()) return;
MTableModel table = DBController.get().prepareAndExecuteAsync("SELECT channel_id FROM logging WHERE guild_id = ? AND enabled = 1", event.getGuild().getId()).blocking(); @Override
public void onMessageUpdate(MessageUpdateEvent event) {
if (event.getAuthor().isBot()) return;
MTableModel table = DBController.get().prepareAndExecuteAsync("SELECT channel_id FROM logging WHERE guild_id = ? AND enabled = 1", event.getGuild().getId()).blocking();
Object logChannel = table.getRowModel(0).getItem(0);
if (logChannel != null) {
String originalMessage = ((DBMessage) DBController.get("message")).getMessageString(event.getMessage().getId());
((DBMessage) DBController.get("message")).logEdit(event.getMessage().getId(), event.getMessage().getContentDisplay());
EmbedBuilder editEmbed = new EmbedBuilder();
editEmbed.setColor(Color.RED);
editEmbed.setDescription(":pencil2: **Message edited by " + event.getAuthor().getName() + "**");
try {
editEmbed.addField("Original message", (originalMessage == null ? "Not available" : originalMessage), false);
} catch (IllegalArgumentException ex) {
editEmbed.addField("Original message :", "Message too long. Check db for full message", false);
}
try {
editEmbed.addField("Edited to :", event.getMessage().getContentDisplay(), false);
} catch (IllegalArgumentException ex) {
editEmbed.addField("Edited to :", "Message too long. Check db for full message", false);
}
editEmbed.setFooter("ID : " + event.getMessageId(), null);
editEmbed.setTimestamp(event.getMessage().getTimeCreated());
event.getJDA().getTextChannelById(logChannel.toString()).sendMessageEmbeds(editEmbed.build()).queue();
}
}
Object logChannel = table.getRowModel(0).getItem(0);
if (logChannel != null) {
String originalMessage = ((DBMessage) DBController.get("message")).getMessageString(event.getMessage().getId());
((DBMessage) DBController.get("message")).logEdit(event.getMessage().getId(), event.getMessage().getContentDisplay());
EmbedBuilder editEmbed = new EmbedBuilder();
editEmbed.setColor(Color.RED);
editEmbed.setDescription(":pencil2: **Message edited by " + event.getAuthor().getName() + "**");
try {
editEmbed.addField("Original message", (originalMessage == null ? "Not available" : originalMessage), false);
} catch (IllegalArgumentException ex) {
editEmbed.addField("Original message :", "Message too long. Check db for full message", false);
}
try {
editEmbed.addField("Edited to :", event.getMessage().getContentDisplay(), false);
} catch (IllegalArgumentException ex) {
editEmbed.addField("Edited to :", "Message too long. Check db for full message", false);
}
editEmbed.setFooter("ID : " + event.getMessageId(), null);
editEmbed.setTimestamp(event.getMessage().getTimeCreated());
event.getJDA().getTextChannelById(logChannel.toString()).sendMessageEmbeds(editEmbed.build()).queue();
}
}
} }
@@ -1,30 +1,50 @@
package netneutrality.handler; package netneutrality.handler;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import netneutrality.MusicBot; import netneutrality.command.CommandContext;
import netneutrality.utils.Settings; import netneutrality.exceptions.CommandErrorException;
import netneutrality.exceptions.CommandExecutionException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
public class LogHandler { public class LogHandler {
private final static Logger logger = LoggerFactory.getLogger(LogHandler.class); private final static Logger logger = LoggerFactory.getLogger(LogHandler.class);
/** /**
* Log the exception to the owner's log TextChannel as defined in {@link Settings#getLogChannel()} * Log an exception accordingly
* *
* @param e The exceptions to log * @param e The exceptions to log
*/ */
public static void log(Exception e) { public static void log(Exception e) {
logger.error(e.getMessage()); if (e instanceof CommandErrorException) {
sendMessageToChannel((CommandErrorException) e);
} else if (e instanceof CommandExecutionException) {
logInternally((CommandExecutionException) e);
} else {
logger.error(e.getMessage(), e);
}
//TODO: to remove or add check if jda is started }
String channel = Settings.getInstance().getLogChannel();
MusicBot.getJDA().getTextChannelById(channel).sendMessage("Error : " + e).queue();
}
public static void logThread(Thread t, Throwable e) { public static void logThread(Thread t, Throwable e) {
logger.error("Exception thrown in thread " + t, e); logger.error("Exception thrown in thread {}", t);
} log((Exception) e);
}
private static void logInternally(CommandExecutionException error) {
CommandContext context = error.getCommandContext();
logger.error("Exception thrown from command [{}] in guild [{}]: {}", context.getCommand().getCommand(), context.getGuild().getId(), error.getMessage(), error);
}
private static void sendMessageToChannel(CommandErrorException error) {
CommandContext context = error.getCommandContext();
context.getChannel().sendMessage(error.getMessage()).queue();
}
} }
@@ -0,0 +1,55 @@
package netneutrality.handler;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import netneutrality.GuildManager;
import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandManager;
import netneutrality.utils.Settings;
import org.jetbrains.annotations.NotNull;
public class MessageReceivedHandler extends ListenerAdapter {
@Override
public void onGuildMessageReceived(@NotNull GuildMessageReceivedEvent event) {
Message message = event.getMessage();
Member member = event.getMember();
User user = event.getAuthor();
Guild guild = event.getGuild();
TextChannel channel = event.getChannel();
if (user.isBot()) return;
if (event.isWebhookMessage()) return;
GuildManager.getManager(guild).getRateLimiter().check(member, message, channel);
GuildManager.getManager(guild).checkAndLogMessage(message, member, channel);
CommandContext context = CommandContext.createContext(event);
String msg = message.getContentDisplay().trim();
if (msg.startsWith(Settings.getInstance().get("BOT_PREFIX", "$"))) {
msg = msg.substring(Settings.getInstance().get("BOT_PREFIX", "$").length()).trim();
String cmd = msg.split(" ", 2)[0];
if (CommandManager.commands.containsKey(cmd) || CommandManager.commandsAlias.containsKey(cmd)) {
AbstractCommand c = CommandManager.commands.containsKey(cmd) ? CommandManager.commands.get(cmd) : CommandManager.commandsAlias.get(cmd);
context.dispatch(c);
}
} else {
GuildManager.getManager(guild).checkBlacklist(message, member, channel);
}
}
}
@@ -1,77 +0,0 @@
package netneutrality.handler;
import net.dv8tion.jda.api.entities.ChannelType;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import netneutrality.GuildManager;
import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandManager;
import netneutrality.command.Visibility;
import netneutrality.db.DBController;
import netneutrality.db.controllers.DBMessage;
import netneutrality.utils.MessageFunction;
import netneutrality.utils.Settings;
import netneutrality.utils.UserFunction;
import org.jetbrains.annotations.NotNull;
public class NewCommandListener extends ListenerAdapter {
public NewCommandListener() {
CommandManager.init();
}
@Override
public void onGuildMessageReceived(@NotNull GuildMessageReceivedEvent event) {
if (event.getAuthor().isBot()) return;
if (event.isWebhookMessage()) return;
GuildManager.getManager(event.getGuild()).getRateLimiter().check(event.getMember(), event.getMessage(), event.getChannel());
}
@Override
public void onMessageReceived(@NotNull MessageReceivedEvent event) {
if (event.getAuthor().isBot()) return;
if (event.isWebhookMessage()) return;
if (event.getMessage().isEdited())
if (event.isFromType(ChannelType.TEXT)) {
((DBMessage) DBController.get("message")).log(event.getGuild(), event.getTextChannel(), event.getAuthor(), event.getMessage());
}
Message message = event.getMessage();
String msg = message.getContentDisplay().trim();
if (msg.startsWith(Settings.getInstance().get("BOT_PREFIX", "$"))) {
msg = msg.substring(Settings.getInstance().get("BOT_PREFIX", "$").length()).trim();
String cmd = msg.split(" ", 2)[0];
String[] args = msg.replaceFirst("(" + cmd + ")(\s)?", "").split("\s");
if (args.length == 1 && args[0].isEmpty())
args = new String[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 (Visibility.check(event.getChannel(), c.getVisibility())) {
if (c.needAdmin()) {
if (!UserFunction.isAdmin(event.getMember())) {
return;
}
}
if (c.canBeExecutedBy(event.getGuild(), event.getMember())) {
c.execute(event, args);
}
}
}
} else {
MessageFunction.checkBlacklist(event.getGuild().getId(), event.getMessage(), event.getTextChannel(), msg);
}
}
}
@@ -8,6 +8,7 @@ package netneutrality.handler;
*/ */
import net.dv8tion.jda.api.events.guild.GuildJoinEvent; import net.dv8tion.jda.api.events.guild.GuildJoinEvent;
import net.dv8tion.jda.api.events.guild.GuildLeaveEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.hooks.ListenerAdapter;
import netneutrality.db.DBController; import netneutrality.db.DBController;
import netneutrality.db.controllers.DBGuild; import netneutrality.db.controllers.DBGuild;
@@ -16,11 +17,14 @@ import org.jetbrains.annotations.NotNull;
public class ServerJoinHandler extends ListenerAdapter { public class ServerJoinHandler extends ListenerAdapter {
@Override @Override
public void onGuildJoin(@NotNull GuildJoinEvent event){ public void onGuildJoin(@NotNull GuildJoinEvent event) {
if (!DBController.get().exists("guilds", "guild_id", event.getGuild().getId())) { ((DBGuild) DBController.get("guild")).insertGuildInDB(event.getGuild());
((DBGuild) DBController.get("guild")).insertGuildInDB(event.getGuild());
}
}
@Override
public void onGuildLeave(@NotNull GuildLeaveEvent event) {
((DBGuild) DBController.get("guild")).removeGuildInDB(event.getGuild());
} }
} }
@@ -3,7 +3,8 @@ package netneutrality.music;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
@@ -18,29 +19,29 @@ import java.nio.ByteBuffer;
* provide20MsAudio(). * provide20MsAudio().
*/ */
public class AudioPlayerSendHandler implements AudioSendHandler { public class AudioPlayerSendHandler implements AudioSendHandler {
private final AudioPlayer audioPlayer; private final AudioPlayer audioPlayer;
private AudioFrame lastFrame; private AudioFrame lastFrame;
/** /**
* @param audioPlayer Audio player to wrap. * @param audioPlayer Audio player to wrap.
*/ */
public AudioPlayerSendHandler(AudioPlayer audioPlayer) { public AudioPlayerSendHandler(AudioPlayer audioPlayer) {
this.audioPlayer = audioPlayer; this.audioPlayer = audioPlayer;
} }
@Override @Override
public boolean canProvide() { public boolean canProvide() {
lastFrame = audioPlayer.provide(); lastFrame = audioPlayer.provide();
return lastFrame != null; return lastFrame != null;
} }
@Override @Override
public ByteBuffer provide20MsAudio() { public ByteBuffer provide20MsAudio() {
return ByteBuffer.wrap(lastFrame.getData()); return ByteBuffer.wrap(lastFrame.getData());
} }
@Override @Override
public boolean isOpus() { public boolean isOpus() {
return true; return true;
} }
} }
@@ -1,4 +1,5 @@
package netneutrality.music;/* package netneutrality.music;
/*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* https://xtremcommunity.com/ * https://xtremcommunity.com/
@@ -37,15 +38,15 @@ public class LoadResultHandler implements AudioLoadResultHandler {
} }
scheduler.queue(audioTrack); scheduler.queue(audioTrack);
} }
@Override @Override
public void playlistLoaded(AudioPlaylist audioPlaylist) { public void playlistLoaded(AudioPlaylist audioPlaylist) {
if (identifier.startsWith("ytsearch:")) { if (identifier.startsWith("ytsearch:")) {
AudioTrack track = audioPlaylist.getTracks().get(0); AudioTrack track = audioPlaylist.getTracks().get(0);
channel.sendMessageEmbeds(MessageFunction.buildAddingTrackMessage(track, user, identifier)).queue(); channel.sendMessageEmbeds(MessageFunction.buildAddingTrackMessage(track, user, String.format("https://youtu.be/%s", track.getIdentifier()))).queue();
scheduler.queue(track); scheduler.queue(track);
} else { } else {
channel.sendMessageEmbeds(MessageFunction.buildAddingPlaylistMessage(audioPlaylist, user, identifier)).queue(); channel.sendMessageEmbeds(MessageFunction.buildAddingPlaylistMessage(audioPlaylist, user, identifier)).queue();
@@ -62,6 +63,7 @@ public class LoadResultHandler implements AudioLoadResultHandler {
@Override @Override
public void loadFailed(FriendlyException e) { public void loadFailed(FriendlyException e) {
channel.sendMessage(e.getMessage()).queue();
LogHandler.log(e); LogHandler.log(e);
} }
} }
@@ -3,7 +3,8 @@ package netneutrality.music;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
@@ -11,14 +12,17 @@ import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager; import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers; import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.VoiceChannel;
import netneutrality.ThreadManager; import netneutrality.ThreadManager;
import netneutrality.command.CommandContext;
import netneutrality.exceptions.CommandErrorException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@@ -70,8 +74,10 @@ public class MusicManager {
leave(); leave();
} }
}, 120, 120, TimeUnit.SECONDS); }, 120, 120, TimeUnit.SECONDS);
} else } else {
logger.error("Error connecting!"); logger.error("Error connecting!");
}
} }
public boolean isConnected() { public boolean isConnected() {
@@ -100,18 +106,36 @@ public class MusicManager {
} }
} }
public synchronized void play(String url, TextChannel channel, Member user, boolean silent) { public void play(String url, CommandContext context, boolean needToBeConnected, boolean silent) {
Member member = context.getGuildUser();
TextChannel channel = context.getChannel();
if (member.getVoiceState() == null) {
return;
}
if (!member.getVoiceState().inVoiceChannel()) {
throw new CommandErrorException("You are not in a voice channel", context, null);
}
VoiceChannel vChannel = member.getVoiceState().getChannel();
if (needToBeConnected && !isConnectedTo(vChannel)) {
throw new CommandErrorException("Not in your voice channel", context, null);
}
if (!isConnectedTo(vChannel)) {
connect(vChannel);
}
String identifier = SourceFinder.getIdentifier(url); String identifier = SourceFinder.getIdentifier(url);
logger.debug(identifier); logger.debug(identifier);
scheduler.setTextChannel(channel); scheduler.setTextChannel(channel);
if (identifier != null) { if (identifier != null) {
playerManager.loadItem(identifier, new LoadResultHandler(identifier, channel, user, scheduler, silent)); playerManager.loadItem(identifier, new LoadResultHandler(identifier, channel, member, scheduler, silent));
} else { } else {
channel.sendMessage("No source found to play the given url").queue(); throw new CommandErrorException("No source found to play the given url", context, null);
leave();
} }
} }
@@ -1,15 +1,15 @@
package netneutrality.music; package netneutrality.music;
import net.dv8tion.jda.api.entities.TextChannel;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import java.util.regex.Matcher;
import java.util.regex.Pattern;
enum SourceEnum { enum SourceEnum {
Youtube, Youtube,
Soundcloud, Soundcloud,
@@ -22,7 +22,7 @@ enum SourceEnum {
public class SourceFinder { public class SourceFinder {
private static final Pattern youtubePattern = Pattern.compile("^(?:https?://)?(?:(?:www\\.)?)?(?:youtube\\.com|youtu\\.be)/.*?(?:embed|e|v|watch.*?v=)?/?([-_a-z0-9]{10,})?(?:&?index=\\d+)?(?>(?:playlist\\?|&)?list=([^#\\\\&\\?]{12,}))?", Pattern.CASE_INSENSITIVE); private static final Pattern youtubePattern = Pattern.compile("^(?:https?://)?(?:(?:www\\.)?)?(?:youtube\\.com|youtu\\.be)/.*?(?:embed|e|v|watch.*?v=)?/?([-_a-z0-9]{10,})?(?:&?index=\\d+)?(?>(?:playlist\\?|&)?list=([^#\\\\&\\?]{12,}))?", Pattern.CASE_INSENSITIVE);
private static final Pattern soundcloudPattern = Pattern.compile("^(?:https?://)?(?:www\\.)?(?:m\\.)?soundcloud\\.com/([a-zA-Z0-9-_]+)/([a-zA-Z0-9-_]+)(?:\\\\?.*|)$", Pattern.CASE_INSENSITIVE); private static final Pattern soundcloudPattern = Pattern.compile("^(?:https?://)?(?:www\\.)?(?:m\\.)?soundcloud\\.com/([a-zA-Z0-9-_]+)/([a-zA-Z0-9-_]+)(?:\\\\?.*|)$", Pattern.CASE_INSENSITIVE);
private static Matcher youtubeMatcher; private static Matcher youtubeMatcher;
private static Matcher soundcloudMatcher; private static Matcher soundcloudMatcher;
private static Matcher BandcampMatcher; private static Matcher BandcampMatcher;
@@ -45,23 +45,12 @@ public class SourceFinder {
} }
public static String getIdentifier(String url) { public static String getIdentifier(String url) {
String identifier = null; String identifier = switch (getSource(url)) {
case Youtube, Soundcloud -> url;
switch (getSource(url)) { case YTSearch -> "ytsearch:" + url;
case Nothing -> null;
case Youtube: default -> null;
identifier = url; };
break;
case Soundcloud:
identifier = url;
break;
case YTSearch:
identifier = "ytsearch:" + url;
break;
case Nothing:
identifier = null;
break;
}
return identifier; return identifier;
} }
@@ -3,7 +3,8 @@ package netneutrality.music;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
@@ -28,12 +29,11 @@ public class TrackScheduler extends AudioEventAdapter {
this.queue = new LinkedBlockingQueue<>(); this.queue = new LinkedBlockingQueue<>();
} }
public synchronized void queue(AudioTrack track) { public void queue(AudioTrack track) {
// Calling startTrack with the noInterrupt set to true will start the track only if nothing is currently playing. If // Calling startTrack with the noInterrupt set to true will start the track only if nothing is currently playing. If
// something is playing, it returns false and does nothing. In that case the player was already playing so this // something is playing, it returns false and does nothing. In that case the player was already playing so this
// track goes to the queue instead. // track goes to the queue instead.
boolean start = player.startTrack(track, true); boolean start = player.startTrack(track, true);
//channel.getManager().setTopic(":speaker: Now playing : " + track.getInfo().title).queue();
if (!start) { if (!start) {
queue.offer(track); queue.offer(track);
@@ -43,8 +43,8 @@ public class TrackScheduler extends AudioEventAdapter {
public void setTextChannel(TextChannel channel) { public void setTextChannel(TextChannel channel) {
this.channel = channel; this.channel = channel;
if (this.topic == null) { if (topic == null) {
this.topic = channel.getTopic(); topic = channel.getTopic();
} }
} }
@@ -58,11 +58,11 @@ public class TrackScheduler extends AudioEventAdapter {
} }
public void resetTopic() { public void resetTopic() {
if (this.channel != null) { if (channel != null && (topic != null && !topic.equals(""))) {
//this.channel.getManager().setTopic(this.topic).queue(); //channel.getManager().setTopic(topic).queue();
} }
this.topic = ""; topic = "";
} }
/** /**
@@ -73,11 +73,7 @@ public class TrackScheduler extends AudioEventAdapter {
// giving null to startTrack, which is a valid argument and will simply stop the player. // giving null to startTrack, which is a valid argument and will simply stop the player.
AudioTrack track = queue.poll(); AudioTrack track = queue.poll();
if (track != null) { if (track != null) {
//channel.getManager().setTopic(":speaker: Now playing : " + track.getInfo().title).queue();
player.startTrack(track, false); player.startTrack(track, false);
} else {
//channel.getManager().setTopic(topic).queue();
} }
} }
@@ -95,10 +91,13 @@ public class TrackScheduler extends AudioEventAdapter {
@Override @Override
public void onTrackStart(AudioPlayer player, AudioTrack track) { public void onTrackStart(AudioPlayer player, AudioTrack track) {
// A track started playing // A track started playing
//channel.getManager().setTopic(":speaker: Now playing : " + track.getInfo().title).queue();
} }
@Override @Override
public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) { public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) {
resetTopic();
if (endReason.mayStartNext) { if (endReason.mayStartNext) {
nextTrack(); nextTrack();
} }
@@ -113,11 +112,13 @@ public class TrackScheduler extends AudioEventAdapter {
@Override @Override
public void onTrackException(AudioPlayer player, AudioTrack track, FriendlyException exception) { public void onTrackException(AudioPlayer player, AudioTrack track, FriendlyException exception) {
resetTopic();
channel.sendMessage("Error while playing track: " + track.getInfo().title).queue(); channel.sendMessage("Error while playing track: " + track.getInfo().title).queue();
} }
@Override @Override
public void onTrackStuck(AudioPlayer player, AudioTrack track, long thresholdMs) { public void onTrackStuck(AudioPlayer player, AudioTrack track, long thresholdMs) {
resetTopic();
nextTrack(); nextTrack();
} }
} }
@@ -41,7 +41,7 @@ public class ChannelFunction {
private synchronized static void deleteFromList(List<Message> messages, TextChannel channel) { private synchronized static void deleteFromList(List<Message> messages, TextChannel channel) {
try { try {
channel.deleteMessages(messages).complete(); channel.deleteMessages(messages).complete();
logger.debug("Deleted " + messages.size() + " messages from channel ["+ channel.getName() + "] in guild [" + channel.getGuild().getName() + "]"); logger.debug("Deleted {} messages from channel [{}] in guild [{}]", messages.size(), channel.getName(), channel.getGuild().getName());
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
messages.forEach(m -> { messages.forEach(m -> {
@@ -3,7 +3,8 @@ package netneutrality.utils;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import java.awt.*; import java.awt.*;
@@ -16,6 +17,7 @@ import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.entities.*;
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandType;
import netneutrality.db.DBController; import netneutrality.db.DBController;
import netneutrality.db.controllers.DBBlacklist; import netneutrality.db.controllers.DBBlacklist;
import netneutrality.db.models.MBlacklist; import netneutrality.db.models.MBlacklist;
@@ -58,7 +60,7 @@ public class MessageFunction {
return false; return false;
} }
public synchronized static MessageEmbed buildCurrentlyPlayingMessage(MusicManager manager, Member user) { public static MessageEmbed buildCurrentlyPlayingMessage(MusicManager manager, Member user) {
AudioTrack current = manager.getCurrentlyPlaying(); AudioTrack current = manager.getCurrentlyPlaying();
EmbedBuilder message = new EmbedBuilder(); EmbedBuilder message = new EmbedBuilder();
@@ -74,7 +76,7 @@ public class MessageFunction {
return message.build(); return message.build();
} }
public synchronized static MessageEmbed buildAddingTrackMessage(AudioTrack track, Member user, String identifier) { public static MessageEmbed buildAddingTrackMessage(AudioTrack track, Member user, String identifier) {
EmbedBuilder message = new EmbedBuilder(); EmbedBuilder message = new EmbedBuilder();
message.setAuthor("Link to track", identifier); message.setAuthor("Link to track", identifier);
message.setThumbnail(String.format("https://img.youtube.com/vi/%s/default.jpg", track.getIdentifier())); message.setThumbnail(String.format("https://img.youtube.com/vi/%s/default.jpg", track.getIdentifier()));
@@ -88,7 +90,7 @@ public class MessageFunction {
return message.build(); return message.build();
} }
public synchronized static MessageEmbed buildAddingPlaylistMessage(AudioPlaylist playlist, Member user, String identifier) { public static MessageEmbed buildAddingPlaylistMessage(AudioPlaylist playlist, Member user, String identifier) {
EmbedBuilder message = new EmbedBuilder(); EmbedBuilder message = new EmbedBuilder();
message.setAuthor("Link to playlist", identifier); message.setAuthor("Link to playlist", identifier);
message.setThumbnail(String.format("https://img.youtube.com/vi/%s/default.jpg", playlist.getSelectedTrack().getIdentifier())); message.setThumbnail(String.format("https://img.youtube.com/vi/%s/default.jpg", playlist.getSelectedTrack().getIdentifier()));
@@ -124,40 +126,60 @@ public class MessageFunction {
return message.build(); return message.build();
} }
public static MessageEmbed buildHelpMessage(HashMap<String, AbstractCommand> commands, HashMap<String, AbstractCommand> alias) { public static ArrayList<MessageEmbed> buildHelpMessage(HashMap<String, AbstractCommand> commands, HashMap<String, AbstractCommand> alias, boolean admin) {
EmbedBuilder message = new EmbedBuilder();
message.setTitle("Commands for Net Neutrality");
message.setColor(Color.green);
SortedSet<String> keys = new TreeSet<>(commands.keySet()); SortedSet<String> keys = new TreeSet<>(commands.keySet());
for (String key : keys) { HashMap<CommandType, EmbedBuilder> help = new HashMap<>();
AbstractCommand command = commands.get(key);
for (String commandName : keys) {
AbstractCommand command = commands.get(commandName);
if (command.getType() == null)
continue;
String usage = "None"; String usage = "None";
String description = "No description yet"; String description = "No description yet";
if (command.isEnabled()) { if (command.isEnabled() && command.getType() != CommandType.UNLISTED) {
if (command.getType() == CommandType.ADMINISTRATION && !admin)
continue;
if (command.getUsage() != null) if (command.getUsage() != null)
usage = command.getUsage(); usage = command.getUsage();
if (command.getDescription() != null) if (command.getDescription() != null)
description = command.getDescription(); description = command.getDescription();
EmbedBuilder message;
if (help.containsKey(command.getType())) {
message = help.get(command.getType());
} else {
help.put(command.getType(), message = new EmbedBuilder());
}
if (message.isEmpty()) {
message.setTitle(command.getType().getDescription() + " commands for NetNeutrality");
message.setColor(Color.GREEN);
}
message.addField(Settings.getInstance().get("BOT_PREFIX") + command.getCommand() + " - Arguments: " + usage, description, false);
} }
message.addField(Settings.getInstance().get("BOT_PREFIX") + command.getCommand() + " - Arguments: " + usage, description, false);
} }
return message.build(); ArrayList<MessageEmbed> messages = new ArrayList<>();
help.values().forEach(embedBuilder -> messages.add(embedBuilder.build()));
return messages;
} }
public static void checkBlacklist(String guildId, Message message, TextChannel channel, String msg) { public static void checkBlacklist(Guild guild, Message message, TextChannel channel) {
((DBBlacklist) DBController.get("blacklist")).getBlacklistFromServer(guildId, mBlacklists -> { ((DBBlacklist) DBController.get("blacklist")).getBlacklistFromServer(guild.getId(), mBlacklists -> {
if (!mBlacklists.isEmpty()) { if (!mBlacklists.isEmpty()) {
boolean found = false; boolean found = false;
for (MBlacklist aBlacklist : mBlacklists) { for (MBlacklist aBlacklist : mBlacklists) {
if (msg.toLowerCase().contains(aBlacklist.getWord())) { if (message.getContentRaw().toLowerCase().contains(aBlacklist.getWord())) {
found = true; found = true;
break; break;
} }
@@ -0,0 +1,34 @@
package netneutrality.utils;/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import net.dv8tion.jda.api.entities.VoiceChannel;
import netneutrality.command.CommandContext;
import netneutrality.exceptions.CommandErrorException;
import netneutrality.exceptions.CommandExecutionException;
import netneutrality.music.MusicManager;
public class MusicUtils {
public static void checkIfConnected(MusicManager manager, CommandContext context) {
if (context.getGuildUser().getVoiceState() == null) {
throw new CommandExecutionException("Voice state is null", context, null);
}
if (!context.getGuildUser().getVoiceState().inVoiceChannel()) {
throw new CommandErrorException("You are not in a voice channel", context, null);
}
VoiceChannel vChannel = context.getGuildUser().getVoiceState().getChannel();
if (!manager.isConnected()) {
throw new CommandErrorException("Player is not in a voice channel", context, null);
}
if (!manager.isConnectedTo(vChannel)) {
throw new CommandErrorException("Player is not in your voice channel", context, null);
}
}
}