Merge pull request #90 from TBMCPlugins/dev

Modules, configs, fixes
This commit is contained in:
Norbi Peti 2019-02-01 17:09:02 +01:00 committed by GitHub
commit 8e36e3e49d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 720 additions and 566 deletions

View file

@ -0,0 +1,138 @@
package buttondevteam.discordplugin;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.architecture.ConfigData;
import buttondevteam.lib.player.ChromaGamerBase;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.val;
import org.bukkit.configuration.file.YamlConfiguration;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IMessage;
import java.io.File;
import java.util.List;
public class AnnouncerModule extends Component {
public ConfigData<IChannel> channel() {
return DPUtils.channelData(getConfig(), "channel", 239519012529111040L);
}
public ConfigData<IChannel> modChannel() {
return DPUtils.channelData(getConfig(), "modChannel", 239519012529111040L);
}
/**
* Set to 0 or >50 to disable
*/
public ConfigData<Short> keepPinned() {
return getConfig().getData("keepPinned", (short) 40);
}
private ConfigData<Long> lastannouncementtime() {
return getConfig().getData("lastAnnouncementTime", 0L);
}
private ConfigData<Long> lastseentime() {
return getConfig().getData("lastSeenTime", 0L);
}
private static final String SubredditURL = "https://www.reddit.com/r/ChromaGamers";
private static boolean stop = false;
@Override
protected void enable() {
stop = false; //If not the first time
DPUtils.performNoWait(() -> {
try {
val keepPinned = keepPinned().get();
if (keepPinned == 0) return;
val channel = channel().get();
List<IMessage> msgs = channel.getPinnedMessages();
for (int i = msgs.size() - 1; i >= keepPinned; i--) { // Unpin all pinned messages except the newest 10
channel.unpin(msgs.get(i));
Thread.sleep(10);
}
} catch (InterruptedException ignore) {
}
});
val yc = YamlConfiguration.loadConfiguration(new File("plugins/DiscordPlugin", "config.yml")); //Name change
if (lastannouncementtime().get() == 0) //Load old data
lastannouncementtime().set(yc.getLong("lastannouncementtime"));
if (lastseentime().get() == 0)
lastseentime().set(yc.getLong("lastseentime"));
new Thread(this::AnnouncementGetterThreadMethod).start();
}
@Override
protected void disable() {
stop = true;
}
private void AnnouncementGetterThreadMethod() {
while (!stop) {
try {
if (!isEnabled()) {
Thread.sleep(10000);
continue;
}
String body = TBMCCoreAPI.DownloadString(SubredditURL + "/new/.json?limit=10");
JsonArray json = new JsonParser().parse(body).getAsJsonObject().get("data").getAsJsonObject()
.get("children").getAsJsonArray();
StringBuilder msgsb = new StringBuilder();
StringBuilder modmsgsb = new StringBuilder();
long lastanntime = lastannouncementtime().get();
for (int i = json.size() - 1; i >= 0; i--) {
JsonObject item = json.get(i).getAsJsonObject();
final JsonObject data = item.get("data").getAsJsonObject();
String author = data.get("author").getAsString();
JsonElement distinguishedjson = data.get("distinguished");
String distinguished;
if (distinguishedjson.isJsonNull())
distinguished = null;
else
distinguished = distinguishedjson.getAsString();
String permalink = "https://www.reddit.com" + data.get("permalink").getAsString();
long date = data.get("created_utc").getAsLong();
if (date > lastseentime().get())
lastseentime().set(date);
else if (date > lastannouncementtime().get()) {
do {
val reddituserclass = ChromaGamerBase.getTypeForFolder("reddit");
if (reddituserclass == null)
break;
val user = ChromaGamerBase.getUser(author, reddituserclass);
String id = user.getConnectedID(DiscordPlayer.class);
if (id != null)
author = "<@" + id + ">";
} while (false);
if (!author.startsWith("<"))
author = "/u/" + author;
(distinguished != null && distinguished.equals("moderator") ? modmsgsb : msgsb)
.append("A new post was submitted to the subreddit by ").append(author).append("\n")
.append(permalink).append("\n");
lastanntime = date;
}
}
if (msgsb.length() > 0)
channel().get().pin(DiscordPlugin.sendMessageToChannelWait(channel().get(), msgsb.toString()));
if (modmsgsb.length() > 0)
DiscordPlugin.sendMessageToChannel(modChannel().get(), modmsgsb.toString());
if (lastannouncementtime().get() != lastanntime) {
lastannouncementtime().set(lastanntime); // If sending succeeded
getPlugin().saveConfig(); //TODO: Won't be needed if I implement auto-saving
}
} catch (Exception e) {
e.printStackTrace();
}
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}

View file

@ -5,6 +5,7 @@ import buttondevteam.lib.architecture.IHaveConfig;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IIDLinkedObject; import sx.blah.discord.handle.obj.IIDLinkedObject;
import sx.blah.discord.handle.obj.IRole;
import sx.blah.discord.util.EmbedBuilder; import sx.blah.discord.util.EmbedBuilder;
import sx.blah.discord.util.RequestBuffer; import sx.blah.discord.util.RequestBuffer;
import sx.blah.discord.util.RequestBuffer.IRequest; import sx.blah.discord.util.RequestBuffer.IRequest;
@ -111,6 +112,10 @@ public final class DPUtils {
return config.getDataPrimDef(key, defID, id -> DiscordPlugin.dc.getChannelByID((long) id), IIDLinkedObject::getLongID); //We can afford to search for the channel in the cache once (instead of using mainServer) return config.getDataPrimDef(key, defID, id -> DiscordPlugin.dc.getChannelByID((long) id), IIDLinkedObject::getLongID); //We can afford to search for the channel in the cache once (instead of using mainServer)
} }
public static ConfigData<IRole> roleData(IHaveConfig config, String key, long defID) {
return config.getDataPrimDef(key, defID, id -> DiscordPlugin.dc.getRoleByID((long) id), IIDLinkedObject::getLongID); //We can afford to search for the channel in the cache once (instead of using mainServer)
}
/** /**
* Mentions the <b>bot channel</b>. Useful for help texts. * Mentions the <b>bot channel</b>. Useful for help texts.
* *

View file

@ -1,14 +1,16 @@
package buttondevteam.discordplugin; package buttondevteam.discordplugin;
import buttondevteam.component.channel.Channel;
import buttondevteam.discordplugin.broadcaster.GeneralEventBroadcasterModule; import buttondevteam.discordplugin.broadcaster.GeneralEventBroadcasterModule;
import buttondevteam.discordplugin.commands.DiscordCommandBase; import buttondevteam.discordplugin.commands.DiscordCommandBase;
import buttondevteam.discordplugin.exceptions.ExceptionListenerModule; import buttondevteam.discordplugin.exceptions.ExceptionListenerModule;
import buttondevteam.discordplugin.listeners.CommonListeners; import buttondevteam.discordplugin.listeners.CommonListeners;
import buttondevteam.discordplugin.listeners.MCListener; import buttondevteam.discordplugin.listeners.MCListener;
import buttondevteam.discordplugin.mcchat.*; import buttondevteam.discordplugin.mcchat.MCChatPrivate;
import buttondevteam.discordplugin.mcchat.MCChatUtils;
import buttondevteam.discordplugin.mcchat.MinecraftChatModule;
import buttondevteam.discordplugin.mccommands.DiscordMCCommandBase; import buttondevteam.discordplugin.mccommands.DiscordMCCommandBase;
import buttondevteam.discordplugin.mccommands.ResetMCCommand; import buttondevteam.discordplugin.mccommands.ResetMCCommand;
import buttondevteam.discordplugin.role.GameRoleModule;
import buttondevteam.lib.TBMCCoreAPI; import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.architecture.ButtonPlugin; import buttondevteam.lib.architecture.ButtonPlugin;
import buttondevteam.lib.architecture.Component; import buttondevteam.lib.architecture.Component;
@ -16,10 +18,6 @@ import buttondevteam.lib.architecture.ConfigData;
import buttondevteam.lib.chat.TBMCChatAPI; import buttondevteam.lib.chat.TBMCChatAPI;
import buttondevteam.lib.player.ChromaGamerBase; import buttondevteam.lib.player.ChromaGamerBase;
import com.google.common.io.Files; import com.google.common.io.Files;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.val; import lombok.val;
import net.milkbowl.vault.permission.Permission; import net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -39,20 +37,15 @@ import sx.blah.discord.util.RequestBuffer;
import java.awt.*; import java.awt.*;
import java.io.File; import java.io.File;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class DiscordPlugin extends ButtonPlugin implements IListener<ReadyEvent> { public class DiscordPlugin extends ButtonPlugin implements IListener<ReadyEvent> {
private static final String SubredditURL = "https://www.reddit.com/r/ChromaGamers";
private static boolean stop = false;
public static IDiscordClient dc; public static IDiscordClient dc;
public static DiscordPlugin plugin; public static DiscordPlugin plugin;
public static boolean SafeMode = true; public static boolean SafeMode = true;
public static List<String> GameRoles;
public ConfigData<Character> Prefix() { public ConfigData<Character> Prefix() {
return getIConfig().getData("prefix", '/', str -> ((String) str).charAt(0), Object::toString); return getIConfig().getData("prefix", '/', str -> ((String) str).charAt(0), Object::toString);
@ -73,12 +66,9 @@ public class DiscordPlugin extends ButtonPlugin implements IListener<ReadyEvent>
@Override @Override
public void pluginEnable() { public void pluginEnable() {
stop = false; //If not the first time
try { try {
Bukkit.getLogger().info("Initializing DiscordPlugin..."); Bukkit.getLogger().info("Initializing DiscordPlugin...");
plugin = this; plugin = this;
lastannouncementtime = getConfig().getLong("lastannouncementtime");
lastseentime = getConfig().getLong("lastseentime");
ClientBuilder cb = new ClientBuilder(); ClientBuilder cb = new ClientBuilder();
cb.withToken(Files.readFirstLine(new File("TBMC", "Token.txt"), StandardCharsets.UTF_8)); cb.withToken(Files.readFirstLine(new File("TBMC", "Token.txt"), StandardCharsets.UTF_8));
dc = cb.login(); dc = cb.login();
@ -148,31 +138,15 @@ public class DiscordPlugin extends ButtonPlugin implements IListener<ReadyEvent>
if (task != null) if (task != null)
task.cancel(); task.cancel();
if (!sent) { if (!sent) {
new ChromaBot(this).updatePlayerList(); Component.registerComponent(this, new GeneralEventBroadcasterModule());
GameRoles = mainServer.getRoles().stream().filter(this::isGameRole).map(IRole::getName).collect(Collectors.toList()); Component.registerComponent(this, new MinecraftChatModule());
Component.registerComponent(this, new ExceptionListenerModule());
val chcons = getConfig().getConfigurationSection("chcons"); Component.registerComponent(this, new GameRoleModule()); //Needs the mainServer to be set
if (chcons != null) { Component.registerComponent(this, new AnnouncerModule());
val chconkeys = chcons.getKeys(false); new ChromaBot(this).updatePlayerList(); //Initialize ChromaBot - The MCCHatModule is tested to be enabled
for (val chconkey : chconkeys) {
val chcon = chcons.getConfigurationSection(chconkey);
val mcch = Channel.getChannels().filter(ch -> ch.ID.equals(chcon.getString("mcchid"))).findAny();
val ch = dc.getChannelByID(chcon.getLong("chid"));
val did = chcon.getLong("did");
val user = dc.fetchUser(did);
val groupid = chcon.getString("groupid");
val toggles = chcon.getInt("toggles");
if (!mcch.isPresent() || ch == null || user == null || groupid == null)
continue;
Bukkit.getScheduler().runTask(this, () -> { //<-- Needed because of occasional ConcurrentModificationExceptions when creating the player (PermissibleBase)
val dcp = new DiscordConnectedPlayer(user, ch, UUID.fromString(chcon.getString("mcuid")), chcon.getString("mcname"));
MCChatCustom.addCustomChat(ch, groupid, mcch.get(), user, dcp, toggles);
});
}
}
DiscordCommandBase.registerCommands(); DiscordCommandBase.registerCommands();
if (ResetMCCommand.resetting) if (ResetMCCommand.resetting) //These will only execute if the chat is enabled
ChromaBot.getInstance().sendMessageCustomAsWell("", new EmbedBuilder().withColor(Color.CYAN) ChromaBot.getInstance().sendMessageCustomAsWell("", new EmbedBuilder().withColor(Color.CYAN)
.withTitle("Discord plugin restarted - chat connected.").build(), ChannelconBroadcast.RESTART); //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)) {
@ -190,16 +164,6 @@ public class DiscordPlugin extends ButtonPlugin implements IListener<ReadyEvent>
getConfig().set("serverup", true); getConfig().set("serverup", true);
saveConfig(); saveConfig();
DPUtils.performNoWait(() -> {
try {
List<IMessage> msgs = genchannel.getPinnedMessages();
for (int i = msgs.size() - 1; i >= 10; i--) { // Unpin all pinned messages except the newest 10
genchannel.unpin(msgs.get(i));
Thread.sleep(10);
}
} catch (InterruptedException ignore) {
}
});
sent = true; sent = true;
if (TBMCCoreAPI.IsTestServer() && !dc.getOurUser().getName().toLowerCase().contains("test")) { if (TBMCCoreAPI.IsTestServer() && !dc.getOurUser().getName().toLowerCase().contains("test")) {
TBMCCoreAPI.SendException( TBMCCoreAPI.SendException(
@ -210,71 +174,28 @@ public class DiscordPlugin extends ButtonPlugin implements IListener<ReadyEvent>
} }
TBMCCoreAPI.SendUnsentExceptions(); TBMCCoreAPI.SendUnsentExceptions();
TBMCCoreAPI.SendUnsentDebugMessages(); TBMCCoreAPI.SendUnsentDebugMessages();
/*if (!TBMCCoreAPI.IsTestServer()) {
final Calendar currentCal = Calendar.getInstance();
final Calendar newCal = Calendar.getInstance();
currentCal.set(currentCal.get(Calendar.YEAR), currentCal.get(Calendar.MONTH),
currentCal.get(Calendar.DAY_OF_MONTH), 4, 10);
if (currentCal.get(Calendar.DAY_OF_MONTH) % 9 == 0 && currentCal.before(newCal)) {
Random rand = new Random();
sendMessageToChannel(dc.getChannels().get(rand.nextInt(dc.getChannels().size())),
"You could make a religion out of this");
}
}*/
} }
}, 0, 10); }, 0, 10);
for (IListener<?> listener : CommonListeners.getListeners()) for (IListener<?> listener : CommonListeners.getListeners())
dc.getDispatcher().registerListener(listener); dc.getDispatcher().registerListener(listener);
Component.registerComponent(this, new GeneralEventBroadcasterModule());
Component.registerComponent(this, new MinecraftChatModule());
Component.registerComponent(this, new ExceptionListenerModule());
TBMCCoreAPI.RegisterEventsForExceptions(new MCListener(), this); TBMCCoreAPI.RegisterEventsForExceptions(new MCListener(), this);
TBMCChatAPI.AddCommands(this, DiscordMCCommandBase.class); TBMCChatAPI.AddCommands(this, DiscordMCCommandBase.class);
TBMCCoreAPI.RegisterUserClass(DiscordPlayer.class); TBMCCoreAPI.RegisterUserClass(DiscordPlayer.class);
ChromaGamerBase.addConverter(sender -> Optional.ofNullable(sender instanceof DiscordSenderBase ChromaGamerBase.addConverter(sender -> Optional.ofNullable(sender instanceof DiscordSenderBase
? ((DiscordSenderBase) sender).getChromaUser() : null)); ? ((DiscordSenderBase) sender).getChromaUser() : null));
new Thread(this::AnnouncementGetterThreadMethod).start();
setupProviders(); setupProviders();
} catch (Exception e) { } catch (Exception e) {
TBMCCoreAPI.SendException("An error occured while enabling DiscordPlugin!", e); TBMCCoreAPI.SendException("An error occured while enabling DiscordPlugin!", e);
} }
} }
public boolean isGameRole(IRole r) {
if (r.getGuild().getLongID() != mainServer.getLongID())
return false; //Only allow on the main server
val rc = new Color(149, 165, 166, 0);
return r.getColor().equals(rc)
&& r.getPosition() < mainServer.getRoleByID(234343495735836672L).getPosition(); //Below the ChromaBot role
}
/** /**
* Always true, except when running "stop" from console * Always true, except when running "stop" from console
*/ */
public static boolean Restart; public static boolean Restart;
@Override @Override
public void pluginDisable() { public void pluginPreDisable() {
stop = true;
MCChatPrivate.logoutAll();
getConfig().set("lastannouncementtime", lastannouncementtime);
getConfig().set("lastseentime", lastseentime);
getConfig().set("serverup", false);
val chcons = MCChatCustom.getCustomChats();
val chconsc = getConfig().createSection("chcons");
for (val chcon : chcons) {
val chconc = chconsc.createSection(chcon.channel.getStringID());
chconc.set("mcchid", chcon.mcchannel.ID);
chconc.set("chid", chcon.channel.getLongID());
chconc.set("did", chcon.user.getLongID());
chconc.set("mcuid", chcon.dcp.getUniqueId().toString());
chconc.set("mcname", chcon.dcp.getName());
chconc.set("groupid", chcon.groupID);
chconc.set("toggles", chcon.toggles);
}
saveConfig();
EmbedObject embed; EmbedObject embed;
if (ResetMCCommand.resetting) if (ResetMCCommand.resetting)
embed = new EmbedBuilder().withColor(Color.ORANGE).withTitle("Discord plugin restarting").build(); embed = new EmbedBuilder().withColor(Color.ORANGE).withTitle("Discord plugin restarting").build();
@ -299,9 +220,16 @@ public class DiscordPlugin extends ButtonPlugin implements IListener<ReadyEvent>
} }
}, ChannelconBroadcast.RESTART, false); }, ChannelconBroadcast.RESTART, false);
ChromaBot.getInstance().updatePlayerList(); ChromaBot.getInstance().updatePlayerList();
}
@Override
public void pluginDisable() {
MCChatPrivate.logoutAll();
getConfig().set("serverup", false);
saveConfig();
try { try {
SafeMode = true; // Stop interacting with Discord SafeMode = true; // Stop interacting with Discord
MCChatListener.stop(true);
ChromaBot.delete(); ChromaBot.delete();
dc.changePresence(StatusType.IDLE, ActivityType.PLAYING, "Chromacraft"); //No longer using the same account for testing dc.changePresence(StatusType.IDLE, ActivityType.PLAYING, "Chromacraft"); //No longer using the same account for testing
dc.logout(); dc.logout();
@ -312,76 +240,8 @@ public class DiscordPlugin extends ButtonPlugin implements IListener<ReadyEvent>
} }
} }
private long lastannouncementtime = 0;
private long lastseentime = 0;
public static final ReactionEmoji DELIVERED_REACTION = ReactionEmoji.of(""); public static final ReactionEmoji DELIVERED_REACTION = ReactionEmoji.of("");
private void AnnouncementGetterThreadMethod() {
while (!stop) {
try {
if (SafeMode) {
Thread.sleep(10000);
continue;
}
String body = TBMCCoreAPI.DownloadString(SubredditURL + "/new/.json?limit=10");
JsonArray json = new JsonParser().parse(body).getAsJsonObject().get("data").getAsJsonObject()
.get("children").getAsJsonArray();
StringBuilder msgsb = new StringBuilder();
StringBuilder modmsgsb = new StringBuilder();
long lastanntime = lastannouncementtime;
for (int i = json.size() - 1; i >= 0; i--) {
JsonObject item = json.get(i).getAsJsonObject();
final JsonObject data = item.get("data").getAsJsonObject();
String author = data.get("author").getAsString();
JsonElement distinguishedjson = data.get("distinguished");
String distinguished;
if (distinguishedjson.isJsonNull())
distinguished = null;
else
distinguished = distinguishedjson.getAsString();
String permalink = "https://www.reddit.com" + data.get("permalink").getAsString();
long date = data.get("created_utc").getAsLong();
if (date > lastseentime)
lastseentime = date;
else if (date > lastannouncementtime) {
do {
val reddituserclass = ChromaGamerBase.getTypeForFolder("reddit");
if (reddituserclass == null)
break;
val user = ChromaGamerBase.getUser(author, reddituserclass);
String id = user.getConnectedID(DiscordPlayer.class);
if (id != null)
author = "<@" + id + ">";
} while (false);
if (!author.startsWith("<"))
author = "/u/" + author;
(distinguished != null && distinguished.equals("moderator") ? modmsgsb : msgsb)
.append("A new post was submitted to the subreddit by ").append(author).append("\n")
.append(permalink).append("\n");
lastanntime = date;
}
}
if (msgsb.length() > 0)
genchannel.pin(sendMessageToChannelWait(genchannel, msgsb.toString()));
if (modmsgsb.length() > 0)
sendMessageToChannel(annchannel, modmsgsb.toString());
if (lastannouncementtime != lastanntime) {
lastannouncementtime = lastanntime; // If sending succeeded
getConfig().set("lastannouncementtime", lastannouncementtime);
getConfig().set("lastseentime", lastseentime);
saveConfig();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
public static void sendMessageToChannel(IChannel channel, String message) { public static void sendMessageToChannel(IChannel channel, String message) {
sendMessageToChannel(channel, message, null); sendMessageToChannel(channel, message, null);
} }

View file

@ -1,6 +1,6 @@
package buttondevteam.discordplugin.commands; package buttondevteam.discordplugin.commands;
import buttondevteam.component.channel.Channel; import buttondevteam.core.component.channel.Channel;
import buttondevteam.discordplugin.*; import buttondevteam.discordplugin.*;
import buttondevteam.discordplugin.mcchat.MCChatCustom; import buttondevteam.discordplugin.mcchat.MCChatCustom;
import buttondevteam.lib.player.TBMCPlayer; import buttondevteam.lib.player.TBMCPlayer;
@ -38,6 +38,7 @@ public class ChannelconCommand extends DiscordCommandBase {
} }
if (args.toLowerCase().startsWith("toggle")) { if (args.toLowerCase().startsWith("toggle")) {
val cc = MCChatCustom.getCustomChat(message.getChannel()); val cc = MCChatCustom.getCustomChat(message.getChannel());
assert cc != null; //It's not null
Supplier<String> togglesString = () -> Arrays.stream(ChannelconBroadcast.values()).map(t -> t.toString().toLowerCase() + ": " + ((cc.toggles & t.flag) == 0 ? "disabled" : "enabled")).collect(Collectors.joining("\n")); 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) {

View file

@ -24,7 +24,6 @@ public abstract class DiscordCommandBase {
commands.put("connect", new ConnectCommand()); // TODO: API for adding commands? commands.put("connect", new ConnectCommand()); // TODO: API for adding commands?
commands.put("userinfo", new UserinfoCommand()); commands.put("userinfo", new UserinfoCommand());
commands.put("help", new HelpCommand()); commands.put("help", new HelpCommand());
commands.put("role", new RoleCommand());
commands.put("mcchat", new MCChatCommand()); commands.put("mcchat", new MCChatCommand());
commands.put("channelcon", new ChannelconCommand()); commands.put("channelcon", new ChannelconCommand());
commands.put("debug", new DebugCommand()); commands.put("debug", new DebugCommand());
@ -56,4 +55,8 @@ public abstract class DiscordCommandBase {
protected String[] splitargs(String args) { protected String[] splitargs(String args) {
return args.split("\\s+"); return args.split("\\s+");
} }
public static void registerCommand(String name, DiscordCommandBase dcb) {
commands.put(name, dcb);
}
} }

View file

@ -5,14 +5,26 @@ import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.lib.TBMCCoreAPI; 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 com.google.common.collect.Lists;
import lombok.val;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import sx.blah.discord.handle.impl.events.user.PresenceUpdateEvent;
import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.handle.obj.IMessage;
import sx.blah.discord.handle.obj.IRole;
import sx.blah.discord.handle.obj.StatusType;
import sx.blah.discord.util.EmbedBuilder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.Calendar;
import java.util.Random; import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
public class FunModule extends Component { public class FunModule extends Component implements Listener {
private static FunModule mod; private static FunModule mod;
private static final String[] serverReadyStrings = new String[]{"In one week from now", // Ali private static final String[] serverReadyStrings = new String[]{"In one week from now", // Ali
@ -35,9 +47,8 @@ public class FunModule extends Component {
return getConfig().getData("serverReady", true); return getConfig().getData("serverReady", true);
} }
private ConfigData<List<String>> serverReadyAnswers() { private ConfigData<ArrayList<String>> serverReadyAnswers() {
return getConfig().getData("serverReadyAnswers", Arrays.asList(serverReadyStrings), return getConfig().getData("serverReadyAnswers", () -> Lists.newArrayList(serverReadyStrings)); //TODO: Test
data -> (List<String>) data, data -> data); //TODO: Test
} }
private static final String[] serverReadyQuestions = new String[]{"when will the server be open", private static final String[] serverReadyQuestions = new String[]{"when will the server be open",
@ -46,41 +57,93 @@ public class FunModule extends Component {
"Vhen vill ze server be open?"}; "Vhen vill ze server be open?"};
private static final Random serverReadyRandom = new Random(); private static final Random serverReadyRandom = new Random();
private static final ArrayList<Short> usableServerReadyStrings = new ArrayList<Short>(serverReadyStrings.length) { private static final ArrayList<Short> usableServerReadyStrings = new ArrayList<>(0);
private static final long serialVersionUID = 2213771460909848770L;
{ private void createUsableServerReadyStrings() {
createUsableServerReadyStrings(this); IntStream.range(0, serverReadyAnswers().get().size())
} .forEach(i -> FunModule.usableServerReadyStrings.add((short) i));
};
private static void createUsableServerReadyStrings(ArrayList<Short> list) {
for (short i = 0; i < serverReadyStrings.length; i++)
list.add(i);
} }
@Override @Override
protected void enable() { protected void enable() {
mod = this; mod = this;
registerListener(this);
} }
@Override @Override
protected void disable() { protected void disable() {
lastlist = lastlistp = ListC = 0;
} }
private static short lastlist = 0;
private static short lastlistp = 0;
private static short ListC = 0;
public static boolean executeMemes(IMessage message) { public static boolean executeMemes(IMessage message) {
if (!ComponentManager.isEnabled(FunModule.class)) return false; val fm = ComponentManager.getIfEnabled(FunModule.class);
if (fm == null) return false;
String msglowercased = message.getContent().toLowerCase();
lastlist++;
if (lastlist > 5) {
ListC = 0;
lastlist = 0;
}
if (msglowercased.equals("list") && Bukkit.getOnlinePlayers().size() == lastlistp && ListC++ > 2) // Lowered already
{
message.reply("Stop it. You know the answer.");
lastlist = 0;
lastlistp = (short) Bukkit.getOnlinePlayers().size();
return true; //Handled
}
lastlistp = (short) Bukkit.getOnlinePlayers().size(); //Didn't handle
if (mod.serverReady().get()) { if (mod.serverReady().get()) {
if (!TBMCCoreAPI.IsTestServer() if (!TBMCCoreAPI.IsTestServer()
&& Arrays.stream(serverReadyQuestions).anyMatch(s -> message.getContent().toLowerCase().contains(s))) { && Arrays.stream(serverReadyQuestions).anyMatch(msglowercased::contains)) {
int next; int next;
if (usableServerReadyStrings.size() == 0) if (usableServerReadyStrings.size() == 0)
createUsableServerReadyStrings(usableServerReadyStrings); fm.createUsableServerReadyStrings();
next = usableServerReadyStrings.remove(serverReadyRandom.nextInt(usableServerReadyStrings.size())); next = usableServerReadyStrings.remove(serverReadyRandom.nextInt(usableServerReadyStrings.size()));
DiscordPlugin.sendMessageToChannel(message.getChannel(), serverReadyStrings[next]); DiscordPlugin.sendMessageToChannel(message.getChannel(), serverReadyStrings[next]);
return true; return false; //Still process it as a command/mcchat if needed
} }
} }
return false; return false;
} }
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
ListC = 0;
}
private ConfigData<IRole> fullHouseDevRole() {
return getConfig().getDataPrimDef("fullHouseDevRole", "Developer", name -> {
val list = DiscordPlugin.devServer.getRolesByName((String) name);
return list.size() > 0 ? list.get(0) : null;
}, IRole::getName);
}
private static long lasttime = 0;
public static void handleFullHouse(PresenceUpdateEvent event) {
val fm = ComponentManager.getIfEnabled(FunModule.class);
if (fm == null) return;
val devrole = fm.fullHouseDevRole().get();
if (devrole == null) return;
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());
}
}
} }

View file

@ -2,42 +2,20 @@ package buttondevteam.discordplugin.listeners;
import buttondevteam.discordplugin.DPUtils; import buttondevteam.discordplugin.DPUtils;
import buttondevteam.discordplugin.DiscordPlugin; import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.fun.FunModule;
import buttondevteam.discordplugin.mcchat.MinecraftChatModule; import buttondevteam.discordplugin.mcchat.MinecraftChatModule;
import buttondevteam.discordplugin.role.GameRoleModule;
import buttondevteam.lib.architecture.Component; import buttondevteam.lib.architecture.Component;
import lombok.val; import lombok.val;
import org.bukkit.Bukkit;
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;
import sx.blah.discord.handle.impl.events.guild.role.RoleCreateEvent; 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.RoleDeleteEvent;
import sx.blah.discord.handle.impl.events.guild.role.RoleUpdateEvent; import sx.blah.discord.handle.impl.events.guild.role.RoleUpdateEvent;
import sx.blah.discord.handle.impl.events.user.PresenceUpdateEvent; import sx.blah.discord.handle.impl.events.user.PresenceUpdateEvent;
import sx.blah.discord.handle.obj.StatusType;
import sx.blah.discord.util.EmbedBuilder;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
public class CommonListeners { public class CommonListeners {
/*private static ArrayList<Object> dcListeners=new ArrayList<>();
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) {
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;
/* /*
MentionEvent: MentionEvent:
- CommandListener (starts with mention, only 'channelcon' and not in #bot) - CommandListener (starts with mention, only 'channelcon' and not in #bot)
@ -55,6 +33,8 @@ public class CommonListeners {
return; return;
if (event.getMessage().getAuthor().isBot()) if (event.getMessage().getAuthor().isBot())
return; return;
if (FunModule.executeMemes(event.getMessage()))
return;
boolean handled = false; boolean handled = false;
if (event.getChannel().getLongID() == DiscordPlugin.plugin.CommandChannel().get().getLongID() //If mentioned, that's higher than chat if (event.getChannel().getLongID() == DiscordPlugin.plugin.CommandChannel().get().getLongID() //If mentioned, that's higher than chat
|| event.getMessage().getContent().contains("channelcon")) //Only 'channelcon' is allowed in other channels || event.getMessage().getContent().contains("channelcon")) //Only 'channelcon' is allowed in other channels
@ -71,48 +51,11 @@ public class CommonListeners {
public void handle(PresenceUpdateEvent event) { public void handle(PresenceUpdateEvent event) {
if (DiscordPlugin.SafeMode) if (DiscordPlugin.SafeMode)
return; return;
val devrole = DiscordPlugin.devServer.getRolesByName("Developer").get(0); FunModule.handleFullHouse(event);
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>) GameRoleModule::handleRoleEvent, //
}, (IListener<RoleCreateEvent>) event -> { (IListener<RoleDeleteEvent>) GameRoleModule::handleRoleEvent, //
Bukkit.getScheduler().runTaskLaterAsynchronously(DiscordPlugin.plugin, () -> { (IListener<RoleUpdateEvent>) GameRoleModule::handleRoleEvent};
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; private static boolean debug = false;

View file

@ -2,7 +2,9 @@ package buttondevteam.discordplugin.listeners;
import buttondevteam.discordplugin.DiscordPlayer; import buttondevteam.discordplugin.DiscordPlayer;
import buttondevteam.discordplugin.DiscordPlugin; import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.commands.ConnectCommand;
import buttondevteam.lib.player.TBMCPlayerGetInfoEvent; import buttondevteam.lib.player.TBMCPlayerGetInfoEvent;
import buttondevteam.lib.player.TBMCPlayerJoinEvent;
import lombok.val; import lombok.val;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.event.Event; import org.bukkit.event.Event;
@ -19,6 +21,17 @@ import java.util.Arrays;
import java.util.logging.Level; import java.util.logging.Level;
public class MCListener implements Listener { public class MCListener implements Listener {
@EventHandler
public void onPlayerJoin(TBMCPlayerJoinEvent e) {
if (ConnectCommand.WaitingToConnect.containsKey(e.GetPlayer().PlayerName().get())) {
@SuppressWarnings("ConstantConditions") IUser user = DiscordPlugin.dc
.getUserByID(Long.parseLong(ConnectCommand.WaitingToConnect.get(e.GetPlayer().PlayerName().get())));
e.getPlayer().sendMessage("§bTo connect with the Discord account @" + user.getName() + "#" + user.getDiscriminator()
+ " do /discord accept");
e.getPlayer().sendMessage("§bIf it wasn't you, do /discord decline");
}
}
@EventHandler @EventHandler
public void onGetInfo(TBMCPlayerGetInfoEvent e) { public void onGetInfo(TBMCPlayerGetInfoEvent e) {
if (DiscordPlugin.SafeMode) if (DiscordPlugin.SafeMode)

View file

@ -1,6 +1,6 @@
package buttondevteam.discordplugin.mcchat; package buttondevteam.discordplugin.mcchat;
import buttondevteam.component.channel.Channel; import buttondevteam.core.component.channel.Channel;
import buttondevteam.discordplugin.DiscordConnectedPlayer; import buttondevteam.discordplugin.DiscordConnectedPlayer;
import lombok.NonNull; import lombok.NonNull;
import lombok.val; import lombok.val;

View file

@ -1,8 +1,8 @@
package buttondevteam.discordplugin.mcchat; package buttondevteam.discordplugin.mcchat;
import buttondevteam.component.channel.Channel;
import buttondevteam.component.channel.ChatRoom;
import buttondevteam.core.ComponentManager; import buttondevteam.core.ComponentManager;
import buttondevteam.core.component.channel.Channel;
import buttondevteam.core.component.channel.ChatRoom;
import buttondevteam.discordplugin.DPUtils; import buttondevteam.discordplugin.DPUtils;
import buttondevteam.discordplugin.DiscordPlugin; import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.DiscordSender; import buttondevteam.discordplugin.DiscordSender;
@ -11,6 +11,7 @@ import buttondevteam.discordplugin.listeners.CommandListener;
import buttondevteam.discordplugin.playerfaker.VanillaCommandListener; import buttondevteam.discordplugin.playerfaker.VanillaCommandListener;
import buttondevteam.lib.TBMCChatEvent; import buttondevteam.lib.TBMCChatEvent;
import buttondevteam.lib.TBMCChatPreprocessEvent; import buttondevteam.lib.TBMCChatPreprocessEvent;
import buttondevteam.lib.TBMCCommandPreprocessEvent;
import buttondevteam.lib.TBMCCoreAPI; import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.chat.ChatMessage; import buttondevteam.lib.chat.ChatMessage;
import buttondevteam.lib.chat.TBMCChatAPI; import buttondevteam.lib.chat.TBMCChatAPI;
@ -47,6 +48,11 @@ public class MCChatListener implements Listener {
private LinkedBlockingQueue<AbstractMap.SimpleEntry<TBMCChatEvent, Instant>> sendevents = new LinkedBlockingQueue<>(); private LinkedBlockingQueue<AbstractMap.SimpleEntry<TBMCChatEvent, Instant>> sendevents = new LinkedBlockingQueue<>();
private Runnable sendrunnable; private Runnable sendrunnable;
private static Thread sendthread; private static Thread sendthread;
private final MinecraftChatModule module;
public MCChatListener(MinecraftChatModule minecraftChatModule) {
module = minecraftChatModule;
}
@EventHandler // Minecraft @EventHandler // Minecraft
public void onMCChat(TBMCChatEvent ev) { public void onMCChat(TBMCChatEvent ev) {
@ -122,9 +128,9 @@ public class MCChatListener implements Listener {
|| ((DiscordSenderBase) e.getSender()).getChannel().getLongID() != ch.getLongID(); || ((DiscordSenderBase) e.getSender()).getChannel().getLongID() != ch.getLongID();
if (e.getChannel().isGlobal() if (e.getChannel().isGlobal()
&& (e.isFromCommand() || isdifferentchannel.test(DiscordPlugin.chatchannel))) && (e.isFromCommand() || isdifferentchannel.test(module.chatChannel().get())))
doit.accept(MCChatUtils.lastmsgdata == null doit.accept(MCChatUtils.lastmsgdata == null
? MCChatUtils.lastmsgdata = new MCChatUtils.LastMsgData(DiscordPlugin.chatchannel, null) ? MCChatUtils.lastmsgdata = new MCChatUtils.LastMsgData(module.chatChannel().get(), null)
: MCChatUtils.lastmsgdata); : MCChatUtils.lastmsgdata);
for (MCChatUtils.LastMsgData data : MCChatPrivate.lastmsgPerUser) { for (MCChatUtils.LastMsgData data : MCChatPrivate.lastmsgPerUser) {
@ -175,12 +181,6 @@ public class MCChatListener implements Listener {
} }
} }
private static final String[] UnconnectedCmds = new String[]{"list", "u", "shrug", "tableflip", "unflip", "mwiki",
"yeehaw", "lenny", "rp", "plugins"};
private static short lastlist = 0;
private static short lastlistp = 0;
// ......................DiscordSender....DiscordConnectedPlayer.DiscordPlayerSender // ......................DiscordSender....DiscordConnectedPlayer.DiscordPlayerSender
// Offline public chat......x............................................ // Offline public chat......x............................................
// Online public chat.......x...........................................x // Online public chat.......x...........................................x
@ -192,8 +192,6 @@ public class MCChatListener implements Listener {
// If online and disabling private chat, don't logout // If online and disabling private chat, don't logout
// The maps may not contain the senders for UnconnectedSenders // The maps may not contain the senders for UnconnectedSenders
public static short ListC = 0;
/** /**
* Stop the listener. Any calls to onMCChat will restart it as long as we're not in safe mode. * Stop the listener. Any calls to onMCChat will restart it as long as we're not in safe mode.
* *
@ -218,7 +216,6 @@ public class MCChatListener implements Listener {
MCChatCustom.lastmsgCustom.clear(); MCChatCustom.lastmsgCustom.clear();
MCChatUtils.lastmsgfromd.clear(); MCChatUtils.lastmsgfromd.clear();
MCChatUtils.ConnectedSenders.clear(); MCChatUtils.ConnectedSenders.clear();
lastlist = lastlistp = ListC = 0;
MCChatUtils.UnconnectedSenders.clear(); MCChatUtils.UnconnectedSenders.clear();
recthread = sendthread = null; recthread = sendthread = null;
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -237,7 +234,7 @@ public class MCChatListener implements Listener {
return false; return false;
val author = ev.getMessage().getAuthor(); val author = ev.getMessage().getAuthor();
final boolean hasCustomChat = MCChatCustom.hasCustomChat(ev.getChannel()); final boolean hasCustomChat = MCChatCustom.hasCustomChat(ev.getChannel());
if (ev.getMessage().getChannel().getLongID() != DiscordPlugin.chatchannel.getLongID() if (ev.getMessage().getChannel().getLongID() != module.chatChannel().get().getLongID()
&& !(ev.getMessage().getChannel().isPrivate() && MCChatPrivate.isMinecraftChatEnabled(author.getStringID())) && !(ev.getMessage().getChannel().isPrivate() && MCChatPrivate.isMinecraftChatEnabled(author.getStringID()))
&& !hasCustomChat) && !hasCustomChat)
return false; //Chat isn't enabled on this channel return false; //Chat isn't enabled on this channel
@ -249,7 +246,6 @@ public class MCChatListener implements Listener {
if (CommandListener.runCommand(ev.getMessage(), true)) if (CommandListener.runCommand(ev.getMessage(), true))
return true; //Allow running commands in chat channels return true; //Allow running commands in chat channels
MCChatUtils.resetLastMessage(ev.getChannel()); MCChatUtils.resetLastMessage(ev.getChannel());
lastlist++;
recevents.add(ev); recevents.add(ev);
if (rectask != null) if (rectask != null)
return true; return true;
@ -306,11 +302,11 @@ public class MCChatListener implements Listener {
}); });
final String cmd = dmessage.substring(1); final String cmd = dmessage.substring(1);
final String cmdlowercased = cmd.toLowerCase(); final String cmdlowercased = cmd.toLowerCase();
if (dsender instanceof DiscordSender && Arrays.stream(UnconnectedCmds) if (dsender instanceof DiscordSender && module.whitelistedCommands().get().stream()
.noneMatch(s -> cmdlowercased.equals(s) || cmdlowercased.startsWith(s + " "))) { .noneMatch(s -> cmdlowercased.equals(s) || cmdlowercased.startsWith(s + " "))) {
// Command not whitelisted // Command not whitelisted
dsender.sendMessage("Sorry, you can only access these commands:\n" dsender.sendMessage("Sorry, you can only access these commands:\n"
+ Arrays.stream(UnconnectedCmds).map(uc -> "/" + uc) + module.whitelistedCommands().get().stream().map(uc -> "/" + uc)
.collect(Collectors.joining(", ")) .collect(Collectors.joining(", "))
+ (user.getConnectedID(TBMCPlayer.class) == null + (user.getConnectedID(TBMCPlayer.class) == null
? "\nTo access your commands, first please connect your accounts, using /connect in " ? "\nTo access your commands, first please connect your accounts, using /connect in "
@ -320,15 +316,10 @@ public class MCChatListener implements Listener {
+ "ou can access all of your regular commands (even offline) in private chat: DM me `mcchat`!"); + "ou can access all of your regular commands (even offline) in private chat: DM me `mcchat`!");
return; return;
} }
if (lastlist > 5) { val ev = new TBMCCommandPreprocessEvent(dsender, dmessage);
ListC = 0; Bukkit.getPluginManager().callEvent(ev);
lastlist = 0; if (ev.isCancelled())
} return;
if (cmdlowercased.equals("list") && Bukkit.getOnlinePlayers().size() == lastlistp && ListC++ > 2) // Lowered already
{
dsender.sendMessage("Stop it. You know the answer.");
lastlist = 0;
} else {
int spi = cmdlowercased.indexOf(' '); int spi = cmdlowercased.indexOf(' ');
final String topcmd = spi == -1 ? cmdlowercased : cmdlowercased.substring(0, spi); final String topcmd = spi == -1 ? cmdlowercased : cmdlowercased.substring(0, spi);
Optional<Channel> ch = Channel.getChannels() Optional<Channel> ch = Channel.getChannels()
@ -379,8 +370,6 @@ public class MCChatListener implements Listener {
} }
} }
} }
}
lastlistp = (short) Bukkit.getOnlinePlayers().size();
} else {// Not a command } else {// Not a command
if (dmessage.length() == 0 && event.getMessage().getAttachments().size() == 0 if (dmessage.length() == 0 && event.getMessage().getAttachments().size() == 0
&& !event.getChannel().isPrivate() && event.getMessage().isSystemMessage()) { && !event.getChannel().isPrivate() && event.getMessage().isSystemMessage()) {

View file

@ -1,7 +1,7 @@
package buttondevteam.discordplugin.mcchat; package buttondevteam.discordplugin.mcchat;
import buttondevteam.component.channel.Channel;
import buttondevteam.core.ComponentManager; import buttondevteam.core.ComponentManager;
import buttondevteam.core.component.channel.Channel;
import buttondevteam.discordplugin.*; import buttondevteam.discordplugin.*;
import buttondevteam.discordplugin.broadcaster.GeneralEventBroadcasterModule; import buttondevteam.discordplugin.broadcaster.GeneralEventBroadcasterModule;
import buttondevteam.lib.TBMCSystemChatEvent; import buttondevteam.lib.TBMCSystemChatEvent;
@ -34,6 +34,7 @@ public class MCChatUtils {
public static final HashMap<String, HashMap<IChannel, DiscordPlayerSender>> OnlineSenders = new HashMap<>(); public static final HashMap<String, HashMap<IChannel, DiscordPlayerSender>> OnlineSenders = new HashMap<>();
static @Nullable LastMsgData lastmsgdata; static @Nullable LastMsgData lastmsgdata;
static LongObjectHashMap<IMessage> lastmsgfromd = new LongObjectHashMap<>(); // Last message sent by a Discord user, used for clearing checkmarks static LongObjectHashMap<IMessage> lastmsgfromd = new LongObjectHashMap<>(); // Last message sent by a Discord user, used for clearing checkmarks
private static MinecraftChatModule module;
public static void updatePlayerList() { public static void updatePlayerList() {
if (notEnabled()) return; if (notEnabled()) return;
@ -45,7 +46,13 @@ public class MCChatUtils {
} }
private static boolean notEnabled() { private static boolean notEnabled() {
return !ComponentManager.isEnabled(MinecraftChatModule.class); return getModule() == null;
}
private static MinecraftChatModule getModule() {
if (module == null) module = ComponentManager.getIfEnabled(MinecraftChatModule.class);
else if (!module.isEnabled()) module = null; //Reset if disabled
return module;
} }
private static void updatePL(LastMsgData lmd) { private static void updatePL(LastMsgData lmd) {
@ -95,7 +102,7 @@ public class MCChatUtils {
public static void forAllMCChat(Consumer<IChannel> action) { public static void forAllMCChat(Consumer<IChannel> action) {
if (notEnabled()) return; if (notEnabled()) return;
action.accept(DiscordPlugin.chatchannel); action.accept(module.chatChannel().get());
for (LastMsgData data : MCChatPrivate.lastmsgPerUser) for (LastMsgData data : MCChatPrivate.lastmsgPerUser)
action.accept(data.channel); action.accept(data.channel);
// 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
@ -160,7 +167,7 @@ public class MCChatUtils {
public static void forAllowedMCChat(Consumer<IChannel> action, TBMCSystemChatEvent event) { public static void forAllowedMCChat(Consumer<IChannel> action, TBMCSystemChatEvent event) {
if (notEnabled()) return; if (notEnabled()) return;
if (event.getChannel().isGlobal()) if (event.getChannel().isGlobal())
action.accept(DiscordPlugin.chatchannel); action.accept(module.chatChannel().get());
for (LastMsgData data : MCChatPrivate.lastmsgPerUser) for (LastMsgData data : MCChatPrivate.lastmsgPerUser)
if (event.shouldSendTo(getSender(data.channel, data.user))) if (event.shouldSendTo(getSender(data.channel, data.user)))
action.accept(data.channel); action.accept(data.channel);
@ -192,8 +199,8 @@ public class MCChatUtils {
*/ */
public static void resetLastMessage(IChannel channel) { public static void resetLastMessage(IChannel channel) {
if (notEnabled()) return; if (notEnabled()) return;
if (channel.getLongID() == DiscordPlugin.chatchannel.getLongID()) { if (channel.getLongID() == module.chatChannel().get().getLongID()) {
(lastmsgdata == null ? lastmsgdata = new LastMsgData(DiscordPlugin.chatchannel, null) (lastmsgdata == null ? lastmsgdata = new LastMsgData(module.chatChannel().get(), null)
: lastmsgdata).message = null; : lastmsgdata).message = null;
return; return;
} // Don't set the whole object to null, the player and channel information should be preserved } // Don't set the whole object to null, the player and channel information should be preserved

View file

@ -1,7 +1,6 @@
package buttondevteam.discordplugin.mcchat; package buttondevteam.discordplugin.mcchat;
import buttondevteam.discordplugin.*; import buttondevteam.discordplugin.*;
import buttondevteam.discordplugin.commands.ConnectCommand;
import buttondevteam.lib.TBMCCoreAPI; import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.TBMCSystemChatEvent; import buttondevteam.lib.TBMCSystemChatEvent;
import buttondevteam.lib.player.*; import buttondevteam.lib.player.*;
@ -51,16 +50,8 @@ class MCListener implements Listener {
MCChatUtils.addSender(MCChatUtils.OnlineSenders, dp.getDiscordID(), MCChatUtils.addSender(MCChatUtils.OnlineSenders, dp.getDiscordID(),
new DiscordPlayerSender(user, DiscordPlugin.chatchannel, p)); //Stored per-channel new DiscordPlayerSender(user, DiscordPlugin.chatchannel, p)); //Stored per-channel
} }
if (ConnectCommand.WaitingToConnect.containsKey(e.GetPlayer().PlayerName().get())) {
IUser user = DiscordPlugin.dc
.getUserByID(Long.parseLong(ConnectCommand.WaitingToConnect.get(e.GetPlayer().PlayerName().get())));
p.sendMessage("§bTo connect with the Discord account @" + user.getName() + "#" + user.getDiscriminator()
+ " do /discord accept");
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";
MCChatUtils.forAllowedCustomAndAllMCChat(MCChatUtils.send(message), e.getPlayer(), ChannelconBroadcast.JOINLEAVE, true); MCChatUtils.forAllowedCustomAndAllMCChat(MCChatUtils.send(message), e.getPlayer(), ChannelconBroadcast.JOINLEAVE, true);
MCChatListener.ListC = 0;
ChromaBot.getInstance().updatePlayerList(); ChromaBot.getInstance().updatePlayerList();
}); });
} }
@ -107,7 +98,7 @@ class MCListener implements Listener {
public void onPlayerMute(MuteStatusChangeEvent e) { public void onPlayerMute(MuteStatusChangeEvent e) {
try { try {
DPUtils.performNoWait(() -> { DPUtils.performNoWait(() -> {
final IRole role = DiscordPlugin.dc.getRoleByID(164090010461667328L); final IRole role = DiscordPlugin.dc.getRoleByID(164090010461667328L); //TODO: Config
final CommandSource source = e.getAffected().getSource(); final CommandSource source = e.getAffected().getSource();
if (!source.isPlayer()) if (!source.isPlayer())
return; return;

View file

@ -1,9 +1,20 @@
package buttondevteam.discordplugin.mcchat; package buttondevteam.discordplugin.mcchat;
import buttondevteam.core.component.channel.Channel;
import buttondevteam.discordplugin.DPUtils;
import buttondevteam.discordplugin.DiscordConnectedPlayer;
import buttondevteam.discordplugin.DiscordPlugin; import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.lib.TBMCCoreAPI; import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.architecture.Component; import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.architecture.ConfigData;
import com.google.common.collect.Lists;
import lombok.Getter; import lombok.Getter;
import lombok.val;
import org.bukkit.Bukkit;
import sx.blah.discord.handle.obj.IChannel;
import java.util.ArrayList;
import java.util.UUID;
public class MinecraftChatModule extends Component { public class MinecraftChatModule extends Component {
private @Getter MCChatListener listener; private @Getter MCChatListener listener;
@ -11,16 +22,60 @@ public class MinecraftChatModule extends Component {
public MCChatListener getListener() { //It doesn't want to generate public MCChatListener getListener() { //It doesn't want to generate
return listener; return listener;
} }
public ConfigData<ArrayList<String>> whitelistedCommands() {
return getConfig().getData("whitelistedCommands", () -> Lists.newArrayList("list", "u", "shrug", "tableflip", "unflip", "mwiki",
"yeehaw", "lenny", "rp", "plugins"));
}
public ConfigData<IChannel> chatChannel() {
return DPUtils.channelData(getConfig(), "chatChannel", 239519012529111040L);
}
@Override @Override
protected void enable() { protected void enable() {
listener = new MCChatListener(); listener = new MCChatListener(this);
DiscordPlugin.dc.getDispatcher().registerListener(listener); DiscordPlugin.dc.getDispatcher().registerListener(listener);
TBMCCoreAPI.RegisterEventsForExceptions(listener, getPlugin()); TBMCCoreAPI.RegisterEventsForExceptions(listener, getPlugin());
TBMCCoreAPI.RegisterEventsForExceptions(new MCListener(), getPlugin()); TBMCCoreAPI.RegisterEventsForExceptions(new MCListener(), getPlugin());//These get undone if restarting/resetting - it will ignore events if disabled
val chcons = getConfig().getConfig().getConfigurationSection("chcons");
if (chcons == null) //Fallback to old place
getConfig().getConfig().getRoot().getConfigurationSection("chcons");
if (chcons != null) {
val chconkeys = chcons.getKeys(false);
for (val chconkey : chconkeys) {
val chcon = chcons.getConfigurationSection(chconkey);
val mcch = Channel.getChannels().filter(ch -> ch.ID.equals(chcon.getString("mcchid"))).findAny();
val ch = DiscordPlugin.dc.getChannelByID(chcon.getLong("chid"));
val did = chcon.getLong("did");
val user = DiscordPlugin.dc.fetchUser(did);
val groupid = chcon.getString("groupid");
val toggles = chcon.getInt("toggles");
if (!mcch.isPresent() || ch == null || user == null || groupid == null)
continue;
Bukkit.getScheduler().runTask(getPlugin(), () -> { //<-- Needed because of occasional ConcurrentModificationExceptions when creating the player (PermissibleBase)
val dcp = new DiscordConnectedPlayer(user, ch, UUID.fromString(chcon.getString("mcuid")), chcon.getString("mcname"));
MCChatCustom.addCustomChat(ch, groupid, mcch.get(), user, dcp, toggles);
});
}
}
} }
@Override @Override
protected void disable() { protected void disable() {
//These get undone if restarting/resetting - it will ignore events if disabled val chcons = MCChatCustom.getCustomChats();
val chconsc = getConfig().getConfig().createSection("chcons");
for (val chcon : chcons) {
val chconc = chconsc.createSection(chcon.channel.getStringID());
chconc.set("mcchid", chcon.mcchannel.ID);
chconc.set("chid", chcon.channel.getLongID());
chconc.set("did", chcon.user.getLongID());
chconc.set("mcuid", chcon.dcp.getUniqueId().toString());
chconc.set("mcname", chcon.dcp.getName());
chconc.set("groupid", chcon.groupID);
chconc.set("toggles", chcon.toggles);
}
MCChatListener.stop(true);
} //TODO: Use ComponentManager.isEnabled() at other places too, instead of SafeMode } //TODO: Use ComponentManager.isEnabled() at other places too, instead of SafeMode
} }

View file

@ -0,0 +1,79 @@
package buttondevteam.discordplugin.role;
import buttondevteam.core.ComponentManager;
import buttondevteam.discordplugin.DPUtils;
import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.commands.DiscordCommandBase;
import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.architecture.ConfigData;
import lombok.val;
import org.bukkit.Bukkit;
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.RoleEvent;
import sx.blah.discord.handle.impl.events.guild.role.RoleUpdateEvent;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IRole;
import java.awt.*;
import java.util.List;
import java.util.stream.Collectors;
public class GameRoleModule extends Component {
public List<String> GameRoles;
@Override
protected void enable() {
DiscordCommandBase.registerCommand("role", new RoleCommand(this));
GameRoles = DiscordPlugin.mainServer.getRoles().stream().filter(this::isGameRole).map(IRole::getName).collect(Collectors.toList());
}
@Override
protected void disable() {
}
private ConfigData<IChannel> logChannel() {
return DPUtils.channelData(getConfig(), "logChannel", 239519012529111040L);
}
public static void handleRoleEvent(RoleEvent roleEvent) {
val grm = ComponentManager.getIfEnabled(GameRoleModule.class);
if (grm == null) return;
val GameRoles = grm.GameRoles;
if (roleEvent instanceof RoleCreateEvent) {
Bukkit.getScheduler().runTaskLaterAsynchronously(DiscordPlugin.plugin, () -> {
if (roleEvent.getRole().isDeleted() || !grm.isGameRole(roleEvent.getRole()))
return; //Deleted or not a game role
GameRoles.add(roleEvent.getRole().getName());
DiscordPlugin.sendMessageToChannel(grm.logChannel().get(), "Added " + roleEvent.getRole().getName() + " as game role. If you don't want this, change the role's color from the default.");
}, 100);
} else if (roleEvent instanceof RoleDeleteEvent) {
if (GameRoles.remove(roleEvent.getRole().getName()))
DiscordPlugin.sendMessageToChannel(grm.logChannel().get(), "Removed " + roleEvent.getRole().getName() + " as a game role.");
} else if (roleEvent instanceof RoleUpdateEvent) {
val event = (RoleUpdateEvent) roleEvent;
if (!grm.isGameRole(event.getNewRole())) {
if (GameRoles.remove(event.getOldRole().getName()))
DiscordPlugin.sendMessageToChannel(grm.logChannel().get(), "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;
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
if (removed)
DiscordPlugin.sendMessageToChannel(grm.logChannel().get(), "Changed game role from " + event.getOldRole().getName() + " to " + event.getNewRole().getName() + ".");
else
DiscordPlugin.sendMessageToChannel(grm.logChannel().get(), "Added " + event.getNewRole().getName() + " as game role because it has the default color.");
}
}
}
private boolean isGameRole(IRole r) {
if (r.getGuild().getLongID() != DiscordPlugin.mainServer.getLongID())
return false; //Only allow on the main server
val rc = new Color(149, 165, 166, 0);
return r.getColor().equals(rc)
&& r.getPosition() < DiscordPlugin.mainServer.getRoleByID(234343495735836672L).getPosition(); //Below the ChromaBot role
}
}

View file

@ -1,7 +1,8 @@
package buttondevteam.discordplugin.commands; package buttondevteam.discordplugin.role;
import buttondevteam.discordplugin.DPUtils; import buttondevteam.discordplugin.DPUtils;
import buttondevteam.discordplugin.DiscordPlugin; import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.commands.DiscordCommandBase;
import buttondevteam.lib.TBMCCoreAPI; import buttondevteam.lib.TBMCCoreAPI;
import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.handle.obj.IMessage;
import sx.blah.discord.handle.obj.IRole; import sx.blah.discord.handle.obj.IRole;
@ -9,7 +10,13 @@ import sx.blah.discord.handle.obj.IRole;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class RoleCommand extends DiscordCommandBase { public class RoleCommand extends DiscordCommandBase { //TODO: Use Command2's parser
private GameRoleModule grm;
RoleCommand(GameRoleModule grm) {
this.grm = grm;
}
@Override @Override
public String getCommandName() { public String getCommandName() {
@ -22,23 +29,23 @@ public class RoleCommand extends DiscordCommandBase {
return false; return false;
String[] argsa = splitargs(args); String[] argsa = splitargs(args);
if (argsa[0].equalsIgnoreCase("add")) { if (argsa[0].equalsIgnoreCase("add")) {
final IRole role = checkAndGetRole(message, argsa, "This command adds a game role to your account."); final IRole role = checkAndGetRole(message, argsa, "This command adds a role to your account.");
if (role == null) if (role == null)
return true; return true;
try { try {
DPUtils.perform(() -> message.getAuthor().addRole(role)); DPUtils.perform(() -> message.getAuthor().addRole(role));
DiscordPlugin.sendMessageToChannel(message.getChannel(), "Added game role."); DiscordPlugin.sendMessageToChannel(message.getChannel(), "Added role.");
} catch (Exception e) { } catch (Exception e) {
TBMCCoreAPI.SendException("Error while adding role!", e); TBMCCoreAPI.SendException("Error while adding role!", e);
DiscordPlugin.sendMessageToChannel(message.getChannel(), "An error occured while adding the role."); DiscordPlugin.sendMessageToChannel(message.getChannel(), "An error occured while adding the role.");
} }
} else if (argsa[0].equalsIgnoreCase("remove")) { } else if (argsa[0].equalsIgnoreCase("remove")) {
final IRole role = checkAndGetRole(message, argsa, "This command removes a game role from your account."); final IRole role = checkAndGetRole(message, argsa, "This command removes a role from your account.");
if (role == null) if (role == null)
return true; return true;
try { try {
DPUtils.perform(() -> message.getAuthor().removeRole(role)); DPUtils.perform(() -> message.getAuthor().removeRole(role));
DiscordPlugin.sendMessageToChannel(message.getChannel(), "Removed game role."); DiscordPlugin.sendMessageToChannel(message.getChannel(), "Removed role.");
} catch (Exception e) { } catch (Exception e) {
TBMCCoreAPI.SendException("Error while removing role!", e); TBMCCoreAPI.SendException("Error while removing role!", e);
DiscordPlugin.sendMessageToChannel(message.getChannel(), "An error occured while removing the role."); DiscordPlugin.sendMessageToChannel(message.getChannel(), "An error occured while removing the role.");
@ -51,7 +58,7 @@ public class RoleCommand extends DiscordCommandBase {
private void listRoles(IMessage message) { private void listRoles(IMessage message) {
DiscordPlugin.sendMessageToChannel(message.getChannel(), DiscordPlugin.sendMessageToChannel(message.getChannel(),
"List of game roles:\n" + DiscordPlugin.GameRoles.stream().sorted().collect(Collectors.joining("\n"))); "List of roles:\n" + grm.GameRoles.stream().sorted().collect(Collectors.joining("\n")));
} }
private IRole checkAndGetRole(IMessage message, String[] argsa, String usage) { private IRole checkAndGetRole(IMessage message, String[] argsa, String usage) {
@ -62,8 +69,8 @@ public class RoleCommand extends DiscordCommandBase {
StringBuilder rolename = new StringBuilder(argsa[1]); StringBuilder rolename = new StringBuilder(argsa[1]);
for (int i = 2; i < argsa.length; i++) for (int i = 2; i < argsa.length; i++)
rolename.append(" ").append(argsa[i]); rolename.append(" ").append(argsa[i]);
if (!DiscordPlugin.GameRoles.contains(rolename.toString())) { if (!grm.GameRoles.contains(rolename.toString())) {
DiscordPlugin.sendMessageToChannel(message.getChannel(), "That game role cannot be found."); DiscordPlugin.sendMessageToChannel(message.getChannel(), "That role cannot be found.");
listRoles(message); listRoles(message);
return null; return null;
} }
@ -71,7 +78,7 @@ public class RoleCommand extends DiscordCommandBase {
if (roles.size() == 0) { if (roles.size() == 0) {
DiscordPlugin.sendMessageToChannel(message.getChannel(), DiscordPlugin.sendMessageToChannel(message.getChannel(),
"The specified role cannot be found on Discord! Removing from the list."); "The specified role cannot be found on Discord! Removing from the list.");
DiscordPlugin.GameRoles.remove(rolename.toString()); grm.GameRoles.remove(rolename.toString());
return null; return null;
} }
if (roles.size() > 1) { if (roles.size() > 1) {
@ -85,7 +92,7 @@ public class RoleCommand extends DiscordCommandBase {
@Override @Override
public String[] getHelpText() { public String[] getHelpText() {
return new String[]{ // return new String[]{ //
"Add or remove game roles from yourself.", // "Add or remove roles from yourself.", //
"Usage: " + DiscordPlugin.getPrefix() + "role add|remove <name> or role list", // "Usage: " + DiscordPlugin.getPrefix() + "role add|remove <name> or role list", //
}; };
} }

View file

@ -1,8 +1,8 @@
name: DiscordPlugin name: Thorpe-Discord
main: buttondevteam.discordplugin.DiscordPlugin main: buttondevteam.discordplugin.DiscordPlugin
version: 1.0 version: 1.0
author: NorbiPeti author: NorbiPeti
depend: [ButtonCore] depend: [ThorpeCore]
commands: commands:
discord: discord:
website: 'https://github.com/TBMCPlugins/DiscordPlugin' website: 'https://github.com/TBMCPlugins/DiscordPlugin'