Fixed role admin cmds

And some code analysis stuff
This commit is contained in:
Norbi Peti 2018-04-07 01:05:54 +02:00
parent 42966d0feb
commit b31aea0c04
No known key found for this signature in database
GPG key ID: DBA4C4549A927E56
3 changed files with 365 additions and 350 deletions

View file

@ -1,164 +1,166 @@
package buttondevteam.discordplugin; package buttondevteam.discordplugin;
import java.awt.Color;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import org.bukkit.Bukkit;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import com.google.common.io.Files;
import com.google.gson.*;
import buttondevteam.discordplugin.listeners.*; import buttondevteam.discordplugin.listeners.*;
import buttondevteam.discordplugin.mccommands.DiscordMCCommandBase; import buttondevteam.discordplugin.mccommands.DiscordMCCommandBase;
import buttondevteam.lib.TBMCCoreAPI; import buttondevteam.lib.TBMCCoreAPI;
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.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 sx.blah.discord.api.*; import org.bukkit.Bukkit;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import sx.blah.discord.api.ClientBuilder;
import sx.blah.discord.api.IDiscordClient;
import sx.blah.discord.api.events.IListener; import sx.blah.discord.api.events.IListener;
import sx.blah.discord.api.internal.json.objects.EmbedObject; import sx.blah.discord.api.internal.json.objects.EmbedObject;
import sx.blah.discord.handle.impl.events.ReadyEvent; import sx.blah.discord.handle.impl.events.ReadyEvent;
import sx.blah.discord.handle.impl.obj.ReactionEmoji; import sx.blah.discord.handle.impl.obj.ReactionEmoji;
import sx.blah.discord.handle.obj.*; import sx.blah.discord.handle.obj.*;
import sx.blah.discord.util.*; import sx.blah.discord.util.EmbedBuilder;
import sx.blah.discord.util.RequestBuffer;
import java.awt.*;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> { public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
private static final String SubredditURL = "https://www.reddit.com/r/ChromaGamers"; private static final String SubredditURL = "https://www.reddit.com/r/ChromaGamers";
private static boolean stop = false; private static boolean stop = false;
static Thread mainThread; static Thread mainThread;
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 static List<String> GameRoles;
public static boolean hooked = false; public static boolean hooked = false;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public void onEnable() { public void onEnable() {
try { try {
Bukkit.getLogger().info("Initializing DiscordPlugin..."); Bukkit.getLogger().info("Initializing DiscordPlugin...");
try { try {
PlayerListWatcher.hookUp(); PlayerListWatcher.hookUp();
hooked = true; hooked = true;
Bukkit.getLogger().info("Finished hooking into the player list"); Bukkit.getLogger().info("Finished hooking into the player list");
} catch (Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
Bukkit.getLogger().warning("Couldn't hook into the player list!"); Bukkit.getLogger().warning("Couldn't hook into the player list!");
} }
plugin = this; plugin = this;
lastannouncementtime = getConfig().getLong("lastannouncementtime"); lastannouncementtime = getConfig().getLong("lastannouncementtime");
lastseentime = getConfig().getLong("lastseentime"); lastseentime = getConfig().getLong("lastseentime");
GameRoles = (List<String>) getConfig().getList("gameroles", new ArrayList<String>()); GameRoles = (List<String>) getConfig().getList("gameroles", new ArrayList<String>());
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();
dc.getDispatcher().registerListener(this); dc.getDispatcher().registerListener(this);
mainThread = Thread.currentThread(); mainThread = Thread.currentThread();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
Bukkit.getPluginManager().disablePlugin(this); Bukkit.getPluginManager().disablePlugin(this);
} }
} }
public static IChannel botchannel; public static IChannel botchannel;
public static IChannel annchannel; public static IChannel annchannel;
public static IChannel genchannel; public static IChannel genchannel;
public static IChannel chatchannel; public static IChannel chatchannel;
public static IChannel botroomchannel; public static IChannel botroomchannel;
/** /**
* Don't send messages, just receive, the same channel is used when testing * Don't send messages, just receive, the same channel is used when testing
*/ */
public static IChannel officechannel; public static IChannel officechannel;
public static IChannel updatechannel; public static IChannel updatechannel;
public static IChannel devofficechannel; public static IChannel devofficechannel;
public static IGuild mainServer; public static IGuild mainServer;
public static IGuild devServer; public static IGuild devServer;
private static volatile BukkitTask task; private static volatile BukkitTask task;
private static volatile boolean sent = false; private static volatile boolean sent = false;
@Override @Override
public void handle(ReadyEvent event) { public void handle(ReadyEvent event) {
try { try {
task = Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> { dc.changePresence(StatusType.DND, ActivityType.PLAYING, "booting");
if (mainServer == null || devServer == null) { task = Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> {
mainServer = event.getClient().getGuildByID(125813020357165056L); if (mainServer == null || devServer == null) {
devServer = event.getClient().getGuildByID(219529124321034241L); mainServer = event.getClient().getGuildByID(125813020357165056L);
} devServer = event.getClient().getGuildByID(219529124321034241L);
if (mainServer == null || devServer == null) }
return; // Retry if (mainServer == null || devServer == null)
if (!TBMCCoreAPI.IsTestServer()) { return; // Retry
botchannel = mainServer.getChannelByID(209720707188260864L); // bot if (!TBMCCoreAPI.IsTestServer()) {
annchannel = mainServer.getChannelByID(126795071927353344L); // announcements botchannel = mainServer.getChannelByID(209720707188260864L); // bot
genchannel = mainServer.getChannelByID(125813020357165056L); // general annchannel = mainServer.getChannelByID(126795071927353344L); // announcements
chatchannel = mainServer.getChannelByID(249663564057411596L); // minecraft_chat genchannel = mainServer.getChannelByID(125813020357165056L); // general
botroomchannel = devServer.getChannelByID(239519012529111040L); // bot-room chatchannel = mainServer.getChannelByID(249663564057411596L); // minecraft_chat
officechannel = devServer.getChannelByID(219626707458457603L); // developers-office botroomchannel = devServer.getChannelByID(239519012529111040L); // bot-room
updatechannel = devServer.getChannelByID(233724163519414272L); // server-updates officechannel = devServer.getChannelByID(219626707458457603L); // developers-office
devofficechannel = officechannel; // developers-office updatechannel = devServer.getChannelByID(233724163519414272L); // server-updates
dc.online("on TBMC"); devofficechannel = officechannel; // developers-office
} else { dc.changePresence(StatusType.ONLINE, ActivityType.PLAYING, "Chromacraft");
botchannel = devServer.getChannelByID(239519012529111040L); // bot-room } else {
annchannel = botchannel; // bot-room botchannel = devServer.getChannelByID(239519012529111040L); // bot-room
genchannel = botchannel; // bot-room annchannel = botchannel; // bot-room
botroomchannel = botchannel;// bot-room genchannel = botchannel; // bot-room
chatchannel = botchannel;// bot-room botroomchannel = botchannel;// bot-room
officechannel = devServer.getChannelByID(219626707458457603L); // developers-office chatchannel = botchannel;// bot-room
updatechannel = botchannel; officechannel = devServer.getChannelByID(219626707458457603L); // developers-office
devofficechannel = botchannel;// bot-room updatechannel = botchannel;
dc.online("testing"); devofficechannel = botchannel;// bot-room
} dc.changePresence(StatusType.ONLINE, ActivityType.PLAYING, "testing");
if (botchannel == null || annchannel == null || genchannel == null || botroomchannel == null }
|| chatchannel == null || officechannel == null || updatechannel == null) if (botchannel == null || annchannel == null || genchannel == null || botroomchannel == null
return; // Retry || chatchannel == null || officechannel == null || updatechannel == null)
SafeMode = false; return; // Retry
if (task != null) SafeMode = false;
task.cancel(); if (task != null)
if (!sent) { task.cancel();
new ChromaBot(this).updatePlayerList(); if (!sent) {
if (getConfig().getBoolean("serverup", false)) { new ChromaBot(this).updatePlayerList();
ChromaBot.getInstance().sendMessage("", new EmbedBuilder().withColor(Color.YELLOW) if (getConfig().getBoolean("serverup", false)) {
.withTitle("Server recovered from a crash - chat connected.").build()); ChromaBot.getInstance().sendMessage("", new EmbedBuilder().withColor(Color.YELLOW)
val thr = new Throwable( .withTitle("Server recovered from a crash - chat connected.").build());
"The server shut down unexpectedly. See the log of the previous run for more details."); val thr = new Throwable(
thr.setStackTrace(new StackTraceElement[0]); "The server shut down unexpectedly. See the log of the previous run for more details.");
TBMCCoreAPI.SendException("The server crashed!", thr); thr.setStackTrace(new StackTraceElement[0]);
} else TBMCCoreAPI.SendException("The server crashed!", thr);
ChromaBot.getInstance().sendMessage("", new EmbedBuilder().withColor(Color.GREEN) } else
.withTitle("Server started - chat connected.").build()); ChromaBot.getInstance().sendMessage("", new EmbedBuilder().withColor(Color.GREEN)
getConfig().set("serverup", true); .withTitle("Server started - chat connected.").build());
saveConfig(); getConfig().set("serverup", true);
DPUtils.performNoWait(() -> { saveConfig();
try { DPUtils.performNoWait(() -> {
List<IMessage> msgs = genchannel.getPinnedMessages(); try {
for (int i = msgs.size() - 1; i >= 10; i--) { // Unpin all pinned messages except the newest 10 List<IMessage> msgs = genchannel.getPinnedMessages();
genchannel.unpin(msgs.get(i)); for (int i = msgs.size() - 1; i >= 10; i--) { // Unpin all pinned messages except the newest 10
Thread.sleep(10); genchannel.unpin(msgs.get(i));
} Thread.sleep(10);
} catch (InterruptedException e) { }
} } catch (InterruptedException ignore) {
}); }
sent = true; });
if (TBMCCoreAPI.IsTestServer() && !dc.getOurUser().getName().toLowerCase().contains("test")) { sent = true;
TBMCCoreAPI.SendException( if (TBMCCoreAPI.IsTestServer() && !dc.getOurUser().getName().toLowerCase().contains("test")) {
"Won't load because we're in testing mode and not using the separate account.", TBMCCoreAPI.SendException(
new Exception( "Won't load because we're in testing mode and not using the separate account.",
"The plugin refuses to load until you change the token to the testing account.")); new Exception(
Bukkit.getPluginManager().disablePlugin(this); "The plugin refuses to load until you change the token to the testing account."));
} Bukkit.getPluginManager().disablePlugin(this);
TBMCCoreAPI.SendUnsentExceptions(); }
TBMCCoreAPI.SendUnsentDebugMessages(); TBMCCoreAPI.SendUnsentExceptions();
TBMCCoreAPI.SendUnsentDebugMessages();
/*if (!TBMCCoreAPI.IsTestServer()) { /*if (!TBMCCoreAPI.IsTestServer()) {
final Calendar currentCal = Calendar.getInstance(); final Calendar currentCal = Calendar.getInstance();
final Calendar newCal = Calendar.getInstance(); final Calendar newCal = Calendar.getInstance();
@ -170,196 +172,197 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
"You could make a religion out of this"); "You could make a religion out of this");
} }
}*/ }*/
} }
}, 0, 10); }, 0, 10);
for (IListener<?> listener : CommandListener.getListeners()) for (IListener<?> listener : CommandListener.getListeners())
dc.getDispatcher().registerListener(listener); dc.getDispatcher().registerListener(listener);
MCChatListener mcchat = new MCChatListener(); MCChatListener mcchat = new MCChatListener();
dc.getDispatcher().registerListener(mcchat); dc.getDispatcher().registerListener(mcchat);
TBMCCoreAPI.RegisterEventsForExceptions(mcchat, this); TBMCCoreAPI.RegisterEventsForExceptions(mcchat, this);
TBMCCoreAPI.RegisterEventsForExceptions(new AutoUpdaterListener(), this); TBMCCoreAPI.RegisterEventsForExceptions(new AutoUpdaterListener(), this);
Bukkit.getPluginManager().registerEvents(new ExceptionListener(), this); Bukkit.getPluginManager().registerEvents(new ExceptionListener(), this);
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);
new Thread(this::AnnouncementGetterThreadMethod).start(); new Thread(this::AnnouncementGetterThreadMethod).start();
setupProviders(); setupProviders();
/* /*
* IDiscordOAuth doa = new DiscordOAuthBuilder(dc).withClientID("226443037893591041") .withClientSecret(getConfig().getString("appsecret")) .withRedirectUrl("https://" + * IDiscordOAuth doa = new DiscordOAuthBuilder(dc).withClientID("226443037893591041") .withClientSecret(getConfig().getString("appsecret")) .withRedirectUrl("https://" +
* (TBMCCoreAPI.IsTestServer() ? "localhost" : "server.figytuna.com") + ":8081/callback") .withScopes(Scope.IDENTIFY).withHttpServerOptions(new HttpServerOptions().setPort(8081)) * (TBMCCoreAPI.IsTestServer() ? "localhost" : "server.figytuna.com") + ":8081/callback") .withScopes(Scope.IDENTIFY).withHttpServerOptions(new HttpServerOptions().setPort(8081))
* .withSuccessHandler((rc, user) -> { rc.response().headers().add("Location", "https://" + (TBMCCoreAPI.IsTestServer() ? "localhost" : "server.figytuna.com") + ":8080/login?type=discord&" * .withSuccessHandler((rc, user) -> { rc.response().headers().add("Location", "https://" + (TBMCCoreAPI.IsTestServer() ? "localhost" : "server.figytuna.com") + ":8080/login?type=discord&"
* + rc.request().query()); rc.response().setStatusCode(303); rc.response().end("Redirecting"); rc.response().close(); }).withFailureHandler(rc -> { rc.response().headers().add("Location", * + rc.request().query()); rc.response().setStatusCode(303); rc.response().end("Redirecting"); rc.response().close(); }).withFailureHandler(rc -> { rc.response().headers().add("Location",
* "https://" + (TBMCCoreAPI.IsTestServer() ? "localhost" : "server.figytuna.com") + ":8080/login?type=discord&" + rc.request().query()); rc.response().setStatusCode(303); * "https://" + (TBMCCoreAPI.IsTestServer() ? "localhost" : "server.figytuna.com") + ":8080/login?type=discord&" + rc.request().query()); rc.response().setStatusCode(303);
* rc.response().end("Redirecting"); rc.response().close(); }).build(); getLogger().info("Auth URL: " + doa.buildAuthUrl()); * rc.response().end("Redirecting"); rc.response().close(); }).build(); getLogger().info("Auth URL: " + doa.buildAuthUrl());
*/ */
} catch (Exception e) { } catch (Exception e) {
TBMCCoreAPI.SendException("An error occured while enabling DiscordPlugin!", e); TBMCCoreAPI.SendException("An error occured while enabling DiscordPlugin!", e);
} }
} }
/** /**
* 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 onDisable() { public void onDisable() {
stop = true; stop = true;
for (val entry : MCChatListener.ConnectedSenders.entrySet()) for (val entry : MCChatListener.ConnectedSenders.entrySet())
MCListener.callEventExcludingSome(new PlayerQuitEvent(entry.getValue(), "")); MCListener.callEventExcludingSome(new PlayerQuitEvent(entry.getValue(), ""));
getConfig().set("lastannouncementtime", lastannouncementtime); getConfig().set("lastannouncementtime", lastannouncementtime);
getConfig().set("lastseentime", lastseentime); getConfig().set("lastseentime", lastseentime);
getConfig().set("gameroles", GameRoles); getConfig().set("gameroles", GameRoles);
getConfig().set("serverup", false); getConfig().set("serverup", false);
saveConfig(); saveConfig();
MCChatListener.forAllMCChat(ch -> DiscordPlugin.sendMessageToChannelWait(ch, "", MCChatListener.forAllMCChat(ch -> DiscordPlugin.sendMessageToChannelWait(ch, "",
new EmbedBuilder().withColor(Restart ? Color.ORANGE : Color.RED) new EmbedBuilder().withColor(Restart ? Color.ORANGE : Color.RED)
.withTitle(Restart ? "Server restarting" : "Server stopping") .withTitle(Restart ? "Server restarting" : "Server stopping")
.withDescription( .withDescription(
Bukkit.getOnlinePlayers().size() > 0 Bukkit.getOnlinePlayers().size() > 0
? (DPUtils ? (DPUtils
.sanitizeString(Bukkit.getOnlinePlayers().stream() .sanitizeString(Bukkit.getOnlinePlayers().stream()
.map(p -> p.getDisplayName()).collect(Collectors.joining(", "))) .map(p -> p.getDisplayName()).collect(Collectors.joining(", ")))
+ (Bukkit.getOnlinePlayers().size() == 1 ? " was " : " were ") + (Bukkit.getOnlinePlayers().size() == 1 ? " was " : " were ")
+ "asked *politely* to leave the server for a bit.") + "asked *politely* to leave the server for a bit.")
: "") : "")
.build())); .build()));
try { ChromaBot.getInstance().updatePlayerList();
SafeMode = true; // Stop interacting with Discord try {
ChromaBot.delete(); SafeMode = true; // Stop interacting with Discord
dc.online("on TBMC"); ChromaBot.delete();
dc.logout(); dc.changePresence(StatusType.IDLE, ActivityType.PLAYING, "Chromacraft"); //No longer using the same account for testing
} catch (Exception e) { dc.logout();
TBMCCoreAPI.SendException("An error occured while disabling DiscordPlugin!", e); } catch (Exception e) {
} TBMCCoreAPI.SendException("An error occured while disabling DiscordPlugin!", e);
} }
}
private long lastannouncementtime = 0; private long lastannouncementtime = 0;
private long lastseentime = 0; private long lastseentime = 0;
public static final ReactionEmoji DELIVERED_REACTION = ReactionEmoji.of(""); public static final ReactionEmoji DELIVERED_REACTION = ReactionEmoji.of("");
private void AnnouncementGetterThreadMethod() { private void AnnouncementGetterThreadMethod() {
while (!stop) { while (!stop) {
try { try {
if (SafeMode) { if (SafeMode) {
Thread.sleep(10000); Thread.sleep(10000);
continue; continue;
} }
String body = TBMCCoreAPI.DownloadString(SubredditURL + "/new/.json?limit=10"); String body = TBMCCoreAPI.DownloadString(SubredditURL + "/new/.json?limit=10");
JsonArray json = new JsonParser().parse(body).getAsJsonObject().get("data").getAsJsonObject() JsonArray json = new JsonParser().parse(body).getAsJsonObject().get("data").getAsJsonObject()
.get("children").getAsJsonArray(); .get("children").getAsJsonArray();
StringBuilder msgsb = new StringBuilder(); StringBuilder msgsb = new StringBuilder();
StringBuilder modmsgsb = new StringBuilder(); StringBuilder modmsgsb = new StringBuilder();
long lastanntime = lastannouncementtime; long lastanntime = lastannouncementtime;
for (int i = json.size() - 1; i >= 0; i--) { for (int i = json.size() - 1; i >= 0; i--) {
JsonObject item = json.get(i).getAsJsonObject(); JsonObject item = json.get(i).getAsJsonObject();
final JsonObject data = item.get("data").getAsJsonObject(); final JsonObject data = item.get("data").getAsJsonObject();
String author = data.get("author").getAsString(); String author = data.get("author").getAsString();
JsonElement distinguishedjson = data.get("distinguished"); JsonElement distinguishedjson = data.get("distinguished");
String distinguished; String distinguished;
if (distinguishedjson.isJsonNull()) if (distinguishedjson.isJsonNull())
distinguished = null; distinguished = null;
else else
distinguished = distinguishedjson.getAsString(); distinguished = distinguishedjson.getAsString();
String permalink = "https://www.reddit.com" + data.get("permalink").getAsString(); String permalink = "https://www.reddit.com" + data.get("permalink").getAsString();
long date = data.get("created_utc").getAsLong(); long date = data.get("created_utc").getAsLong();
if (date > lastseentime) if (date > lastseentime)
lastseentime = date; lastseentime = date;
else if (date > lastannouncementtime) { else if (date > lastannouncementtime) {
do { do {
val reddituserclass = ChromaGamerBase.getTypeForFolder("reddit"); val reddituserclass = ChromaGamerBase.getTypeForFolder("reddit");
if (reddituserclass == null) if (reddituserclass == null)
break; break;
val user = ChromaGamerBase.getUser(author, reddituserclass); val user = ChromaGamerBase.getUser(author, reddituserclass);
String id = user.getConnectedID(DiscordPlayer.class); String id = user.getConnectedID(DiscordPlayer.class);
if (id != null) if (id != null)
author = "<@" + id + ">"; author = "<@" + id + ">";
} while (false); } while (false);
if (!author.startsWith("<")) if (!author.startsWith("<"))
author = "/u/" + author; author = "/u/" + author;
(distinguished != null && distinguished.equals("moderator") ? modmsgsb : msgsb) (distinguished != null && distinguished.equals("moderator") ? modmsgsb : msgsb)
.append("A new post was submitted to the subreddit by ").append(author).append("\n") .append("A new post was submitted to the subreddit by ").append(author).append("\n")
.append(permalink).append("\n"); .append(permalink).append("\n");
lastanntime = date; lastanntime = date;
} }
} }
if (msgsb.length() > 0) if (msgsb.length() > 0)
genchannel.pin(sendMessageToChannelWait(genchannel, msgsb.toString())); genchannel.pin(sendMessageToChannelWait(genchannel, msgsb.toString()));
if (modmsgsb.length() > 0) if (modmsgsb.length() > 0)
sendMessageToChannel(annchannel, modmsgsb.toString()); sendMessageToChannel(annchannel, modmsgsb.toString());
if (lastannouncementtime != lastanntime) { if (lastannouncementtime != lastanntime) {
lastannouncementtime = lastanntime; // If sending succeeded lastannouncementtime = lastanntime; // If sending succeeded
getConfig().set("lastannouncementtime", lastannouncementtime); getConfig().set("lastannouncementtime", lastannouncementtime);
getConfig().set("lastseentime", lastseentime); getConfig().set("lastseentime", lastseentime);
saveConfig(); saveConfig();
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
try { try {
Thread.sleep(10000); Thread.sleep(10000);
} catch (InterruptedException ex) { } catch (InterruptedException ex) {
Thread.currentThread().interrupt(); 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);
} }
public static void sendMessageToChannel(IChannel channel, String message, EmbedObject embed) { public static void sendMessageToChannel(IChannel channel, String message, EmbedObject embed) {
sendMessageToChannel(channel, message, embed, false); sendMessageToChannel(channel, message, embed, false);
} }
public static IMessage sendMessageToChannelWait(IChannel channel, String message) { public static IMessage sendMessageToChannelWait(IChannel channel, String message) {
return sendMessageToChannelWait(channel, message, null); return sendMessageToChannelWait(channel, message, null);
} }
public static IMessage sendMessageToChannelWait(IChannel channel, String message, EmbedObject embed) { public static IMessage sendMessageToChannelWait(IChannel channel, String message, EmbedObject embed) {
return sendMessageToChannel(channel, message, embed, true); return sendMessageToChannel(channel, message, embed, true);
} }
private static IMessage sendMessageToChannel(IChannel channel, String message, EmbedObject embed, boolean wait) { private static IMessage sendMessageToChannel(IChannel channel, String message, EmbedObject embed, boolean wait) {
if (message.length() > 1900) { if (message.length() > 1900) {
message = message.substring(0, 1900); message = message.substring(0, 1900);
Bukkit.getLogger() Bukkit.getLogger()
.warning("Message was too long to send to discord and got truncated. In " + channel.getName()); .warning("Message was too long to send to discord and got truncated. In " + channel.getName());
} }
try { try {
if (channel == chatchannel) if (channel == chatchannel)
MCChatListener.resetLastMessage(); // If this is a chat message, it'll be set again MCChatListener.resetLastMessage(); // If this is a chat message, it'll be set again
else if (channel.isPrivate()) else if (channel.isPrivate())
MCChatListener.resetLastMessage(channel); MCChatListener.resetLastMessage(channel);
final String content = message; final String content = message;
RequestBuffer.IRequest<IMessage> r = () -> embed == null ? channel.sendMessage(content) RequestBuffer.IRequest<IMessage> r = () -> embed == null ? channel.sendMessage(content)
: channel.sendMessage(content, embed, false); : channel.sendMessage(content, embed, false);
if (wait) if (wait)
return DPUtils.perform(r); return DPUtils.perform(r);
else { else {
DPUtils.performNoWait(r); DPUtils.performNoWait(r);
return null; return null;
} }
} catch (Exception e) { } catch (Exception e) {
Bukkit.getLogger().warning( Bukkit.getLogger().warning(
"Failed to deliver message to Discord! Channel: " + channel.getName() + " Message: " + message); "Failed to deliver message to Discord! Channel: " + channel.getName() + " Message: " + message);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public static Permission perms; public static Permission perms;
public boolean setupProviders() { public boolean setupProviders() {
try { try {
Class.forName("net.milkbowl.vault.permission.Permission"); Class.forName("net.milkbowl.vault.permission.Permission");
Class.forName("net.milkbowl.vault.chat.Chat"); Class.forName("net.milkbowl.vault.chat.Chat");
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
return false; return false;
} }
RegisteredServiceProvider<Permission> permsProvider = Bukkit.getServer().getServicesManager() RegisteredServiceProvider<Permission> permsProvider = Bukkit.getServer().getServicesManager()
.getRegistration(Permission.class); .getRegistration(Permission.class);
perms = permsProvider.getProvider(); perms = permsProvider.getProvider();
return perms != null; return perms != null;
} }
} }

View file

@ -1,14 +1,15 @@
package buttondevteam.discordplugin.commands; package buttondevteam.discordplugin.commands;
import java.util.List;
import java.util.stream.Collectors;
import buttondevteam.discordplugin.DPUtils; import buttondevteam.discordplugin.DPUtils;
import buttondevteam.discordplugin.DiscordPlugin; import buttondevteam.discordplugin.DiscordPlugin;
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;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class RoleCommand extends DiscordCommandBase { public class RoleCommand extends DiscordCommandBase {
@Override @Override
@ -50,20 +51,18 @@ public class RoleCommand extends DiscordCommandBase {
DiscordPlugin.sendMessageToChannel(message.getChannel(), DiscordPlugin.sendMessageToChannel(message.getChannel(),
"List of game roles:\n" + DiscordPlugin.GameRoles.stream().collect(Collectors.joining("\n"))); "List of game roles:\n" + DiscordPlugin.GameRoles.stream().collect(Collectors.joining("\n")));
} else if (argsa[0].equalsIgnoreCase("admin") && argsa.length > 1 && argsa[1].equalsIgnoreCase("addrole")) { } else if (argsa[0].equalsIgnoreCase("admin") && argsa.length > 1 && argsa[1].equalsIgnoreCase("addrole")) {
if (!message.getAuthor().getRolesForGuild(DiscordPlugin.mainServer).stream() if (message.getAuthor().getRolesForGuild(DiscordPlugin.mainServer).stream()
.anyMatch(r -> r.getLongID() == 126030201472811008L)) { .noneMatch(r -> r.getLongID() == 126030201472811008L)) {
DiscordPlugin.sendMessageToChannel(message.getChannel(), DiscordPlugin.sendMessageToChannel(message.getChannel(),
"You need to be a moderator to use this command."); "You need to be a moderator to use this command.");
return; return;
} }
if (argsa.length < 2) { if (argsa.length < 3) {
DiscordPlugin.sendMessageToChannel(message.getChannel(), DiscordPlugin.sendMessageToChannel(message.getChannel(),
"Add a role to the game role list.\nUsage: " + argsa[0] + " <rolename>"); "Add a role to the game role list.\nUsage: " + argsa[0] + " <rolename>");
return; return;
} }
String rolename = argsa[1]; String rolename = Arrays.stream(argsa).skip(2).collect(Collectors.joining(" "));
for (int i = 2; i < argsa.length; i++)
rolename += " " + argsa[i];
final List<IRole> roles = (TBMCCoreAPI.IsTestServer() ? DiscordPlugin.devServer : DiscordPlugin.mainServer) final List<IRole> roles = (TBMCCoreAPI.IsTestServer() ? DiscordPlugin.devServer : DiscordPlugin.mainServer)
.getRolesByName(rolename); .getRolesByName(rolename);
if (roles.size() == 0) { if (roles.size() == 0) {

View file

@ -1,12 +1,17 @@
package buttondevteam.discordplugin.listeners; package buttondevteam.discordplugin.listeners;
import java.awt.Color; import buttondevteam.discordplugin.*;
import java.util.*; import buttondevteam.discordplugin.playerfaker.VanillaCommandListener;
import java.util.concurrent.LinkedBlockingQueue; import buttondevteam.lib.TBMCChatEvent;
import java.util.function.*; import buttondevteam.lib.TBMCChatPreprocessEvent;
import java.util.stream.Collectors; import buttondevteam.lib.TBMCCoreAPI;
import java.util.stream.Stream; import buttondevteam.lib.TBMCSystemChatEvent;
import buttondevteam.lib.chat.Channel;
import buttondevteam.lib.chat.ChatRoom;
import buttondevteam.lib.chat.TBMCChatAPI;
import buttondevteam.lib.player.TBMCPlayer;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@ -14,21 +19,29 @@ import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import buttondevteam.discordplugin.*;
import buttondevteam.discordplugin.playerfaker.VanillaCommandListener;
import buttondevteam.lib.*;
import buttondevteam.lib.chat.Channel;
import buttondevteam.lib.chat.ChatRoom;
import buttondevteam.lib.chat.TBMCChatAPI;
import buttondevteam.lib.player.TBMCPlayer;
import lombok.RequiredArgsConstructor;
import lombok.val;
import sx.blah.discord.api.events.IListener; import sx.blah.discord.api.events.IListener;
import sx.blah.discord.api.internal.json.objects.EmbedObject; 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.impl.events.guild.channel.message.MessageReceivedEvent;
import sx.blah.discord.handle.obj.*; import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.util.*; import sx.blah.discord.handle.obj.IMessage;
import sx.blah.discord.handle.obj.IPrivateChannel;
import sx.blah.discord.handle.obj.IUser;
import sx.blah.discord.util.DiscordException;
import sx.blah.discord.util.EmbedBuilder;
import sx.blah.discord.util.MissingPermissionsException;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Optional;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MCChatListener implements Listener, IListener<MessageReceivedEvent> { public class MCChatListener implements Listener, IListener<MessageReceivedEvent> {
private BukkitTask sendtask; private BukkitTask sendtask;
@ -65,7 +78,7 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
DPUtils.embedWithHead( DPUtils.embedWithHead(
embed.withAuthorUrl("https://tbmcplugins.github.io/profile.html?type=minecraft&id=" embed.withAuthorUrl("https://tbmcplugins.github.io/profile.html?type=minecraft&id="
+ ((Player) e.getSender()).getUniqueId()), + ((Player) e.getSender()).getUniqueId()),
((Player) e.getSender()).getName()); e.getSender().getName());
else if (e.getSender() instanceof DiscordSenderBase) else if (e.getSender() instanceof DiscordSenderBase)
embed.withAuthorIcon(((DiscordSenderBase) e.getSender()).getUser().getAvatarURL()) embed.withAuthorIcon(((DiscordSenderBase) e.getSender()).getUser().getAvatarURL())
.withAuthorUrl("https://tbmcplugins.github.io/profile.html?type=discord&id=" .withAuthorUrl("https://tbmcplugins.github.io/profile.html?type=discord&id="