1
0
mirror of https://github.com/sciwhiz12/Janitor.git synced 2024-09-20 01:44:02 +00:00

Move to JDA

This commit is contained in:
Arnold Alejo Nunag 2020-09-18 03:05:56 +08:00
parent fb10a70891
commit 888309063c
Signed by: sciwhiz12
GPG Key ID: 622CF446534317E1
14 changed files with 129 additions and 118 deletions

View File

@ -31,7 +31,7 @@ version = getVersion()
println("Version: ${version}") println("Version: ${version}")
dependencies { dependencies {
implementation group: 'org.javacord', name: 'javacord', version: javacord_version implementation group: 'net.dv8tion', name: 'JDA', version: jda_version
implementation group: 'com.electronwill.night-config', name: 'toml', version: nightconfig_version implementation group: 'com.electronwill.night-config', name: 'toml', version: nightconfig_version
implementation group: 'net.sf.jopt-simple', name: 'jopt-simple', version: jopt_version implementation group: 'net.sf.jopt-simple', name: 'jopt-simple', version: jopt_version
implementation group: 'com.google.guava', name: 'guava', version: guava_version implementation group: 'com.google.guava', name: 'guava', version: guava_version

View File

@ -1,7 +1,7 @@
grgit_version=4.0.2 grgit_version=4.0.2
shadow_version=6.0.0 shadow_version=6.0.0
javacord_version=3.0.6 jda_version=4.2.0_168
nightconfig_version=3.6.3 nightconfig_version=3.6.3
jopt_version=6.0-alpha-3 jopt_version=6.0-alpha-3
guava_version=29.0-jre guava_version=29.0-jre

View File

@ -36,7 +36,7 @@ public class BotConsole {
String[] parts = input.split(" "); String[] parts = input.split(" ");
switch (parts[0]) { switch (parts[0]) {
case "shutdown": { case "shutdown": {
bot.disconnect(); bot.shutdown();
break; break;
} }
default: default:

View File

@ -1,6 +1,12 @@
package sciwhiz12.janitor; package sciwhiz12.janitor;
import org.javacord.api.DiscordApiBuilder; import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.events.ReadyEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.requests.GatewayIntent;
import org.jetbrains.annotations.NotNull;
import sciwhiz12.janitor.config.BotConfig; import sciwhiz12.janitor.config.BotConfig;
import sciwhiz12.janitor.config.BotOptions; import sciwhiz12.janitor.config.BotOptions;
@ -19,9 +25,18 @@ public class BotStartup {
JANITOR.info("Building bot instance and connecting to Discord..."); JANITOR.info("Building bot instance and connecting to Discord...");
try { try {
DiscordApiBuilder builder = new DiscordApiBuilder().setToken(config.getToken().get()); JDABuilder builder = JDABuilder.createDefault(config.getToken().get());
builder.login() builder.enableIntents(GatewayIntent.GUILD_MESSAGES, GatewayIntent.DIRECT_MESSAGES, GatewayIntent.GUILD_MEMBERS)
.thenAccept(api -> new JanitorBot(api, config)); .setStatus(OnlineStatus.DO_NOT_DISTURB)
.setAutoReconnect(true)
.setActivity(Activity.listening("for the ready call..."))
.addEventListeners(new ListenerAdapter() {
@Override
public void onReady(@NotNull ReadyEvent event) {
new JanitorBot(event.getJDA(), config);
}
})
.build();
} catch (Exception ex) { } catch (Exception ex) {
JANITOR.error("Error while building Discord connection", ex); JANITOR.error("Error while building Discord connection", ex);
} }

View File

@ -1,9 +1,10 @@
package sciwhiz12.janitor; package sciwhiz12.janitor;
import org.javacord.api.DiscordApi; import net.dv8tion.jda.api.JDA;
import org.javacord.api.entity.activity.ActivityType; import net.dv8tion.jda.api.OnlineStatus;
import org.javacord.api.entity.user.User; import net.dv8tion.jda.api.entities.Activity;
import org.javacord.api.entity.user.UserStatus; import net.dv8tion.jda.api.entities.PrivateChannel;
import net.dv8tion.jda.api.entities.User;
import sciwhiz12.janitor.commands.CommandRegistry; import sciwhiz12.janitor.commands.CommandRegistry;
import sciwhiz12.janitor.config.BotConfig; import sciwhiz12.janitor.config.BotConfig;
import sciwhiz12.janitor.utils.Util; import sciwhiz12.janitor.utils.Util;
@ -12,35 +13,34 @@ import static sciwhiz12.janitor.Logging.JANITOR;
import static sciwhiz12.janitor.Logging.STATUS; import static sciwhiz12.janitor.Logging.STATUS;
public class JanitorBot { public class JanitorBot {
private final DiscordApi discord; private final JDA discord;
private final BotConfig config; private final BotConfig config;
private final BotConsole console; private final BotConsole console;
private final CommandRegistry cmdRegistry; private final CommandRegistry cmdRegistry;
public JanitorBot(DiscordApi discord, BotConfig config) { public JanitorBot(JDA discord, BotConfig config) {
this.config = config; this.config = config;
this.console = new BotConsole(this, System.in); this.console = new BotConsole(this, System.in);
this.cmdRegistry = new CommandRegistry(this, config.getCommandPrefix()); this.cmdRegistry = new CommandRegistry(this, config.getCommandPrefix());
this.discord = discord; this.discord = discord;
discord.addMessageCreateListener(cmdRegistry); discord.addEventListener(cmdRegistry);
discord.updateStatus(UserStatus.ONLINE); discord.getPresence().setPresence(OnlineStatus.ONLINE, Activity.playing(" n' sweeping n' testing!"));
discord.updateActivity(ActivityType.PLAYING, " n' sweeping n' testing!");
JANITOR.info("Ready!"); JANITOR.info("Ready!");
config.getOwnerID() config.getOwnerID()
.map(ownerId -> getDiscord().getUserById(ownerId)) .map(discord::retrieveUserById)
.ifPresent(retrieveUser -> .ifPresent(retrieveUser ->
retrieveUser retrieveUser
.thenCompose(User::openPrivateChannel) .flatMap(User::openPrivateChannel)
.thenCompose(channel -> channel.sendMessage("Started up and ready!")) .flatMap(channel -> channel.sendMessage("Started up and ready!"))
.whenCompleteAsync(Util.handle( .queue(
msg -> JANITOR.debug(STATUS, "Sent ready message to owner!"), msg -> JANITOR.debug(STATUS, "Sent ready message to owner!"),
error -> JANITOR.error(STATUS, "Error while sending ready message to owner", error)) error -> JANITOR.error(STATUS, "Error while sending ready message to owner", error)
) )
); );
console.start(); console.start();
} }
public DiscordApi getDiscord() { public JDA getDiscord() {
return this.discord; return this.discord;
} }
@ -52,24 +52,28 @@ public class JanitorBot {
return this.cmdRegistry; return this.cmdRegistry;
} }
public void disconnect() { public void shutdown() {
JANITOR.info(STATUS, "Shutting down!"); JANITOR.info(STATUS, "Shutting down!");
console.stop(); console.stop();
discord.disconnect(); getConfig().getOwnerID()
// getConfig().getOwnerID() .map(discord::retrieveUserById)
// .map(id -> getJDA().getUserById(id)) .map(owner ->
// .ifPresent(owner -> owner.openPrivateChannel().submit() owner
// .thenCompose(channel -> channel.sendMessage( .flatMap(User::openPrivateChannel)
// "Shutting down, in accordance with your orders. Goodbye!") .flatMap(channel ->
// .submit()) channel.sendMessage("Shutting down, in accordance with your orders. Goodbye!"))
// .whenComplete(Util.handle( .submit()
// msg -> JANITOR .whenComplete(Util.handle(
// .debug(STATUS, "Sent shutdown message to owner: {}", msg ->
// Util.toString(owner)), JANITOR
// err -> JANITOR .debug(STATUS, "Sent shutdown message to owner: {}",
// .error(STATUS, "Error while sending shutdown message to owner", err) Util.toString(((PrivateChannel) msg.getChannel()).getUser())),
// )) err ->
// .join()); JANITOR
// getJDA().shutdown(); .error(STATUS, "Error while sending shutdown message to owner", err)
))
.join()
);
discord.shutdown();
} }
} }

View File

@ -1,7 +1,7 @@
package sciwhiz12.janitor.commands; package sciwhiz12.janitor.commands;
import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import org.javacord.api.event.message.MessageCreateEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import sciwhiz12.janitor.JanitorBot; import sciwhiz12.janitor.JanitorBot;
public abstract class BaseCommand { public abstract class BaseCommand {
@ -19,5 +19,5 @@ public abstract class BaseCommand {
return registry.getBot(); return registry.getBot();
} }
public abstract LiteralArgumentBuilder<MessageCreateEvent> getNode(); public abstract LiteralArgumentBuilder<MessageReceivedEvent> getNode();
} }

View File

@ -4,8 +4,10 @@ import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.ParseResults; import com.mojang.brigadier.ParseResults;
import com.mojang.brigadier.StringReader; import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.CommandSyntaxException;
import org.javacord.api.event.message.MessageCreateEvent; import net.dv8tion.jda.api.events.GenericEvent;
import org.javacord.api.listener.message.MessageCreateListener; import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.EventListener;
import org.jetbrains.annotations.NotNull;
import sciwhiz12.janitor.JanitorBot; import sciwhiz12.janitor.JanitorBot;
import sciwhiz12.janitor.commands.bot.ShutdownCommand; import sciwhiz12.janitor.commands.bot.ShutdownCommand;
import sciwhiz12.janitor.commands.misc.HelloCommand; import sciwhiz12.janitor.commands.misc.HelloCommand;
@ -19,16 +21,14 @@ import java.util.Map;
import static sciwhiz12.janitor.Logging.COMMANDS; import static sciwhiz12.janitor.Logging.COMMANDS;
import static sciwhiz12.janitor.Logging.JANITOR; import static sciwhiz12.janitor.Logging.JANITOR;
public class CommandRegistry implements MessageCreateListener { public class CommandRegistry implements EventListener {
private final JanitorBot bot; private final JanitorBot bot;
// private final Pattern pattern;
private final String prefix; private final String prefix;
private final Map<String, BaseCommand> registry = new HashMap<>(); private final Map<String, BaseCommand> registry = new HashMap<>();
private final CommandDispatcher<MessageCreateEvent> dispatcher; private final CommandDispatcher<MessageReceivedEvent> dispatcher;
public CommandRegistry(JanitorBot bot, String prefix) { public CommandRegistry(JanitorBot bot, String prefix) {
this.bot = bot; this.bot = bot;
// this.pattern = Pattern.compile("^" + prefix + "([A-Za-z0-9]+).*$");
this.prefix = prefix; this.prefix = prefix;
this.dispatcher = new CommandDispatcher<>(); this.dispatcher = new CommandDispatcher<>();
@ -41,7 +41,7 @@ public class CommandRegistry implements MessageCreateListener {
} }
} }
public CommandDispatcher<MessageCreateEvent> getDispatcher() { public CommandDispatcher<MessageReceivedEvent> getDispatcher() {
return this.dispatcher; return this.dispatcher;
} }
@ -54,14 +54,16 @@ public class CommandRegistry implements MessageCreateListener {
} }
@Override @Override
public void onMessageCreate(MessageCreateEvent event) { public void onEvent(@NotNull GenericEvent genericEvent) {
String msg = event.getMessage().getContent(); if (!(genericEvent instanceof MessageReceivedEvent)) return;
MessageReceivedEvent event = (MessageReceivedEvent) genericEvent;
String msg = event.getMessage().getContentRaw();
if (!msg.startsWith(this.prefix)) return; if (!msg.startsWith(this.prefix)) return;
JANITOR.debug(COMMANDS, "Received message starting with valid command prefix. Author: {}, full message: {}", JANITOR.debug(COMMANDS, "Received message starting with valid command prefix. Author: {}, full message: {}",
Util.toString(event.getMessageAuthor().asUser().orElse(null)), msg); Util.toString(event.getAuthor()), msg);
try { try {
StringReader command = new StringReader(msg.substring(this.prefix.length())); StringReader command = new StringReader(msg.substring(this.prefix.length()));
ParseResults<MessageCreateEvent> parseResults = this.dispatcher.parse(command, event); ParseResults<MessageReceivedEvent> parseResults = this.dispatcher.parse(command, event);
if (parseResults.getReader().canRead()) { if (parseResults.getReader().canRead()) {
// Parsing did not succeed, i.e. command not found // Parsing did not succeed, i.e. command not found
// TODO: add separate code path when insufficient permissions / requires fails // TODO: add separate code path when insufficient permissions / requires fails

View File

@ -7,11 +7,11 @@ import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import org.javacord.api.DiscordApi; import net.dv8tion.jda.api.JDA;
import org.javacord.api.entity.user.User; import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.requests.RestAction;
import java.util.Collection; import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -62,7 +62,7 @@ public class UserArgument implements ArgumentType<UserArgument.IUserProvider> {
} }
public interface IUserProvider { public interface IUserProvider {
CompletableFuture<User> getUsers(DiscordApi api); RestAction<User> getUsers(JDA api);
} }
static class NumericalProvider implements IUserProvider { static class NumericalProvider implements IUserProvider {
@ -73,8 +73,8 @@ public class UserArgument implements ArgumentType<UserArgument.IUserProvider> {
} }
@Override @Override
public CompletableFuture<User> getUsers(DiscordApi api) { public RestAction<User> getUsers(JDA api) {
return api.getUserById(snowflakeID); return api.retrieveUserById(snowflakeID);
} }
} }
} }

View File

@ -2,7 +2,7 @@ package sciwhiz12.janitor.commands.bot;
import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.context.CommandContext;
import org.javacord.api.event.message.MessageCreateEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import sciwhiz12.janitor.commands.BaseCommand; import sciwhiz12.janitor.commands.BaseCommand;
import sciwhiz12.janitor.commands.CommandRegistry; import sciwhiz12.janitor.commands.CommandRegistry;
import sciwhiz12.janitor.utils.Util; import sciwhiz12.janitor.utils.Util;
@ -19,23 +19,25 @@ public class ShutdownCommand extends BaseCommand {
} }
@Override @Override
public LiteralArgumentBuilder<MessageCreateEvent> getNode() { public LiteralArgumentBuilder<MessageReceivedEvent> getNode() {
return literal("shutdown") return literal("shutdown")
.requires(ctx -> ctx.getMessageAuthor().getId() == ownerID) .requires(ctx -> ctx.getAuthor().getIdLong() == ownerID)
.executes(this::run); .executes(this::run);
} }
int run(final CommandContext<MessageCreateEvent> ctx) { int run(final CommandContext<MessageReceivedEvent> ctx) {
ctx.getSource() ctx.getSource()
.getMessage() .getMessage()
.getChannel() .getChannel()
.sendMessage("Shutting down, in accordance with the owner's command. Goodbye all!") .sendMessage("Shutting down, in accordance with the owner's command. Goodbye all!")
.whenCompleteAsync(Util.handle( .submit()
success -> JANITOR.debug("Sent shutdown message to channel {}", Util.toString(ctx.getSource().getMessageAuthor())), .whenComplete(Util.handle(
err -> JANITOR.error("Error while sending ping message to bot owner {}", Util.toString(ctx.getSource().getMessageAuthor())) success -> JANITOR.debug("Sent shutdown message to channel {}", Util.toString(ctx.getSource().getAuthor())),
err -> JANITOR.error("Error while sending ping message to bot owner {}", Util.toString(ctx.getSource().getAuthor()))
) )
).join(); )
getBot().disconnect(); .join();
getBot().shutdown();
return 1; return 1;
} }
} }

View File

@ -2,7 +2,7 @@ package sciwhiz12.janitor.commands.misc;
import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.context.CommandContext;
import org.javacord.api.event.message.MessageCreateEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import sciwhiz12.janitor.commands.BaseCommand; import sciwhiz12.janitor.commands.BaseCommand;
import sciwhiz12.janitor.commands.CommandRegistry; import sciwhiz12.janitor.commands.CommandRegistry;
import sciwhiz12.janitor.commands.arguments.UserArgument; import sciwhiz12.janitor.commands.arguments.UserArgument;
@ -17,7 +17,7 @@ public class HelloCommand extends BaseCommand {
super(registry); super(registry);
} }
public LiteralArgumentBuilder<MessageCreateEvent> getNode() { public LiteralArgumentBuilder<MessageReceivedEvent> getNode() {
return literal("greet") return literal("greet")
.then( .then(
argument("user", UserArgument.user()) argument("user", UserArgument.user())
@ -25,18 +25,13 @@ public class HelloCommand extends BaseCommand {
); );
} }
int run(final CommandContext<MessageCreateEvent> ctx) { int run(final CommandContext<MessageReceivedEvent> ctx) {
UserArgument.getUser("user", ctx).getUsers(ctx.getSource().getApi()) UserArgument.getUser("user", ctx)
.thenCompose(user -> .getUsers(getBot().getDiscord())
ctx.getSource() .flatMap(user -> ctx.getSource().getChannel().sendMessage("Hello " + user.getAsMention() + "!"))
.getMessage() .queue(
.getChannel() success -> JANITOR.debug("Sent greeting message to {}", Util.toString(ctx.getSource().getAuthor())),
.sendMessage("Hello " + user.getMentionTag() + " !") err -> JANITOR.error("Error while sending greeting message to {}", Util.toString(ctx.getSource().getAuthor()))
)
.whenCompleteAsync(Util.handle(
success -> JANITOR.debug("Sent greeting message to {}", Util.toString(ctx.getSource().getMessageAuthor())),
err -> JANITOR.error("Error while sending greeting message to {}", Util.toString(ctx.getSource().getMessageAuthor()))
)
); );
return 1; return 1;
} }

View File

@ -2,7 +2,7 @@ package sciwhiz12.janitor.commands.misc;
import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.context.CommandContext;
import org.javacord.api.event.message.MessageCreateEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import sciwhiz12.janitor.commands.BaseCommand; import sciwhiz12.janitor.commands.BaseCommand;
import sciwhiz12.janitor.commands.CommandRegistry; import sciwhiz12.janitor.commands.CommandRegistry;
import sciwhiz12.janitor.utils.Util; import sciwhiz12.janitor.utils.Util;
@ -15,19 +15,18 @@ public class OKCommand extends BaseCommand {
super(registry); super(registry);
} }
public LiteralArgumentBuilder<MessageCreateEvent> getNode() { public LiteralArgumentBuilder<MessageReceivedEvent> getNode() {
return literal("ok") return literal("ok")
.executes(this::run); .executes(this::run);
} }
int run(final CommandContext<MessageCreateEvent> ctx) { int run(final CommandContext<MessageReceivedEvent> ctx) {
ctx.getSource() ctx.getSource()
.getMessage() .getMessage()
.addReaction("\uD83D\uDC4C") .addReaction("\uD83D\uDC4C")
.whenCompleteAsync(Util.handle( .queue(
success -> JANITOR.debug("Reacted :ok_hand: to {}'s message", Util.toString(ctx.getSource().getMessageAuthor())), success -> JANITOR.debug("Reacted :ok_hand: to {}'s message", Util.toString(ctx.getSource().getAuthor())),
err -> JANITOR.error("Error while reacting :ok_hand: to {}'s message", Util.toString(ctx.getSource().getMessageAuthor())) err -> JANITOR.error("Error while reacting :ok_hand: to {}'s message", Util.toString(ctx.getSource().getAuthor()))
)
); );
return 1; return 1;
} }

View File

@ -2,7 +2,7 @@ package sciwhiz12.janitor.commands.misc;
import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.context.CommandContext;
import org.javacord.api.event.message.MessageCreateEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import sciwhiz12.janitor.commands.BaseCommand; import sciwhiz12.janitor.commands.BaseCommand;
import sciwhiz12.janitor.commands.CommandRegistry; import sciwhiz12.janitor.commands.CommandRegistry;
import sciwhiz12.janitor.utils.Util; import sciwhiz12.janitor.utils.Util;
@ -20,20 +20,19 @@ public class PingCommand extends BaseCommand {
this.reply = reply; this.reply = reply;
} }
public LiteralArgumentBuilder<MessageCreateEvent> getNode() { public LiteralArgumentBuilder<MessageReceivedEvent> getNode() {
return literal(command) return literal(command)
.executes(this::run); .executes(this::run);
} }
int run(final CommandContext<MessageCreateEvent> ctx) { int run(final CommandContext<MessageReceivedEvent> ctx) {
ctx.getSource() ctx.getSource()
.getMessage() .getMessage()
.getChannel() .getChannel()
.sendMessage(reply) .sendMessage(reply)
.whenCompleteAsync(Util.handle( .queue(
success -> JANITOR.debug("Sent ping message to {}: {}", Util.toString(ctx.getSource().getMessageAuthor()), reply), success -> JANITOR.debug("Sent ping message to {}: {}", Util.toString(ctx.getSource().getAuthor()), reply),
err -> JANITOR.error("Error while sending ping message to {}", Util.toString(ctx.getSource().getMessageAuthor())) err -> JANITOR.error("Error while sending ping message to {}", Util.toString(ctx.getSource().getAuthor()))
)
); );
return 1; return 1;
} }

View File

@ -3,14 +3,14 @@ package sciwhiz12.janitor.utils;
import com.mojang.brigadier.arguments.ArgumentType; import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.builder.RequiredArgumentBuilder; import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import org.javacord.api.event.message.MessageCreateEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
public class CommandHelper { public class CommandHelper {
public static LiteralArgumentBuilder<MessageCreateEvent> literal(String command) { public static LiteralArgumentBuilder<MessageReceivedEvent> literal(String command) {
return LiteralArgumentBuilder.literal(command); return LiteralArgumentBuilder.literal(command);
} }
public static <Arg> RequiredArgumentBuilder<MessageCreateEvent, Arg> argument(String command, ArgumentType<Arg> argument) { public static <Arg> RequiredArgumentBuilder<MessageReceivedEvent, Arg> argument(String command, ArgumentType<Arg> argument) {
return RequiredArgumentBuilder.argument(command, argument); return RequiredArgumentBuilder.argument(command, argument);
} }
} }

View File

@ -1,12 +1,6 @@
package sciwhiz12.janitor.utils; package sciwhiz12.janitor.utils;
import org.javacord.api.entity.DiscordEntity; import net.dv8tion.jda.api.entities.*;
import org.javacord.api.entity.channel.Channel;
import org.javacord.api.entity.channel.ServerChannel;
import org.javacord.api.entity.message.MessageAuthor;
import org.javacord.api.entity.permission.Role;
import org.javacord.api.entity.server.Server;
import org.javacord.api.entity.user.User;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
@ -20,33 +14,34 @@ public class Util {
return obj; return obj;
} }
public static String toString(final MessageAuthor author) { // public static String toString(final MessageAuthor author) {
return author.asUser().map(Util::toString).orElseGet(() -> String.format("{MessageAuthor,%s}:%s", author.getDiscriminatedName(), author.getId())); // return author.asUser().map(Util::toString).orElseGet(() -> String.format("{MessageAuthor,%s}:%s", author.getDiscriminatedName(), author.getId()));
} // }
public static String toString(@Nullable final User user) { public static String toString(@Nullable final User user) {
return user != null ? String.format("{User,%s#%s}:%s", user.getName(), user.getDiscriminator(), getID(user)) : "unknown"; return user != null ? String.format("{User,%s#%s}:%s", user.getName(), user.getDiscriminator(), getID(user)) : "unknown";
} }
public static String toString(final Channel channel) { public static String toString(final MessageChannel channel) {
if (channel instanceof ServerChannel) { if (channel instanceof GuildChannel) {
ServerChannel gc = (ServerChannel) channel; GuildChannel gc = (GuildChannel) channel;
return String.format("[Channel:%s,%s@%s]%s", gc.getType(), gc.getName(), toString(gc.getServer()), getID(channel)); return String.format("[GuildChannel:%s,%s@%s]%s", gc.getType(), gc.getName(), toString(gc.getGuild()), getID(channel));
} }
return String.format("[Channel:%s]:%s", channel.getType(), getID(channel)); // TextChannel vs PrivateChannel
return String.format("[MessageChannel]:%s", getID(channel));
} }
public static String toString(final Server guild) { public static String toString(final Guild guild) {
return String.format("(Guild:%s):%s", guild.getName(), getID(guild)); return String.format("(Guild:%s):%s", guild.getName(), getID(guild));
} }
public static String getID(final DiscordEntity entity) { public static String getID(final ISnowflake entity) {
String prefix = "?"; String prefix = "?";
if (entity instanceof User) { if (entity instanceof User) {
prefix = "@&"; prefix = "@";
} else if (entity instanceof Role) { } else if (entity instanceof Role) {
prefix = "@!"; prefix = "@&";
} else if (entity instanceof Channel) { } else if (entity instanceof GuildChannel) {
prefix = "#"; prefix = "#";
} }
return String.format("<%s%s>", prefix, entity.getId()); return String.format("<%s%s>", prefix, entity.getId());