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.util.EmbedBuilder;
import javax.annotation.Nullable;
import java.awt.*;
import java.util.Arrays;
import java.util.stream.Collectors;
@ -62,9 +63,10 @@ public class ChromaBot {
*
* @param message The message to send, duh
* @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) {
MCChatListener.forCustomAndAllMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, message, embed));
public void sendMessageCustomAsWell(String message, EmbedObject embed, @Nullable ChannelconBroadcast toggle) {
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 dcp = new DiscordConnectedPlayer(user, ch, UUID.fromString(chcon.getString("mcuid")), chcon.getString("mcname"));
val groupid = chcon.getString("groupid");
val toggles = chcon.getInt("toggles");
if (!mcch.isPresent() || ch == null || user == null || groupid == null)
continue;
MCChatListener.addCustomChat(ch, groupid, mcch.get(), dp, user, dcp);
MCChatListener.addCustomChat(ch, groupid, mcch.get(), user, dcp, toggles);
}
}
DiscordCommandBase.registerCommands();
if (ResetMCCommand.resetting)
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)) {
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(
"The server shut down unexpectedly. See the log of the previous run for more details.");
thr.setStackTrace(new StackTraceElement[0]);
TBMCCoreAPI.SendException("The server crashed!", thr);
} else
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
@ -261,17 +262,15 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
chconc.set("mcuid", chcon.dcp.getUniqueId().toString());
chconc.set("mcname", chcon.dcp.getName());
chconc.set("groupid", chcon.groupID);
chconc.set("toggles", chcon.toggles);
}
saveConfig();
MCChatListener.forCustomAndAllMCChat(ch -> {
try {
EmbedObject embed;
if (ResetMCCommand.resetting)
DiscordPlugin.sendMessageToChannelWait(ch, "",
new EmbedBuilder().withColor(Color.ORANGE).withTitle("Discord plugin restarting").build());
embed = new EmbedBuilder().withColor(Color.ORANGE).withTitle("Discord plugin restarting").build();
else
DiscordPlugin.sendMessageToChannelWait(ch, "",
new EmbedBuilder().withColor(Restart ? Color.ORANGE : Color.RED)
embed = new EmbedBuilder().withColor(Restart ? Color.ORANGE : Color.RED)
.withTitle(Restart ? "Server restarting" : "Server stopping")
.withDescription(
Bukkit.getOnlinePlayers().size() > 0
@ -279,13 +278,17 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
.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);
+ "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 -> {
try {
DiscordPlugin.sendMessageToChannelWait(ch, "",
embed, 5, TimeUnit.SECONDS);
} catch (TimeoutException | InterruptedException e) {
e.printStackTrace();
}
});
}, ChannelconBroadcast.RESTART, false);
ChromaBot.getInstance().updatePlayerList();
try {
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());
}
try {
if (channel == chatchannel)
MCChatListener.resetLastMessage(); // If this is a chat message, it'll be set again
else if (channel.isPrivate())
MCChatListener.resetLastMessage(channel);
MCChatListener.resetLastMessage(channel); // If this is a chat message, it'll be set again
final String content = message;
RequestBuffer.IRequest<IMessage> r = () -> embed == null ? channel.sendMessage(content)
: channel.sendMessage(content, embed, false);

View file

@ -30,7 +30,7 @@ public class PlayerListWatcher extends DedicatedPlayerList {
if (packet instanceof PacketPlayOutChat) {
Field msgf = PacketPlayOutChat.class.getDeclaredField("a");
msgf.setAccessible(true);
MCChatListener.sendSystemMessageToChat(((IChatBaseComponent) msgf.get(packet)).toPlainText());
MCChatListener.forAllMCChat(MCChatListener.send(((IChatBaseComponent) msgf.get(packet)).toPlainText()));
}
} catch (Exception 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;
}
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(" ");
if (argsa.length < 2) {
message.reply("Toggles: " + togglesString.get());
message.reply("toggles:\n" + togglesString.get());
return true;
}
String arg = argsa[1].toUpperCase();
val b = Arrays.stream(ChannelconBroadcast.values()).filter(t -> t.toString().equals(arg)).findAny();
if (!b.isPresent()) {
message.reply("Cannot find toggle. Toggles: " + togglesString.get());
message.reply("cannot find toggle. Toggles:\n" + togglesString.get());
return true;
}
//TODO: Toggle that toggle
val cc = MCChatListener.getCustomChat(message.getChannel());
//A B | F
//------- A: original - B: mask - F: new
//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.");
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 + "`!");
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"))
&& (e.isFromcmd() || isdifferentchannel.test(DiscordPlugin.chatchannel)))
doit.accept(lastmsgdata == null
? lastmsgdata = new LastMsgData(DiscordPlugin.chatchannel, null, null)
? lastmsgdata = new LastMsgData(DiscordPlugin.chatchannel, null)
: lastmsgdata);
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)))
doit.accept(data);
}
@ -167,7 +167,6 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
public final IChannel channel;
public Channel mcchannel;
public final IUser user;
public final DiscordPlayer dp;
}
public static class CustomLMD extends LastMsgData {
@ -176,12 +175,13 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
public final DiscordConnectedPlayer dcp;
public int toggles;
public CustomLMD(@NonNull IChannel channel, @NonNull IUser user, @NonNull DiscordPlayer dp,
@NonNull String groupid, @NonNull Channel mcchannel, @NonNull DiscordConnectedPlayer dcp) {
super(channel, user, dp);
private CustomLMD(@NonNull IChannel channel, @NonNull IUser user,
@NonNull String groupid, @NonNull Channel mcchannel, @NonNull DiscordConnectedPlayer dcp, int toggles) {
super(channel, user);
groupID = groupid;
this.mcchannel = mcchannel;
this.dcp = dcp;
this.toggles = toggles;
}
}
@ -240,7 +240,7 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
if (!start)
lastmsgfromd.remove(channel.getLongID());
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());
}
@ -295,8 +295,8 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
.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) {
val lmd = new CustomLMD(channel, user, dp, groupid, mcchannel, dcp);
public static void addCustomChat(IChannel channel, String groupid, Channel mcchannel, IUser user, DiscordConnectedPlayer dcp, int toggles) {
val lmd = new CustomLMD(channel, user, groupid, mcchannel, dcp, toggles);
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 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) {
forAllMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, DPUtils.sanitizeString(msg)));
public static void resetLastMessage(IChannel channel) {
if (channel.getLongID() == DiscordPlugin.chatchannel.getLongID()) {
(lastmsgdata == null ? lastmsgdata = new LastMsgData(DiscordPlugin.chatchannel, null)
: lastmsgdata).message = null;
return;
} // Don't set the whole object to null, the player and channel information should be preserved
for (LastMsgData data : channel.isPrivate() ? lastmsgPerUser : lastmsgCustom) {
if (data.channel.getLongID() == channel.getLongID()) {
data.message = null;
return;
}
public static void sendSystemMessageToChat(TBMCSystemChatEvent event) {
forAllowedMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, DPUtils.sanitizeString(event.getMessage())),
event);
}
//If it gets here, it's sending a message to a non-chat channel
}
public static void forAllMCChat(Consumer<IChannel> action) {
@ -364,9 +356,21 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
// lastmsgCustom.forEach(cc -> action.accept(cc.channel)); - Only send relevant messages to custom chat
}
public static void forCustomAndAllMCChat(Consumer<IChannel> action) {
/**
* For custom and all MC chat
*
* @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);
lastmsgCustom.forEach(cc -> action.accept(cc.channel));
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);
}
/**
@ -388,6 +392,31 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
}).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) {
if (Channel.GlobalChat.ID.equals(event.getChannel().ID))
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)
if (CommandListener.runCommand(ev.getMessage(), true))
return;
if (!ev.getMessage().getChannel().isPrivate())
resetLastMessage();
else if (hasCustomChat)
resetLastMessageCustom(ev.getChannel());
else
resetLastMessage(ev.getMessage().getChannel());
resetLastMessage(ev.getChannel());
lastlist++;
recevents.add(ev);
if (rectask != null)

View file

@ -63,9 +63,7 @@ public class MCListener implements Listener {
p.sendMessage("§bIf it wasn't you, do /discord decline");
}
final String message = e.GetPlayer().PlayerName().get() + " joined the game";
if (!DiscordPlugin.hooked)
MCChatListener.sendSystemMessageToChat(message);
MCChatListener.forAllowedCustomMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, message), e.getPlayer(), ChannelconBroadcast.JOINLEAVE);
MCChatListener.forAllowedCustomAndAllMCChat(MCChatListener.send(message), e.getPlayer(), ChannelconBroadcast.JOINLEAVE, true);
//System.out.println("Does this appear more than once?"); //No
MCChatListener.ListC = 0;
ChromaBot.getInstance().updatePlayerList();
@ -85,16 +83,14 @@ public class MCListener implements Listener {
Bukkit.getScheduler().runTaskLaterAsynchronously(DiscordPlugin.plugin,
ChromaBot.getInstance()::updatePlayerList, 5);
final String message = e.GetPlayer().PlayerName().get() + " left the game";
if (!DiscordPlugin.hooked)
MCChatListener.sendSystemMessageToChat(message); //TODO: Probably double sends if kicked and unhooked
MCChatListener.forAllowedCustomMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, message), e.getPlayer(), ChannelconBroadcast.JOINLEAVE);
MCChatListener.forAllowedCustomAndAllMCChat(MCChatListener.send(message), e.getPlayer(), ChannelconBroadcast.JOINLEAVE, true);
}
@EventHandler(priority = EventPriority.HIGHEST)
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
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
@ -113,20 +109,17 @@ public class MCListener implements Listener {
@EventHandler(priority = EventPriority.LOW)
public void onPlayerDeath(PlayerDeathEvent e) {
if (!DiscordPlugin.hooked)
MCChatListener.sendSystemMessageToChat(e.getDeathMessage());
MCChatListener.forAllowedCustomMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, e.getDeathMessage()), e.getEntity(), ChannelconBroadcast.DEATH);
MCChatListener.forAllowedCustomAndAllMCChat(MCChatListener.send(e.getDeathMessage()), e.getEntity(), ChannelconBroadcast.DEATH, true);
}
@EventHandler
public void onPlayerAFK(AfkStatusChangeEvent e) { //TODO: Add AFK to custom chats?
public void onPlayerAFK(AfkStatusChangeEvent e) {
final Player base = e.getAffected().getBase();
if (e.isCancelled() || !base.isOnline())
return;
final String msg = base.getDisplayName()
+ " is " + (e.getValue() ? "now" : "no longer") + " AFK.";
MCChatListener.sendSystemMessageToChat(msg);
MCChatListener.forAllowedCustomMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, msg), base, ChannelconBroadcast.AFK);
MCChatListener.forAllowedCustomAndAllMCChat(MCChatListener.send(msg), base, ChannelconBroadcast.AFK, false);
}
@EventHandler
@ -158,14 +151,12 @@ public class MCListener implements Listener {
@EventHandler
public void onChatSystemMessage(TBMCSystemChatEvent event) {
MCChatListener.sendSystemMessageToChat(event);
MCChatListener.forAllowedCustomMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, event.getMessage()), null, ChannelconBroadcast.BROADCAST); //TODO: Method to send message
MCChatListener.forCustomAndAllMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, event.getMessage()), ChannelconBroadcast.BROADCAST, false);
}
@EventHandler
public void onBroadcastMessage(BroadcastMessageEvent event) {
MCChatListener.sendSystemMessageToChat(event.getMessage());
MCChatListener.forAllowedCustomMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, event.getMessage()), null, ChannelconBroadcast.BROADCAST);
MCChatListener.forCustomAndAllMCChat(MCChatListener.send(event.getMessage()), ChannelconBroadcast.BROADCAST, false);
}
/*@EventHandler

View file

@ -46,13 +46,13 @@ public class DiscordInventory implements Inventory {
@Override
public HashMap<Integer, ItemStack> addItem(ItemStack... items) throws IllegalArgumentException { // Can't add anything
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
public HashMap<Integer, ItemStack> removeItem(ItemStack... items) throws IllegalArgumentException {
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