Another version of the events stuff

It directly calls the methods in the modules
Also made a fun module
This commit is contained in:
Norbi Peti 2018-12-23 03:22:50 +01:00
parent e29e6f1682
commit 7a6b79365f
No known key found for this signature in database
GPG key ID: DBA4C4549A927E56
8 changed files with 273 additions and 237 deletions

View file

@ -1,6 +1,7 @@
package buttondevteam.discordplugin.commands;
import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.mcchat.MCChatCommand;
import buttondevteam.lib.TBMCCoreAPI;
import sx.blah.discord.handle.obj.IMessage;

View file

@ -0,0 +1,86 @@
package buttondevteam.discordplugin.fun;
import buttondevteam.core.ComponentManager;
import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.architecture.ConfigData;
import sx.blah.discord.handle.obj.IMessage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class FunModule extends Component {
private static FunModule mod;
private static final String[] serverReadyStrings = new String[]{"In one week from now", // Ali
"Between now and the heat-death of the universe.", // Ghostise
"Soon™", "Ask again this time next month", // Ghostise
"In about 3 seconds", // Nicolai
"After we finish 8 plugins", // Ali
"Tomorrow.", // Ali
"After one tiiiny feature", // Ali
"Next commit", // Ali
"After we finish strangling Towny", // Ali
"When we kill every *fucking* bug", // Ali
"Once the server stops screaming.", // Ali
"After HL3 comes out", // Ali
"Next time you ask", // Ali
"When will *you* be open?" // Ali
};
private ConfigData<Boolean> serverReady() {
return getData("serverReady", true);
}
private ConfigData<List<String>> serverReadyAnswers() {
return getData("serverReadyAnswers", Arrays.asList(serverReadyStrings),
data -> (List<String>) data, data -> data); //TODO: Test
}
private static final String[] serverReadyQuestions = new String[]{"when will the server be open",
"when will the server be ready", "when will the server be done", "when will the server be complete",
"when will the server be finished", "when's the server ready", "when's the server open",
"Vhen vill ze server be open?"};
private static final Random serverReadyRandom = new Random();
private static final ArrayList<Short> usableServerReadyStrings = new ArrayList<Short>(serverReadyStrings.length) {
private static final long serialVersionUID = 2213771460909848770L;
{
createUsableServerReadyStrings(this);
}
};
private static void createUsableServerReadyStrings(ArrayList<Short> list) {
for (short i = 0; i < serverReadyStrings.length; i++)
list.add(i);
}
@Override
protected void enable() {
mod = this;
}
@Override
protected void disable() {
}
public static boolean executeMemes(IMessage message) {
if (!ComponentManager.isEnabled(FunModule.class)) return false;
if (mod.serverReady().get()) {
if (!TBMCCoreAPI.IsTestServer()
&& Arrays.stream(serverReadyQuestions).anyMatch(s -> message.getContent().toLowerCase().contains(s))) {
int next;
if (usableServerReadyStrings.size() == 0)
createUsableServerReadyStrings(usableServerReadyStrings);
next = usableServerReadyStrings.remove(serverReadyRandom.nextInt(usableServerReadyStrings.size()));
DiscordPlugin.sendMessageToChannel(message.getChannel(), serverReadyStrings[next]);
return true;
}
}
return false;
}
}

View file

@ -1,27 +1,73 @@
package buttondevteam.discordplugin.listeners;
import buttondevteam.discordplugin.AsyncDiscordEvent;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import sx.blah.discord.api.events.Event;
import sx.blah.discord.handle.impl.events.guild.channel.message.MentionEvent;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.commands.DiscordCommandBase;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IMessage;
public class CommandListener implements Listener {
@SuppressWarnings("unchecked")
@EventHandler
public <T extends Event> void onEvent(AsyncDiscordEvent<T> event_) {
if (event_.getEvent() instanceof MentionEvent)
onMention((AsyncDiscordEvent<MentionEvent>) event_);
else if (event_.getEvent() instanceof MessageReceivedEvent)
onMessageReceived((AsyncDiscordEvent<MessageReceivedEvent>) event_);
public class CommandListener {
/**
* Runs a ChromaBot command. If mentionedonly is false, it will only execute the command if it was in #bot with the correct prefix or in private.
*
* @param message The Discord message
* @param mentionedonly Only run the command if ChromaBot is mentioned at the start of the message
* @return Whether it ran the command
*/
public static boolean runCommand(IMessage message, boolean mentionedonly) {
final IChannel channel = message.getChannel();
if (mentionedonly) {
if (!channel.getStringID().equals(DiscordPlugin.botchannel.getStringID())
&& !message.getContent().contains("channelcon")) //Allow channelcon in other servers
return false; //Private chat is handled without mentions
} else {
if (!message.getChannel().isPrivate()
&& !(message.getContent().startsWith("/")
&& channel.getStringID().equals(DiscordPlugin.botchannel.getStringID()))) //
return false;
}
message.getChannel().setTypingStatus(true); // Fun
final StringBuilder cmdwithargs = new StringBuilder(message.getContent());
final String mention = DiscordPlugin.dc.getOurUser().mention(false);
final String mentionNick = DiscordPlugin.dc.getOurUser().mention(true);
boolean gotmention = checkanddeletemention(cmdwithargs, mention, message);
gotmention = checkanddeletemention(cmdwithargs, mentionNick, message) || gotmention;
for (String mentionRole : (Iterable<String>) message.getRoleMentions().stream().filter(r -> DiscordPlugin.dc.getOurUser().hasRole(r)).map(r -> r.mention())::iterator)
gotmention = checkanddeletemention(cmdwithargs, mentionRole, message) || gotmention; // Delete all mentions
if (mentionedonly && !gotmention) {
message.getChannel().setTypingStatus(false);
return false;
}
message.getChannel().setTypingStatus(true);
String cmdwithargsString = cmdwithargs.toString().trim(); //Remove spaces between mention and command
int index = cmdwithargsString.indexOf(" ");
String cmd;
String args;
if (index == -1) {
cmd = cmdwithargsString;
args = "";
} else {
cmd = cmdwithargsString.substring(0, index);
args = cmdwithargsString.substring(index + 1).trim(); //In case there are multiple spaces
}
DiscordCommandBase.runCommand(cmd.toLowerCase(), args, message);
message.getChannel().setTypingStatus(false);
return true;
}
private void onMention(AsyncDiscordEvent<MentionEvent> event) {
//TODO: Can't use priorities with this
}
private void onMessageReceived(AsyncDiscordEvent<MessageReceivedEvent> event) {
private static boolean checkanddeletemention(StringBuilder cmdwithargs, String mention, IMessage message) {
if (message.getContent().startsWith(mention)) // TODO: Resolve mentions: Compound arguments, either a mention or text
if (cmdwithargs.length() > mention.length() + 1)
cmdwithargs.delete(0,
cmdwithargs.charAt(mention.length()) == ' ' ? mention.length() + 1 : mention.length());
else
cmdwithargs.replace(0, cmdwithargs.length(), "help");
else {
if (cmdwithargs.length() > 0 && cmdwithargs.charAt(0) == '/')
cmdwithargs.deleteCharAt(0); //Don't treat / as mention, mentions can be used in public mcchat
return false;
}
if (cmdwithargs.length() == 0)
cmdwithargs.replace(0, cmdwithargs.length(), "help");
return true;
}
}

View file

@ -1,15 +1,11 @@
package buttondevteam.discordplugin.listeners;
import buttondevteam.discordplugin.AsyncDiscordEvent;
import buttondevteam.discordplugin.DPUtils;
import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.commands.DiscordCommandBase;
import buttondevteam.discordplugin.mcchat.MCChatCustom;
import buttondevteam.discordplugin.mcchat.MCChatPrivate;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.discordplugin.mcchat.MinecraftChatModule;
import buttondevteam.lib.architecture.Component;
import lombok.val;
import org.bukkit.Bukkit;
import sx.blah.discord.api.events.Event;
import sx.blah.discord.api.events.IListener;
import sx.blah.discord.handle.impl.events.guild.channel.message.MentionEvent;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
@ -17,195 +13,112 @@ import sx.blah.discord.handle.impl.events.guild.role.RoleCreateEvent;
import sx.blah.discord.handle.impl.events.guild.role.RoleDeleteEvent;
import sx.blah.discord.handle.impl.events.guild.role.RoleUpdateEvent;
import sx.blah.discord.handle.impl.events.user.PresenceUpdateEvent;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IMessage;
import sx.blah.discord.handle.obj.StatusType;
import sx.blah.discord.util.EmbedBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class CommonListeners {
private static final String[] serverReadyStrings = new String[]{"In one week from now", // Ali
"Between now and the heat-death of the universe.", // Ghostise
"Soon™", "Ask again this time next month", // Ghostise
"In about 3 seconds", // Nicolai
"After we finish 8 plugins", // Ali
"Tomorrow.", // Ali
"After one tiiiny feature", // Ali
"Next commit", // Ali
"After we finish strangling Towny", // Ali
"When we kill every *fucking* bug", // Ali
"Once the server stops screaming.", // Ali
"After HL3 comes out", // Ali
"Next time you ask", // Ali
"When will *you* be open?" // Ali
};
/*private static ArrayList<Object> dcListeners=new ArrayList<>();
private static final String[] serverReadyQuestions = new String[]{"when will the server be open",
"when will the server be ready", "when will the server be done", "when will the server be complete",
"when will the server be finished", "when's the server ready", "when's the server open",
"Vhen vill ze server be open?"};
private static final Random serverReadyRandom = new Random();
private static final ArrayList<Short> usableServerReadyStrings = new ArrayList<Short>(serverReadyStrings.length) {
private static final long serialVersionUID = 2213771460909848770L;
{
createUsableServerReadyStrings(this);
}
};
private static void createUsableServerReadyStrings(ArrayList<Short> list) {
for (short i = 0; i < serverReadyStrings.length; i++)
list.add(i);
public static void registerDiscordListener(DiscordListener listener) {
//Step 1: Get all events that are handled by us
//Step 2: Find methods that handle these
//...or just simply call the methods in the right order
}
private static void callDiscordEvent(Event event) {
MCListener.callEventExcluding(new AsyncDiscordEvent(event), true, "DiscordPlugin");
}
String name=event.getClass().getSimpleName();
name=Character.toLowerCase(name.charAt(0))+name.substring(1);
for (Object listener : dcListeners) {
listener.getClass().getMethods(name, AsyncDiscordEvent.class);
}
}*/
private static long lasttime = 0;
public static IListener<?>[] getListeners() {
return new IListener[]{new IListener<MentionEvent>() {
@Override
public void handle(MentionEvent event) {
if (DiscordPlugin.SafeMode)
return;
callDiscordEvent(event);
if (event.getMessage().getAuthor().isBot())
return;
final IChannel channel = event.getMessage().getChannel();
if (!channel.getStringID().equals(DiscordPlugin.botchannel.getStringID())
&& (!event.getMessage().getContent().contains("channelcon") || MCChatCustom.hasCustomChat(channel))) //Allow channelcon in other servers but avoid double handling when it's enabled
return;
if (channel.getStringID().equals(DiscordPlugin.chatchannel.getStringID()))
return; // The chat code already handles this - Right now while testing botchannel is the same as chatchannel
event.getMessage().getChannel().setTypingStatus(true); // Fun
runCommand(event.getMessage(), true);
}
}, new IListener<MessageReceivedEvent>() {
@Override
public void handle(MessageReceivedEvent event) {
if (DiscordPlugin.SafeMode)
return;
final String msglowercase = event.getMessage().getContent().toLowerCase();
if (!TBMCCoreAPI.IsTestServer()
&& Arrays.stream(serverReadyQuestions).anyMatch(s -> msglowercase.contains(s))) {
int next;
if (usableServerReadyStrings.size() == 0)
createUsableServerReadyStrings(usableServerReadyStrings);
next = usableServerReadyStrings.remove(serverReadyRandom.nextInt(usableServerReadyStrings.size()));
DiscordPlugin.sendMessageToChannel(event.getMessage().getChannel(), serverReadyStrings[next]);
return;
}
if (!event.getMessage().getChannel().isPrivate()
&& !(event.getMessage().getContent().startsWith("/")
&& event.getChannel().getStringID().equals(DiscordPlugin.botchannel.getStringID()))) //
return;
if (MCChatPrivate.isMinecraftChatEnabled(event.getAuthor().toString()))
if (!event.getMessage().getContent().equalsIgnoreCase("mcchat"))
return;
if (event.getMessage().getAuthor().isBot())
return;
runCommand(event.getMessage(), false);
}
}, new IListener<sx.blah.discord.handle.impl.events.user.PresenceUpdateEvent>() {
@Override
public void handle(PresenceUpdateEvent event) {
if (DiscordPlugin.SafeMode)
return;
val devrole = DiscordPlugin.devServer.getRolesByName("Developer").get(0);
if (event.getOldPresence().getStatus().equals(StatusType.OFFLINE)
&& !event.getNewPresence().getStatus().equals(StatusType.OFFLINE)
&& event.getUser().getRolesForGuild(DiscordPlugin.devServer).stream()
.anyMatch(r -> r.getLongID() == devrole.getLongID())
&& DiscordPlugin.devServer.getUsersByRole(devrole).stream()
.noneMatch(u -> u.getPresence().getStatus().equals(StatusType.OFFLINE))
&& lasttime + 10 < TimeUnit.NANOSECONDS.toHours(System.nanoTime())
&& Calendar.getInstance().get(Calendar.DAY_OF_MONTH) % 5 == 0) {
DiscordPlugin.sendMessageToChannel(DiscordPlugin.devofficechannel, "Full house!",
new EmbedBuilder()
.withImage(
"https://cdn.discordapp.com/attachments/249295547263877121/249687682618359808/poker-hand-full-house-aces-kings-playing-cards-15553791.png")
.build());
lasttime = TimeUnit.NANOSECONDS.toHours(System.nanoTime());
}
}
}, (IListener<RoleCreateEvent>) event -> {
Bukkit.getScheduler().runTaskLaterAsynchronously(DiscordPlugin.plugin, () -> {
if (event.getRole().isDeleted() || !DiscordPlugin.plugin.isGameRole(event.getRole()))
return; //Deleted or not a game role
DiscordPlugin.GameRoles.add(event.getRole().getName());
DiscordPlugin.sendMessageToChannel(DiscordPlugin.modlogchannel, "Added " + event.getRole().getName() + " as game role. If you don't want this, change the role's color from the default.");
}, 100);
}, (IListener<RoleDeleteEvent>) event -> {
if (DiscordPlugin.GameRoles.remove(event.getRole().getName()))
DiscordPlugin.sendMessageToChannel(DiscordPlugin.modlogchannel, "Removed " + event.getRole().getName() + " as a game role.");
}, (IListener<RoleUpdateEvent>) event -> { //Role update event
if (!DiscordPlugin.plugin.isGameRole(event.getNewRole())) {
if (DiscordPlugin.GameRoles.remove(event.getOldRole().getName()))
DiscordPlugin.sendMessageToChannel(DiscordPlugin.modlogchannel, "Removed " + event.getOldRole().getName() + " as a game role because it's color changed.");
} else {
if (DiscordPlugin.GameRoles.contains(event.getOldRole().getName()) && event.getOldRole().getName().equals(event.getNewRole().getName()))
return;
boolean removed = DiscordPlugin.GameRoles.remove(event.getOldRole().getName()); //Regardless of whether it was a game role
DiscordPlugin.GameRoles.add(event.getNewRole().getName()); //Add it because it has no color
if (removed)
DiscordPlugin.sendMessageToChannel(DiscordPlugin.modlogchannel, "Changed game role from " + event.getOldRole().getName() + " to " + event.getNewRole().getName() + ".");
else
DiscordPlugin.sendMessageToChannel(DiscordPlugin.modlogchannel, "Added " + event.getNewRole().getName() + " as game role because it has the default color.");
}
}};
}
/*
MentionEvent:
- CommandListener (starts with mention, in #bot unless 'channelcon')
/**
* Runs a ChromaBot command.
*
* @param message The Discord message
* @param mentionedonly Only run the command if ChromaBot is mentioned at the start of the message
* @return Whether it ran the command (always true if mentionedonly is false)
*/
public static boolean runCommand(IMessage message, boolean mentionedonly) {
debug("A");
if (DiscordPlugin.SafeMode)
return true;
debug("B");
final StringBuilder cmdwithargs = new StringBuilder(message.getContent());
final String mention = DiscordPlugin.dc.getOurUser().mention(false);
final String mentionNick = DiscordPlugin.dc.getOurUser().mention(true);
boolean gotmention = checkanddeletemention(cmdwithargs, mention, message);
gotmention = checkanddeletemention(cmdwithargs, mentionNick, message) || gotmention;
for (String mentionRole : (Iterable<String>) message.getRoleMentions().stream().filter(r -> DiscordPlugin.dc.getOurUser().hasRole(r)).map(r -> r.mention())::iterator)
gotmention = checkanddeletemention(cmdwithargs, mentionRole, message) || gotmention; // Delete all mentions
debug("C");
if (mentionedonly && !gotmention) {
message.getChannel().setTypingStatus(false);
return false;
}
debug("D");
message.getChannel().setTypingStatus(true);
String cmdwithargsString = cmdwithargs.toString().trim(); //Remove spaces between mention and command
int index = cmdwithargsString.indexOf(" ");
String cmd;
String args;
if (index == -1) {
cmd = cmdwithargsString;
args = "";
} else {
cmd = cmdwithargsString.substring(0, index);
args = cmdwithargsString.substring(index + 1).trim(); //In case there are multiple spaces
}
debug("E");
DiscordCommandBase.runCommand(cmd.toLowerCase(), args, message);
message.getChannel().setTypingStatus(false);
return true;
}
MessageReceivedEvent:
- Minecraft chat (is enabled in the channel and message isn't [/]mcchat)
- CommandListener (with the correct prefix in #bot, or in private)
*/
public static IListener<?>[] getListeners() {
return new IListener[]{new IListener<MentionEvent>() {
@Override
public void handle(MentionEvent event) {
if (DiscordPlugin.SafeMode)
return;
if (event.getMessage().getAuthor().isBot())
return;
CommandListener.runCommand(event.getMessage(), true);
}
}, new IListener<MessageReceivedEvent>() {
@Override
public void handle(MessageReceivedEvent event) {
if (DiscordPlugin.SafeMode)
return;
if (event.getMessage().getAuthor().isBot())
return;
boolean handled = false;
val mcchat = Component.getComponents().get(MinecraftChatModule.class);
if (mcchat != null && mcchat.isEnabled())
handled = ((MinecraftChatModule) mcchat).getListener().handleDiscord(event);
if (!handled)
handled = CommandListener.runCommand(event.getMessage(), false);
}
}, new IListener<sx.blah.discord.handle.impl.events.user.PresenceUpdateEvent>() {
@Override
public void handle(PresenceUpdateEvent event) {
if (DiscordPlugin.SafeMode)
return;
val devrole = DiscordPlugin.devServer.getRolesByName("Developer").get(0);
if (event.getOldPresence().getStatus().equals(StatusType.OFFLINE)
&& !event.getNewPresence().getStatus().equals(StatusType.OFFLINE)
&& event.getUser().getRolesForGuild(DiscordPlugin.devServer).stream()
.anyMatch(r -> r.getLongID() == devrole.getLongID())
&& DiscordPlugin.devServer.getUsersByRole(devrole).stream()
.noneMatch(u -> u.getPresence().getStatus().equals(StatusType.OFFLINE))
&& lasttime + 10 < TimeUnit.NANOSECONDS.toHours(System.nanoTime())
&& Calendar.getInstance().get(Calendar.DAY_OF_MONTH) % 5 == 0) {
DiscordPlugin.sendMessageToChannel(DiscordPlugin.devofficechannel, "Full house!",
new EmbedBuilder()
.withImage(
"https://cdn.discordapp.com/attachments/249295547263877121/249687682618359808/poker-hand-full-house-aces-kings-playing-cards-15553791.png")
.build());
lasttime = TimeUnit.NANOSECONDS.toHours(System.nanoTime());
}
}
}, (IListener<RoleCreateEvent>) event -> {
Bukkit.getScheduler().runTaskLaterAsynchronously(DiscordPlugin.plugin, () -> {
if (event.getRole().isDeleted() || !DiscordPlugin.plugin.isGameRole(event.getRole()))
return; //Deleted or not a game role
DiscordPlugin.GameRoles.add(event.getRole().getName());
DiscordPlugin.sendMessageToChannel(DiscordPlugin.modlogchannel, "Added " + event.getRole().getName() + " as game role. If you don't want this, change the role's color from the default.");
}, 100);
}, (IListener<RoleDeleteEvent>) event -> {
if (DiscordPlugin.GameRoles.remove(event.getRole().getName()))
DiscordPlugin.sendMessageToChannel(DiscordPlugin.modlogchannel, "Removed " + event.getRole().getName() + " as a game role.");
}, (IListener<RoleUpdateEvent>) event -> { //Role update event
if (!DiscordPlugin.plugin.isGameRole(event.getNewRole())) {
if (DiscordPlugin.GameRoles.remove(event.getOldRole().getName()))
DiscordPlugin.sendMessageToChannel(DiscordPlugin.modlogchannel, "Removed " + event.getOldRole().getName() + " as a game role because it's color changed.");
} else {
if (DiscordPlugin.GameRoles.contains(event.getOldRole().getName()) && event.getOldRole().getName().equals(event.getNewRole().getName()))
return;
boolean removed = DiscordPlugin.GameRoles.remove(event.getOldRole().getName()); //Regardless of whether it was a game role
DiscordPlugin.GameRoles.add(event.getNewRole().getName()); //Add it because it has no color
if (removed)
DiscordPlugin.sendMessageToChannel(DiscordPlugin.modlogchannel, "Changed game role from " + event.getOldRole().getName() + " to " + event.getNewRole().getName() + ".");
else
DiscordPlugin.sendMessageToChannel(DiscordPlugin.modlogchannel, "Added " + event.getNewRole().getName() + " as game role because it has the default color.");
}
}};
}
private static boolean debug = false;
@ -217,21 +130,4 @@ public class CommonListeners {
public static boolean debug() {
return debug = !debug;
}
private static boolean checkanddeletemention(StringBuilder cmdwithargs, String mention, IMessage message) {
if (message.getContent().startsWith(mention)) // TODO: Resolve mentions: Compound arguments, either a mention or text
if (cmdwithargs.length() > mention.length() + 1)
cmdwithargs.delete(0,
cmdwithargs.charAt(mention.length()) == ' ' ? mention.length() + 1 : mention.length());
else
cmdwithargs.replace(0, cmdwithargs.length(), "help");
else {
if (cmdwithargs.length() > 0 && cmdwithargs.charAt(0) == '/')
cmdwithargs.deleteCharAt(0); //Don't treat / as mention, mentions can be used in public mcchat
return false;
}
if (cmdwithargs.length() == 0)
cmdwithargs.replace(0, cmdwithargs.length(), "help");
return true;
}
}

View file

@ -0,0 +1,4 @@
package buttondevteam.discordplugin.listeners;
public interface DiscordListener {
}

View file

@ -1,8 +1,8 @@
package buttondevteam.discordplugin.commands;
package buttondevteam.discordplugin.mcchat;
import buttondevteam.discordplugin.DiscordPlayer;
import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.mcchat.MCChatPrivate;
import buttondevteam.discordplugin.commands.DiscordCommandBase;
import buttondevteam.lib.TBMCCoreAPI;
import sx.blah.discord.handle.obj.IMessage;
@ -13,7 +13,7 @@ public class MCChatCommand extends DiscordCommandBase {
return "mcchat";
}
@Override
@Override //TODO: Only register if module is enabled
public boolean run(IMessage message, String args) {
if (!message.getChannel().isPrivate()) {
DiscordPlugin.sendMessageToChannel(message.getChannel(),

View file

@ -5,7 +5,6 @@ import buttondevteam.discordplugin.DPUtils;
import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.DiscordSender;
import buttondevteam.discordplugin.DiscordSenderBase;
import buttondevteam.discordplugin.listeners.CommonListeners;
import buttondevteam.discordplugin.playerfaker.VanillaCommandListener;
import buttondevteam.lib.TBMCChatEvent;
import buttondevteam.lib.TBMCChatPreprocessEvent;
@ -22,7 +21,6 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.scheduler.BukkitTask;
import sx.blah.discord.api.events.IListener;
import sx.blah.discord.api.internal.json.objects.EmbedObject;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
import sx.blah.discord.handle.obj.IChannel;
@ -43,7 +41,7 @@ import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class MCChatListener implements Listener, IListener<MessageReceivedEvent> {
public class MCChatListener implements Listener {
private BukkitTask sendtask;
private LinkedBlockingQueue<AbstractMap.SimpleEntry<TBMCChatEvent, Instant>> sendevents = new LinkedBlockingQueue<>();
private Runnable sendrunnable;
@ -231,27 +229,25 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
private Runnable recrun;
private static Thread recthread;
@Override // Discord - TODO: Call from the common listener
public void handle(MessageReceivedEvent ev) {
// Discord
public boolean handleDiscord(MessageReceivedEvent ev) {
if (!ComponentManager.isEnabled(MinecraftChatModule.class))
return;
return false;
val author = ev.getMessage().getAuthor();
if (author.isBot())
return;
final boolean hasCustomChat = MCChatCustom.hasCustomChat(ev.getChannel());
if (!ev.getMessage().getChannel().getStringID().equals(DiscordPlugin.chatchannel.getStringID())
if (ev.getMessage().getChannel().getLongID() != DiscordPlugin.chatchannel.getLongID()
&& !(ev.getMessage().getChannel().isPrivate() && MCChatPrivate.isMinecraftChatEnabled(author.getStringID()))
&& !hasCustomChat)
return;
if (ev.getMessage().getContent().equalsIgnoreCase("mcchat"))
return; // Race condition: If it gets here after it enabled mcchat it says it - I might as well allow disabling with this (CommonListeners)
if (CommonListeners.runCommand(ev.getMessage(), true))
return;
return false; //Chat isn't enabled on this channel
if (hasCustomChat && ev.getMessage().getContent().length() < "/mcchat<>".length()
&& ev.getMessage().getContent().replace("/", "")
.equalsIgnoreCase("mcchat")) //Either mcchat or /mcchat
return false; //Allow disabling the chat if needed
MCChatUtils.resetLastMessage(ev.getChannel());
lastlist++;
recevents.add(ev);
if (rectask != null)
return;
return true;
recrun = () -> { //Don't return in a while loop next time
recthread = Thread.currentThread();
processDiscordToMC();
@ -259,6 +255,7 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
rectask = Bukkit.getScheduler().runTaskAsynchronously(DiscordPlugin.plugin, recrun); //Continue message processing
};
rectask = Bukkit.getScheduler().runTaskAsynchronously(DiscordPlugin.plugin, recrun); //Start message processing
return true;
}
private void processDiscordToMC() {

View file

@ -3,13 +3,19 @@ package buttondevteam.discordplugin.mcchat;
import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.architecture.Component;
import lombok.Getter;
public class MinecraftChatModule extends Component {
private @Getter MCChatListener listener;
public MCChatListener getListener() { //It doesn't want to generate
return listener;
}
@Override
protected void enable() {
MCChatListener mcchat = new MCChatListener();
DiscordPlugin.dc.getDispatcher().registerListener(mcchat);
TBMCCoreAPI.RegisterEventsForExceptions(mcchat, getPlugin());
listener = new MCChatListener();
DiscordPlugin.dc.getDispatcher().registerListener(listener);
TBMCCoreAPI.RegisterEventsForExceptions(listener, getPlugin());
TBMCCoreAPI.RegisterEventsForExceptions(new MCListener(), getPlugin());
}