Toggles work! Other changes

#75
- Changed shutdown kick message
- Added timeout for resetting as well
- Last message handling fixed (#71)
- Some restructuring related to mcchat
This commit is contained in:
Norbi Peti 2018-10-24 00:07:07 +02:00
parent 18fdbc5770
commit 9e827d14d0
No known key found for this signature in database
GPG key ID: DBA4C4549A927E56
7 changed files with 124 additions and 108 deletions

View file

@ -9,6 +9,7 @@ import sx.blah.discord.api.internal.json.objects.EmbedObject;
import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.util.EmbedBuilder; import sx.blah.discord.util.EmbedBuilder;
import javax.annotation.Nullable;
import java.awt.*; import java.awt.*;
import java.util.Arrays; import java.util.Arrays;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -62,9 +63,10 @@ public class ChromaBot {
* *
* @param message The message to send, duh * @param message The message to send, duh
* @param embed Custom fancy stuff, use {@link EmbedBuilder} to create one * @param embed Custom fancy stuff, use {@link EmbedBuilder} to create one
* @param toggle The toggle type for channelcon
*/ */
public void sendMessageCustomAsWell(String message, EmbedObject embed) { public void sendMessageCustomAsWell(String message, EmbedObject embed, @Nullable ChannelconBroadcast toggle) {
MCChatListener.forCustomAndAllMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, message, embed)); MCChatListener.forCustomAndAllMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, message, embed), toggle, false);
} }
/** /**

View file

@ -153,26 +153,27 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
val user = dc.fetchUser(did); val user = dc.fetchUser(did);
val dcp = new DiscordConnectedPlayer(user, ch, UUID.fromString(chcon.getString("mcuid")), chcon.getString("mcname")); val dcp = new DiscordConnectedPlayer(user, ch, UUID.fromString(chcon.getString("mcuid")), chcon.getString("mcname"));
val groupid = chcon.getString("groupid"); val groupid = chcon.getString("groupid");
val toggles = chcon.getInt("toggles");
if (!mcch.isPresent() || ch == null || user == null || groupid == null) if (!mcch.isPresent() || ch == null || user == null || groupid == null)
continue; continue;
MCChatListener.addCustomChat(ch, groupid, mcch.get(), dp, user, dcp); MCChatListener.addCustomChat(ch, groupid, mcch.get(), user, dcp, toggles);
} }
} }
DiscordCommandBase.registerCommands(); DiscordCommandBase.registerCommands();
if (ResetMCCommand.resetting) if (ResetMCCommand.resetting)
ChromaBot.getInstance().sendMessageCustomAsWell("", new EmbedBuilder().withColor(Color.CYAN) ChromaBot.getInstance().sendMessageCustomAsWell("", new EmbedBuilder().withColor(Color.CYAN)
.withTitle("Discord plugin restarted - chat connected.").build()); //Really important to note the chat, hmm .withTitle("Discord plugin restarted - chat connected.").build(), 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("", new EmbedBuilder().withColor(Color.YELLOW)
.withTitle("Server recovered from a crash - chat connected.").build()); .withTitle("Server recovered from a crash - chat connected.").build(), 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]);
TBMCCoreAPI.SendException("The server crashed!", thr); TBMCCoreAPI.SendException("The server crashed!", thr);
} else } else
ChromaBot.getInstance().sendMessageCustomAsWell("", new EmbedBuilder().withColor(Color.GREEN) ChromaBot.getInstance().sendMessageCustomAsWell("", new EmbedBuilder().withColor(Color.GREEN)
.withTitle("Server started - chat connected.").build()); .withTitle("Server started - chat connected.").build(), ChannelconBroadcast.RESTART);
ResetMCCommand.resetting = false; //This is the last event handling this flag ResetMCCommand.resetting = false; //This is the last event handling this flag
@ -261,31 +262,33 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
chconc.set("mcuid", chcon.dcp.getUniqueId().toString()); chconc.set("mcuid", chcon.dcp.getUniqueId().toString());
chconc.set("mcname", chcon.dcp.getName()); chconc.set("mcname", chcon.dcp.getName());
chconc.set("groupid", chcon.groupID); chconc.set("groupid", chcon.groupID);
chconc.set("toggles", chcon.toggles);
} }
saveConfig(); saveConfig();
EmbedObject embed;
if (ResetMCCommand.resetting)
embed = new EmbedBuilder().withColor(Color.ORANGE).withTitle("Discord plugin restarting").build();
else
embed = new EmbedBuilder().withColor(Restart ? Color.ORANGE : Color.RED)
.withTitle(Restart ? "Server restarting" : "Server stopping")
.withDescription(
Bukkit.getOnlinePlayers().size() > 0
? (DPUtils
.sanitizeString(Bukkit.getOnlinePlayers().stream()
.map(Player::getDisplayName).collect(Collectors.joining(", ")))
+ (Bukkit.getOnlinePlayers().size() == 1 ? " was " : " were ")
+ "kicked the hell out.") //TODO: Make configurable
: "") //If 'restart' is disabled then this isn't shown even if joinleave is enabled
.build();
MCChatListener.forCustomAndAllMCChat(ch -> { MCChatListener.forCustomAndAllMCChat(ch -> {
try { try {
if (ResetMCCommand.resetting)
DiscordPlugin.sendMessageToChannelWait(ch, "", DiscordPlugin.sendMessageToChannelWait(ch, "",
new EmbedBuilder().withColor(Color.ORANGE).withTitle("Discord plugin restarting").build()); embed, 5, TimeUnit.SECONDS);
else
DiscordPlugin.sendMessageToChannelWait(ch, "",
new EmbedBuilder().withColor(Restart ? Color.ORANGE : Color.RED)
.withTitle(Restart ? "Server restarting" : "Server stopping")
.withDescription(
Bukkit.getOnlinePlayers().size() > 0
? (DPUtils
.sanitizeString(Bukkit.getOnlinePlayers().stream()
.map(Player::getDisplayName).collect(Collectors.joining(", ")))
+ (Bukkit.getOnlinePlayers().size() == 1 ? " was " : " were ")
+ "asked *politely* to leave the server for a bit.")
: "")
.build(), 5, TimeUnit.SECONDS);
} catch (TimeoutException | InterruptedException e) { } catch (TimeoutException | InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
}); }, ChannelconBroadcast.RESTART, false);
ChromaBot.getInstance().updatePlayerList(); ChromaBot.getInstance().updatePlayerList();
try { try {
SafeMode = true; // Stop interacting with Discord SafeMode = true; // Stop interacting with Discord
@ -415,10 +418,7 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
.warning("Message was too long to send to discord and got truncated. In " + channel.getName()); .warning("Message was too long to send to discord and got truncated. In " + channel.getName());
} }
try { try {
if (channel == chatchannel) MCChatListener.resetLastMessage(channel); // If this is a chat message, it'll be set again
MCChatListener.resetLastMessage(); // If this is a chat message, it'll be set again
else if (channel.isPrivate())
MCChatListener.resetLastMessage(channel);
final String content = message; final String content = message;
RequestBuffer.IRequest<IMessage> r = () -> embed == null ? channel.sendMessage(content) RequestBuffer.IRequest<IMessage> r = () -> embed == null ? channel.sendMessage(content)
: channel.sendMessage(content, embed, false); : channel.sendMessage(content, embed, false);

View file

@ -30,7 +30,7 @@ public class PlayerListWatcher extends DedicatedPlayerList {
if (packet instanceof PacketPlayOutChat) { if (packet instanceof PacketPlayOutChat) {
Field msgf = PacketPlayOutChat.class.getDeclaredField("a"); Field msgf = PacketPlayOutChat.class.getDeclaredField("a");
msgf.setAccessible(true); msgf.setAccessible(true);
MCChatListener.sendSystemMessageToChat(((IChatBaseComponent) msgf.get(packet)).toPlainText()); MCChatListener.forAllMCChat(MCChatListener.send(((IChatBaseComponent) msgf.get(packet)).toPlainText()));
} }
} catch (Exception e) { } catch (Exception e) {
TBMCCoreAPI.SendException("Failed to broadcast message sent to all players - hacking failed.", e); TBMCCoreAPI.SendException("Failed to broadcast message sent to all players - hacking failed.", e);

View file

@ -40,20 +40,19 @@ public class ChannelconCommand extends DiscordCommandBase {
return true; return true;
} }
if (args.toLowerCase().startsWith("toggle")) { if (args.toLowerCase().startsWith("toggle")) {
Supplier<String> togglesString = () -> Arrays.stream(ChannelconBroadcast.values()).map(t -> t.toString().toLowerCase()).collect(Collectors.joining(", ")); val cc = MCChatListener.getCustomChat(message.getChannel());
Supplier<String> togglesString = () -> Arrays.stream(ChannelconBroadcast.values()).map(t -> t.toString().toLowerCase() + ": " + ((cc.toggles & t.flag) == 0 ? "disabled" : "enabled")).collect(Collectors.joining("\n"));
String[] argsa = args.split(" "); String[] argsa = args.split(" ");
if (argsa.length < 2) { if (argsa.length < 2) {
message.reply("Toggles: " + togglesString.get()); message.reply("toggles:\n" + togglesString.get());
return true; return true;
} }
String arg = argsa[1].toUpperCase(); String arg = argsa[1].toUpperCase();
val b = Arrays.stream(ChannelconBroadcast.values()).filter(t -> t.toString().equals(arg)).findAny(); val b = Arrays.stream(ChannelconBroadcast.values()).filter(t -> t.toString().equals(arg)).findAny();
if (!b.isPresent()) { if (!b.isPresent()) {
message.reply("Cannot find toggle. Toggles: " + togglesString.get()); message.reply("cannot find toggle. Toggles:\n" + togglesString.get());
return true; return true;
} }
//TODO: Toggle that toggle
val cc = MCChatListener.getCustomChat(message.getChannel());
//A B | F //A B | F
//------- A: original - B: mask - F: new //------- A: original - B: mask - F: new
//0 0 | 0 //0 0 | 0
@ -91,7 +90,7 @@ public class ChannelconCommand extends DiscordCommandBase {
message.reply("sorry, this MC chat is already connected to a different channel, multiple channels are not supported atm."); message.reply("sorry, this MC chat is already connected to a different channel, multiple channels are not supported atm.");
return true; return true;
} }
MCChatListener.addCustomChat(message.getChannel(), groupid, ev.getChannel(), dp, message.getAuthor(), dcp); MCChatListener.addCustomChat(message.getChannel(), groupid, ev.getChannel(), message.getAuthor(), dcp, 0);
message.reply("alright, connection made to group `" + groupid + "`!"); message.reply("alright, connection made to group `" + groupid + "`!");
return true; return true;
} }

View file

@ -128,11 +128,11 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
if ((e.getChannel() == Channel.GlobalChat || e.getChannel().ID.equals("rp")) if ((e.getChannel() == Channel.GlobalChat || e.getChannel().ID.equals("rp"))
&& (e.isFromcmd() || isdifferentchannel.test(DiscordPlugin.chatchannel))) && (e.isFromcmd() || isdifferentchannel.test(DiscordPlugin.chatchannel)))
doit.accept(lastmsgdata == null doit.accept(lastmsgdata == null
? lastmsgdata = new LastMsgData(DiscordPlugin.chatchannel, null, null) ? lastmsgdata = new LastMsgData(DiscordPlugin.chatchannel, null)
: lastmsgdata); : lastmsgdata);
for (LastMsgData data : lastmsgPerUser) { for (LastMsgData data : lastmsgPerUser) {
if (data.dp.isMinecraftChatEnabled() && (e.isFromcmd() || isdifferentchannel.test(data.channel)) if ((e.isFromcmd() || isdifferentchannel.test(data.channel))
&& e.shouldSendTo(getSender(data.channel, data.user))) && e.shouldSendTo(getSender(data.channel, data.user)))
doit.accept(data); doit.accept(data);
} }
@ -167,7 +167,6 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
public final IChannel channel; public final IChannel channel;
public Channel mcchannel; public Channel mcchannel;
public final IUser user; public final IUser user;
public final DiscordPlayer dp;
} }
public static class CustomLMD extends LastMsgData { public static class CustomLMD extends LastMsgData {
@ -176,12 +175,13 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
public final DiscordConnectedPlayer dcp; public final DiscordConnectedPlayer dcp;
public int toggles; public int toggles;
public CustomLMD(@NonNull IChannel channel, @NonNull IUser user, @NonNull DiscordPlayer dp, private CustomLMD(@NonNull IChannel channel, @NonNull IUser user,
@NonNull String groupid, @NonNull Channel mcchannel, @NonNull DiscordConnectedPlayer dcp) { @NonNull String groupid, @NonNull Channel mcchannel, @NonNull DiscordConnectedPlayer dcp, int toggles) {
super(channel, user, dp); super(channel, user);
groupID = groupid; groupID = groupid;
this.mcchannel = mcchannel; this.mcchannel = mcchannel;
this.dcp = dcp; this.dcp = dcp;
this.toggles = toggles;
} }
} }
@ -240,7 +240,7 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
if (!start) if (!start)
lastmsgfromd.remove(channel.getLongID()); lastmsgfromd.remove(channel.getLongID());
return start // return start //
? lastmsgPerUser.add(new LastMsgData(channel, user, dp)) // Doesn't support group DMs ? lastmsgPerUser.add(new LastMsgData(channel, user)) // Doesn't support group DMs
: lastmsgPerUser.removeIf(lmd -> lmd.channel.getLongID() == channel.getLongID()); : lastmsgPerUser.removeIf(lmd -> lmd.channel.getLongID() == channel.getLongID());
} }
@ -295,8 +295,8 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
.anyMatch(lmd -> ((IPrivateChannel) lmd.channel).getRecipient().getStringID().equals(did)); .anyMatch(lmd -> ((IPrivateChannel) lmd.channel).getRecipient().getStringID().equals(did));
} }
public static void addCustomChat(IChannel channel, String groupid, Channel mcchannel, DiscordPlayer dp, IUser user, DiscordConnectedPlayer dcp) { public static void addCustomChat(IChannel channel, String groupid, Channel mcchannel, IUser user, DiscordConnectedPlayer dcp, int toggles) {
val lmd = new CustomLMD(channel, user, dp, groupid, mcchannel, dcp); val lmd = new CustomLMD(channel, user, groupid, mcchannel, dcp, toggles);
lastmsgCustom.add(lmd); lastmsgCustom.add(lmd);
} }
@ -328,33 +328,25 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
public static final HashMap<String, HashMap<IChannel, DiscordPlayerSender>> OnlineSenders = new HashMap<>(); public static final HashMap<String, HashMap<IChannel, DiscordPlayerSender>> OnlineSenders = new HashMap<>();
public static short ListC = 0; public static short ListC = 0;
public static void resetLastMessage() {
(lastmsgdata == null ? lastmsgdata = new LastMsgData(DiscordPlugin.chatchannel, null, null)
: lastmsgdata).message = null;
} // Don't set the whole object to null, the player and channel information should be preserved
public static void resetLastMessage(IChannel channel) {
for (LastMsgData data : lastmsgPerUser)
if (data.channel.getLongID() == channel.getLongID())
data.message = null; // Since only private channels are stored, only those will work anyways
}
public static void resetLastMessageCustom(IChannel channel) {
for (LastMsgData data : lastmsgCustom)
if (data.channel.getLongID() == channel.getLongID())
data.message = null;
}
/** /**
* This overload sends it to the global chat. * Resets the last message, so it will start a new one instead of appending to it.
* This is used when someone (even the bot) sends a message to the channel.
*
* @param channel The channel to reset in - the process is slightly different for the public, private and custom chats
*/ */
public static void sendSystemMessageToChat(String msg) { public static void resetLastMessage(IChannel channel) {
forAllMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, DPUtils.sanitizeString(msg))); if (channel.getLongID() == DiscordPlugin.chatchannel.getLongID()) {
} (lastmsgdata == null ? lastmsgdata = new LastMsgData(DiscordPlugin.chatchannel, null)
: lastmsgdata).message = null;
public static void sendSystemMessageToChat(TBMCSystemChatEvent event) { return;
forAllowedMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, DPUtils.sanitizeString(event.getMessage())), } // Don't set the whole object to null, the player and channel information should be preserved
event); for (LastMsgData data : channel.isPrivate() ? lastmsgPerUser : lastmsgCustom) {
if (data.channel.getLongID() == channel.getLongID()) {
data.message = null;
return;
}
}
//If it gets here, it's sending a message to a non-chat channel
} }
public static void forAllMCChat(Consumer<IChannel> action) { public static void forAllMCChat(Consumer<IChannel> action) {
@ -364,30 +356,67 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
// lastmsgCustom.forEach(cc -> action.accept(cc.channel)); - Only send relevant messages to custom chat // lastmsgCustom.forEach(cc -> action.accept(cc.channel)); - Only send relevant messages to custom chat
} }
public static void forCustomAndAllMCChat(Consumer<IChannel> action) { /**
forAllMCChat(action); * For custom and all MC chat
lastmsgCustom.forEach(cc -> action.accept(cc.channel)); *
* @param action The action to act
* @param toggle The toggle to check
* @param hookmsg Whether the message is also sent from the hook
*/
public static void forCustomAndAllMCChat(Consumer<IChannel> action, @Nullable ChannelconBroadcast toggle, boolean hookmsg) {
if (!DiscordPlugin.hooked || !hookmsg)
forAllMCChat(action);
final Consumer<CustomLMD> customLMDConsumer = cc -> action.accept(cc.channel);
if (toggle == null)
lastmsgCustom.forEach(customLMDConsumer);
else
lastmsgCustom.stream().filter(cc -> (cc.toggles & toggle.flag) != 0).forEach(customLMDConsumer);
} }
/** /**
* Do the {@code action} for each custom chat the {@code sender} have access to and has that broadcast type enabled. * Do the {@code action} for each custom chat the {@code sender} have access to and has that broadcast type enabled.
* *
* @param action The action to do * @param action The action to do
* @param sender The sender to check perms of or null to send to all that has it toggled * @param sender The sender to check perms of or null to send to all that has it toggled
* @param toggle The toggle to check or null to send to all allowed * @param toggle The toggle to check or null to send to all allowed
*/ */
public static void forAllowedCustomMCChat(Consumer<IChannel> action, @Nullable CommandSender sender, @Nullable ChannelconBroadcast toggle) { public static void forAllowedCustomMCChat(Consumer<IChannel> action, @Nullable CommandSender sender, @Nullable ChannelconBroadcast toggle) {
lastmsgCustom.stream().filter(clmd -> { lastmsgCustom.stream().filter(clmd -> {
//new TBMCChannelConnectFakeEvent(sender, clmd.mcchannel).shouldSendTo(clmd.dcp) - Thought it was this simple hehe - Wait, it *should* be this simple //new TBMCChannelConnectFakeEvent(sender, clmd.mcchannel).shouldSendTo(clmd.dcp) - Thought it was this simple hehe - Wait, it *should* be this simple
if (toggle != null && (clmd.toggles & toggle.flag) == 0) if (toggle != null && (clmd.toggles & toggle.flag) == 0)
return false; //If null then allow return false; //If null then allow
if (sender == null) if (sender == null)
return true; return true;
val e = new TBMCChannelConnectFakeEvent(sender, clmd.mcchannel); val e = new TBMCChannelConnectFakeEvent(sender, clmd.mcchannel);
return clmd.groupID.equals(e.getGroupID(sender)); return clmd.groupID.equals(e.getGroupID(sender));
}).forEach(cc -> action.accept(cc.channel)); //TODO: Use getScore and getGroupID in fake event constructor - This should also send error messages on channel connect }).forEach(cc -> action.accept(cc.channel)); //TODO: Use getScore and getGroupID in fake event constructor - This should also send error messages on channel connect
} }
/**
* Do the {@code action} for each custom chat the {@code sender} have access to and has that broadcast type enabled.
*
* @param action The action to do
* @param sender The sender to check perms of or null to send to all that has it toggled
* @param toggle The toggle to check or null to send to all allowed
* @param hookmsg Whether the message is also sent from the hook
*/
public static void forAllowedCustomAndAllMCChat(Consumer<IChannel> action, @Nullable CommandSender sender, @Nullable ChannelconBroadcast toggle, boolean hookmsg) {
if (!DiscordPlugin.hooked || !hookmsg)
forAllMCChat(action);
lastmsgCustom.stream().filter(clmd -> {
if (toggle != null && (clmd.toggles & toggle.flag) == 0)
return false; //If null then allow
if (sender == null)
return true;
val e = new TBMCChannelConnectFakeEvent(sender, clmd.mcchannel);
return clmd.groupID.equals(e.getGroupID(sender));
}).forEach(cc -> action.accept(cc.channel)); //TODO: Use getScore and getGroupID in fake event constructor - This should also send error messages on channel connect
}
public static Consumer<IChannel> send(String message) {
return ch -> DiscordPlugin.sendMessageToChannel(ch, DPUtils.sanitizeString(message));
}
private static void forAllowedMCChat(Consumer<IChannel> action, TBMCSystemChatEvent event) { private static void forAllowedMCChat(Consumer<IChannel> action, TBMCSystemChatEvent event) {
if (Channel.GlobalChat.ID.equals(event.getChannel().ID)) if (Channel.GlobalChat.ID.equals(event.getChannel().ID))
action.accept(DiscordPlugin.chatchannel); action.accept(DiscordPlugin.chatchannel);
@ -451,12 +480,7 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
return; // Race condition: If it gets here after it enabled mcchat it says it - I might as well allow disabling with this (CommandListener) return; // Race condition: If it gets here after it enabled mcchat it says it - I might as well allow disabling with this (CommandListener)
if (CommandListener.runCommand(ev.getMessage(), true)) if (CommandListener.runCommand(ev.getMessage(), true))
return; return;
if (!ev.getMessage().getChannel().isPrivate()) resetLastMessage(ev.getChannel());
resetLastMessage();
else if (hasCustomChat)
resetLastMessageCustom(ev.getChannel());
else
resetLastMessage(ev.getMessage().getChannel());
lastlist++; lastlist++;
recevents.add(ev); recevents.add(ev);
if (rectask != null) if (rectask != null)

View file

@ -63,9 +63,7 @@ public class MCListener implements Listener {
p.sendMessage("§bIf it wasn't you, do /discord decline"); p.sendMessage("§bIf it wasn't you, do /discord decline");
} }
final String message = e.GetPlayer().PlayerName().get() + " joined the game"; final String message = e.GetPlayer().PlayerName().get() + " joined the game";
if (!DiscordPlugin.hooked) MCChatListener.forAllowedCustomAndAllMCChat(MCChatListener.send(message), e.getPlayer(), ChannelconBroadcast.JOINLEAVE, true);
MCChatListener.sendSystemMessageToChat(message);
MCChatListener.forAllowedCustomMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, message), e.getPlayer(), ChannelconBroadcast.JOINLEAVE);
//System.out.println("Does this appear more than once?"); //No //System.out.println("Does this appear more than once?"); //No
MCChatListener.ListC = 0; MCChatListener.ListC = 0;
ChromaBot.getInstance().updatePlayerList(); ChromaBot.getInstance().updatePlayerList();
@ -85,16 +83,14 @@ public class MCListener implements Listener {
Bukkit.getScheduler().runTaskLaterAsynchronously(DiscordPlugin.plugin, Bukkit.getScheduler().runTaskLaterAsynchronously(DiscordPlugin.plugin,
ChromaBot.getInstance()::updatePlayerList, 5); ChromaBot.getInstance()::updatePlayerList, 5);
final String message = e.GetPlayer().PlayerName().get() + " left the game"; final String message = e.GetPlayer().PlayerName().get() + " left the game";
if (!DiscordPlugin.hooked) MCChatListener.forAllowedCustomAndAllMCChat(MCChatListener.send(message), e.getPlayer(), ChannelconBroadcast.JOINLEAVE, true);
MCChatListener.sendSystemMessageToChat(message); //TODO: Probably double sends if kicked and unhooked
MCChatListener.forAllowedCustomMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, message), e.getPlayer(), ChannelconBroadcast.JOINLEAVE);
} }
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerKick(PlayerKickEvent e) { public void onPlayerKick(PlayerKickEvent e) {
if (!DiscordPlugin.hooked && !e.getReason().equals("The server is restarting") /*if (!DiscordPlugin.hooked && !e.getReason().equals("The server is restarting")
&& !e.getReason().equals("Server closed")) // The leave messages errored with the previous setup, I could make it wait since I moved it here, but instead I have a special && !e.getReason().equals("Server closed")) // The leave messages errored with the previous setup, I could make it wait since I moved it here, but instead I have a special
MCChatListener.sendSystemMessageToChat(e.getPlayer().getName() + " left the game"); // message for this - Oh wait this doesn't even send normally because of the hook MCChatListener.forAllowedCustomAndAllMCChat(e.getPlayer().getName() + " left the game"); // message for this - Oh wait this doesn't even send normally because of the hook*/
} }
@EventHandler @EventHandler
@ -113,20 +109,17 @@ public class MCListener implements Listener {
@EventHandler(priority = EventPriority.LOW) @EventHandler(priority = EventPriority.LOW)
public void onPlayerDeath(PlayerDeathEvent e) { public void onPlayerDeath(PlayerDeathEvent e) {
if (!DiscordPlugin.hooked) MCChatListener.forAllowedCustomAndAllMCChat(MCChatListener.send(e.getDeathMessage()), e.getEntity(), ChannelconBroadcast.DEATH, true);
MCChatListener.sendSystemMessageToChat(e.getDeathMessage());
MCChatListener.forAllowedCustomMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, e.getDeathMessage()), e.getEntity(), ChannelconBroadcast.DEATH);
} }
@EventHandler @EventHandler
public void onPlayerAFK(AfkStatusChangeEvent e) { //TODO: Add AFK to custom chats? public void onPlayerAFK(AfkStatusChangeEvent e) {
final Player base = e.getAffected().getBase(); final Player base = e.getAffected().getBase();
if (e.isCancelled() || !base.isOnline()) if (e.isCancelled() || !base.isOnline())
return; return;
final String msg = base.getDisplayName() final String msg = base.getDisplayName()
+ " is " + (e.getValue() ? "now" : "no longer") + " AFK."; + " is " + (e.getValue() ? "now" : "no longer") + " AFK.";
MCChatListener.sendSystemMessageToChat(msg); MCChatListener.forAllowedCustomAndAllMCChat(MCChatListener.send(msg), base, ChannelconBroadcast.AFK, false);
MCChatListener.forAllowedCustomMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, msg), base, ChannelconBroadcast.AFK);
} }
@EventHandler @EventHandler
@ -158,14 +151,12 @@ public class MCListener implements Listener {
@EventHandler @EventHandler
public void onChatSystemMessage(TBMCSystemChatEvent event) { public void onChatSystemMessage(TBMCSystemChatEvent event) {
MCChatListener.sendSystemMessageToChat(event); MCChatListener.forCustomAndAllMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, event.getMessage()), ChannelconBroadcast.BROADCAST, false);
MCChatListener.forAllowedCustomMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, event.getMessage()), null, ChannelconBroadcast.BROADCAST); //TODO: Method to send message
} }
@EventHandler @EventHandler
public void onBroadcastMessage(BroadcastMessageEvent event) { public void onBroadcastMessage(BroadcastMessageEvent event) {
MCChatListener.sendSystemMessageToChat(event.getMessage()); MCChatListener.forCustomAndAllMCChat(MCChatListener.send(event.getMessage()), ChannelconBroadcast.BROADCAST, false);
MCChatListener.forAllowedCustomMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, event.getMessage()), null, ChannelconBroadcast.BROADCAST);
} }
/*@EventHandler /*@EventHandler

View file

@ -46,13 +46,13 @@ public class DiscordInventory implements Inventory {
@Override @Override
public HashMap<Integer, ItemStack> addItem(ItemStack... items) throws IllegalArgumentException { // Can't add anything public HashMap<Integer, ItemStack> addItem(ItemStack... items) throws IllegalArgumentException { // Can't add anything
return new HashMap<>( return new HashMap<>(
IntStream.range(0, items.length).mapToObj(i -> i).collect(Collectors.toMap(i -> i, i -> items[i]))); IntStream.range(0, items.length).boxed().collect(Collectors.toMap(i -> i, i -> items[i])));
} }
@Override @Override
public HashMap<Integer, ItemStack> removeItem(ItemStack... items) throws IllegalArgumentException { public HashMap<Integer, ItemStack> removeItem(ItemStack... items) throws IllegalArgumentException {
return new HashMap<>( return new HashMap<>(
IntStream.range(0, items.length).mapToObj(i -> i).collect(Collectors.toMap(i -> i, i -> items[i]))); IntStream.range(0, items.length).boxed().collect(Collectors.toMap(i -> i, i -> items[i])));
} }
@Override @Override