More converting

This commit is contained in:
Norbi Peti 2019-04-17 16:51:42 +02:00
parent d8d75c063b
commit 12ca6fbfb5
4 changed files with 93 additions and 75 deletions

View file

@ -4,12 +4,10 @@ import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.architecture.Component; import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.architecture.ConfigData; import buttondevteam.lib.architecture.ConfigData;
import buttondevteam.lib.architecture.IHaveConfig; import buttondevteam.lib.architecture.IHaveConfig;
import discord4j.core.object.entity.Channel; import discord4j.core.object.entity.*;
import discord4j.core.object.entity.Guild;
import discord4j.core.object.entity.Role;
import discord4j.core.object.util.Snowflake; import discord4j.core.object.util.Snowflake;
import discord4j.core.spec.EmbedCreateSpec;
import lombok.val; import lombok.val;
import sx.blah.discord.util.EmbedBuilder;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -17,8 +15,8 @@ import java.util.regex.Matcher;
public final class DPUtils { public final class DPUtils {
public static EmbedBuilder embedWithHead(EmbedBuilder builder, String playername) { public static EmbedCreateSpec embedWithHead(EmbedCreateSpec ecs, String playername, String profileUrl) {
return builder.withAuthorIcon("https://minotar.net/avatar/" + playername + "/32.png"); return ecs.setAuthor(playername, profileUrl, "https://minotar.net/avatar/" + playername + "/32.png");
} }
/** /**
@ -33,7 +31,7 @@ public final class DPUtils {
* Removes §[char] colour codes from strings * Removes §[char] colour codes from strings
*/ */
public static String sanitizeStringNoEscape(String string) { public static String sanitizeStringNoEscape(String string) {
String sanitizedString = ""; StringBuilder sanitizedString = new StringBuilder();
boolean random = false; boolean random = false;
for (int i = 0; i < string.length(); i++) { for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == '§') { if (string.charAt(i) == '§') {
@ -41,14 +39,14 @@ public final class DPUtils {
random = string.charAt(i) == 'k'; random = string.charAt(i) == 'k';
} else { } else {
if (!random) // Skip random/obfuscated characters if (!random) // Skip random/obfuscated characters
sanitizedString += string.charAt(i); sanitizedString.append(string.charAt(i));
} }
} }
return sanitizedString; return sanitizedString.toString();
} }
public static String escape(String message) { public static String escape(String message) {
return message.replaceAll("([*_~])", Matcher.quoteReplacement("\\")+"$1"); return message.replaceAll("([*_~])", Matcher.quoteReplacement("\\") + "$1");
} }
public static Logger getLogger() { public static Logger getLogger() {
@ -57,8 +55,14 @@ public final class DPUtils {
return DiscordPlugin.plugin.getLogger(); return DiscordPlugin.plugin.getLogger();
} }
public static ConfigData<Channel> channelData(IHaveConfig config, String key, long defID) { public static ConfigData<MessageChannel> channelData(IHaveConfig config, String key, long defID) {
return config.getDataPrimDef(key, defID, id -> DiscordPlugin.dc.getChannelById(Snowflake.of((long) id)).block(), ch -> ch.getId().asLong()); //We can afford to search for the channel in the cache once (instead of using mainServer) return config.getDataPrimDef(key, defID, id -> {
Channel ch = DiscordPlugin.dc.getChannelById(Snowflake.of((long) id)).block();
if (ch instanceof MessageChannel)
return (MessageChannel) ch;
else
return null;
}, ch -> ch.getId().asLong()); //We can afford to search for the channel in the cache once (instead of using mainServer)
} }
public static ConfigData<Role> roleData(IHaveConfig config, String key, String defName) { public static ConfigData<Role> roleData(IHaveConfig config, String key, String defName) {

View file

@ -111,7 +111,7 @@ public class DiscordPlugin extends ButtonPlugin {
private static volatile BukkitTask task; private static volatile BukkitTask task;
private static volatile boolean sent = false; private static volatile boolean sent = false;
public void handleReady(ReadyEvent event) { private void handleReady(ReadyEvent event) {
try { try {
dc.updatePresence(Presence.doNotDisturb(Activity.playing("booting"))).subscribe(); dc.updatePresence(Presence.doNotDisturb(Activity.playing("booting"))).subscribe();
val tries = new AtomicInteger(); val tries = new AtomicInteger();
@ -159,11 +159,11 @@ public class DiscordPlugin extends ButtonPlugin {
getManager().registerCommand(new DebugCommand()); getManager().registerCommand(new DebugCommand());
getManager().registerCommand(new ConnectCommand()); getManager().registerCommand(new ConnectCommand());
if (DiscordMCCommand.resetting) //These will only execute if the chat is enabled if (DiscordMCCommand.resetting) //These will only execute if the chat is enabled
ChromaBot.getInstance().sendMessageCustomAsWell("", new EmbedBuilder().withColor(Color.CYAN) ChromaBot.getInstance().sendMessageCustomAsWell(ch->ch.createEmbed(ecs->ecs.setColor(Color.CYAN)
.withTitle("Discord plugin restarted - chat connected.").build(), ChannelconBroadcast.RESTART); //Really important to note the chat, hmm .setTitle("Discord plugin restarted - chat connected.")), ChannelconBroadcast.RESTART); //Really important to note the chat, hmm
else if (getConfig().getBoolean("serverup", false)) { else if (getConfig().getBoolean("serverup", false)) {
ChromaBot.getInstance().sendMessageCustomAsWell("", new EmbedBuilder().withColor(Color.YELLOW) ChromaBot.getInstance().sendMessageCustomAsWell(ch->ch.createEmbed(ecs->ecs.setColor(Color.YELLOW)
.withTitle("Server recovered from a crash - chat connected.").build(), ChannelconBroadcast.RESTART); .setTitle("Server recovered from a crash - chat connected.")), ChannelconBroadcast.RESTART);
val thr = new Throwable( val thr = new Throwable(
"The server shut down unexpectedly. See the log of the previous run for more details."); "The server shut down unexpectedly. See the log of the previous run for more details.");
thr.setStackTrace(new StackTraceElement[0]); thr.setStackTrace(new StackTraceElement[0]);
@ -188,8 +188,7 @@ public class DiscordPlugin extends ButtonPlugin {
TBMCCoreAPI.SendUnsentDebugMessages(); TBMCCoreAPI.SendUnsentDebugMessages();
} }
}, 0, 10); }, 0, 10);
for (IListener<?> listener : CommonListeners.getListeners()) CommonListeners.register(dc.getEventDispatcher());
dc.getDispatcher().registerListener(listener);
TBMCCoreAPI.RegisterEventsForExceptions(new MCListener(), this); TBMCCoreAPI.RegisterEventsForExceptions(new MCListener(), this);
getCommand2MC().registerCommand(new DiscordMCCommand()); getCommand2MC().registerCommand(new DiscordMCCommand());
TBMCCoreAPI.RegisterUserClass(DiscordPlayer.class); TBMCCoreAPI.RegisterUserClass(DiscordPlayer.class);

View file

@ -7,6 +7,12 @@ import buttondevteam.discordplugin.mcchat.MinecraftChatModule;
import buttondevteam.discordplugin.role.GameRoleModule; import buttondevteam.discordplugin.role.GameRoleModule;
import buttondevteam.lib.TBMCCoreAPI; import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.architecture.Component; import buttondevteam.lib.architecture.Component;
import discord4j.core.event.EventDispatcher;
import discord4j.core.event.domain.PresenceUpdateEvent;
import discord4j.core.event.domain.message.MessageCreateEvent;
import discord4j.core.event.domain.role.RoleCreateEvent;
import discord4j.core.event.domain.role.RoleDeleteEvent;
import discord4j.core.event.domain.role.RoleUpdateEvent;
import lombok.val; import lombok.val;
import sx.blah.discord.api.events.IListener; import sx.blah.discord.api.events.IListener;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent; import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
@ -26,10 +32,8 @@ public class CommonListeners {
- Minecraft chat (is enabled in the channel and message isn't [/]mcchat) - Minecraft chat (is enabled in the channel and message isn't [/]mcchat)
- CommandListener (with the correct prefix in #bot, or in private) - CommandListener (with the correct prefix in #bot, or in private)
*/ */
public static IListener<?>[] getListeners() { public static void register(EventDispatcher dispatcher) {
return new IListener[]{new IListener<MessageReceivedEvent>() { dispatcher.on(MessageCreateEvent.class).subscribe(event->{
@Override
public void handle(MessageReceivedEvent event) {
if (DiscordPlugin.SafeMode) if (DiscordPlugin.SafeMode)
return; return;
if (event.getMessage().getAuthor().isBot()) if (event.getMessage().getAuthor().isBot())
@ -39,8 +43,8 @@ public class CommonListeners {
try { try {
boolean handled = false; boolean handled = false;
val commandChannel = DiscordPlugin.plugin.CommandChannel().get(); val commandChannel = DiscordPlugin.plugin.CommandChannel().get();
if ((commandChannel != null && event.getChannel().getLongID() == commandChannel.getLongID()) //If mentioned, that's higher than chat if ((commandChannel != null && event.getMessage().getChannelId().asLong() == commandChannel.getId().asLong()) //If mentioned, that's higher than chat
|| event.getMessage().getContent().contains("channelcon")) //Only 'channelcon' is allowed in other channels || event.getMessage().getContent().orElse("").contains("channelcon")) //Only 'channelcon' is allowed in other channels
handled = CommandListener.runCommand(event.getMessage(), true); //#bot is handled here handled = CommandListener.runCommand(event.getMessage(), true); //#bot is handled here
if (handled) return; if (handled) return;
val mcchat = Component.getComponents().get(MinecraftChatModule.class); val mcchat = Component.getComponents().get(MinecraftChatModule.class);
@ -51,17 +55,15 @@ public class CommonListeners {
} catch (Exception e) { } catch (Exception e) {
TBMCCoreAPI.SendException("An error occured while handling a message!", e); TBMCCoreAPI.SendException("An error occured while handling a message!", e);
} }
} });
}, new IListener<sx.blah.discord.handle.impl.events.user.PresenceUpdateEvent>() { dispatcher.on(PresenceUpdateEvent.class).subscribe(event->{
@Override
public void handle(PresenceUpdateEvent event) {
if (DiscordPlugin.SafeMode) if (DiscordPlugin.SafeMode)
return; return;
FunModule.handleFullHouse(event); FunModule.handleFullHouse(event);
} });
}, (IListener<RoleCreateEvent>) GameRoleModule::handleRoleEvent, // dispatcher.on(RoleCreateEvent.class).subscribe(GameRoleModule::handleRoleEvent);
(IListener<RoleDeleteEvent>) GameRoleModule::handleRoleEvent, // dispatcher.on(RoleDeleteEvent.class).subscribe(GameRoleModule::handleRoleEvent);
(IListener<RoleUpdateEvent>) GameRoleModule::handleRoleEvent}; dispatcher.on(RoleUpdateEvent.class).subscribe(GameRoleModule::handleRoleEvent);
} }
private static boolean debug = false; private static boolean debug = false;

View file

@ -5,6 +5,12 @@ import buttondevteam.discordplugin.DPUtils;
import buttondevteam.discordplugin.DiscordPlugin; import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.lib.architecture.Component; import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.architecture.ConfigData; import buttondevteam.lib.architecture.ConfigData;
import discord4j.core.event.domain.role.RoleCreateEvent;
import discord4j.core.event.domain.role.RoleDeleteEvent;
import discord4j.core.event.domain.role.RoleEvent;
import discord4j.core.event.domain.role.RoleUpdateEvent;
import discord4j.core.object.entity.MessageChannel;
import discord4j.core.object.entity.Role;
import lombok.val; import lombok.val;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import sx.blah.discord.handle.impl.events.guild.role.RoleCreateEvent; import sx.blah.discord.handle.impl.events.guild.role.RoleCreateEvent;
@ -24,7 +30,7 @@ public class GameRoleModule extends Component<DiscordPlugin> {
@Override @Override
protected void enable() { protected void enable() {
getPlugin().getManager().registerCommand(new RoleCommand(this)); getPlugin().getManager().registerCommand(new RoleCommand(this));
GameRoles = DiscordPlugin.mainServer.getRoles().stream().filter(this::isGameRole).map(IRole::getName).collect(Collectors.toList()); GameRoles = DiscordPlugin.mainServer.getRoles().filter(this::isGameRole).map(Role::getName).collect(Collectors.toList()).block();
} }
@Override @Override
@ -32,7 +38,7 @@ public class GameRoleModule extends Component<DiscordPlugin> {
} }
private ConfigData<IChannel> logChannel() { private ConfigData<MessageChannel> logChannel() {
return DPUtils.channelData(getConfig(), "logChannel", 239519012529111040L); return DPUtils.channelData(getConfig(), "logChannel", 239519012529111040L);
} }
@ -43,41 +49,48 @@ public class GameRoleModule extends Component<DiscordPlugin> {
val logChannel = grm.logChannel().get(); val logChannel = grm.logChannel().get();
if (roleEvent instanceof RoleCreateEvent) { if (roleEvent instanceof RoleCreateEvent) {
Bukkit.getScheduler().runTaskLaterAsynchronously(DiscordPlugin.plugin, () -> { Bukkit.getScheduler().runTaskLaterAsynchronously(DiscordPlugin.plugin, () -> {
if (roleEvent.getRole().isDeleted() || !grm.isGameRole(roleEvent.getRole())) Role role=((RoleCreateEvent) roleEvent).getRole();
if (!grm.isGameRole(role))
return; //Deleted or not a game role return; //Deleted or not a game role
GameRoles.add(roleEvent.getRole().getName()); GameRoles.add(role.getName());
if (logChannel != null) if (logChannel != null)
DiscordPlugin.sendMessageToChannel(logChannel, "Added " + roleEvent.getRole().getName() + " as game role. If you don't want this, change the role's color from the default."); logChannel.createMessage("Added " + role.getName() + " as game role. If you don't want this, change the role's color from the default.").subscribe();
}, 100); }, 100);
} else if (roleEvent instanceof RoleDeleteEvent) { } else if (roleEvent instanceof RoleDeleteEvent) {
if (GameRoles.remove(roleEvent.getRole().getName()) && logChannel != null) Role role=((RoleDeleteEvent) roleEvent).getRole().orElse(null);
DiscordPlugin.sendMessageToChannel(logChannel, "Removed " + roleEvent.getRole().getName() + " as a game role."); if(role==null) return;
if (GameRoles.remove(role.getName()) && logChannel != null)
logChannel, "Removed " + role.getName() + " as a game role.");
} else if (roleEvent instanceof RoleUpdateEvent) { } else if (roleEvent instanceof RoleUpdateEvent) {
val event = (RoleUpdateEvent) roleEvent; val event = (RoleUpdateEvent) roleEvent;
if (!grm.isGameRole(event.getNewRole())) { if(!event.getOld().isPresent()) {
if (GameRoles.remove(event.getOldRole().getName()) && logChannel != null) DPUtils.getLogger().warning("Old role not stored, cannot update game role!");
DiscordPlugin.sendMessageToChannel(logChannel, "Removed " + event.getOldRole().getName() + " as a game role because it's color changed.");
} else {
if (GameRoles.contains(event.getOldRole().getName()) && event.getOldRole().getName().equals(event.getNewRole().getName()))
return; return;
boolean removed = GameRoles.remove(event.getOldRole().getName()); //Regardless of whether it was a game role }
GameRoles.add(event.getNewRole().getName()); //Add it because it has no color Role or=event.getOld().get();
if (!grm.isGameRole(event.getCurrent())) {
if (GameRoles.remove(or.getName()) && logChannel != null)
logChannel.createMessage("Removed " + or.getName() + " as a game role because it's color changed.").subscribe();
} else {
if (GameRoles.contains(or.getName()) && or.getName().equals(event.getCurrent().getName()))
return;
boolean removed = GameRoles.remove(or.getName()); //Regardless of whether it was a game role
GameRoles.add(event.getCurrent().getName()); //Add it because it has no color
if (logChannel != null) { if (logChannel != null) {
if (removed) if (removed)
DiscordPlugin.sendMessageToChannel(logChannel, "Changed game role from " + event.getOldRole().getName() + " to " + event.getNewRole().getName() + "."); logChannel.createMessage("Changed game role from " + or.getName() + " to " + event.getCurrent().getName() + ".").subscribe();
else else
DiscordPlugin.sendMessageToChannel(logChannel, "Added " + event.getNewRole().getName() + " as game role because it has the default color."); logChannel.createMessage("Added " + event.getCurrent().getName() + " as game role because it has the default color.").subscribe();
} }
} }
} }
} }
private boolean isGameRole(IRole r) { private boolean isGameRole(Role r) {
if (r.getGuild().getLongID() != DiscordPlugin.mainServer.getLongID()) if (r.getGuildId().asLong() != DiscordPlugin.mainServer.getId().asLong())
return false; //Only allow on the main server return false; //Only allow on the main server
val rc = new Color(149, 165, 166, 0); val rc = new Color(149, 165, 166, 0);
return r.getColor().equals(rc) return r.getColor().equals(rc)
&& DiscordPlugin.dc.getOurUser().getRolesForGuild(DiscordPlugin.mainServer) && DiscordPlugin.dc.getSelf().block().asMember(DiscordPlugin.mainServer.getId()).block().hasHigherRoles(r); //Below one of our roles
.stream().anyMatch(or -> r.getPosition() < or.getPosition()); //Below one of our roles
} }
} }