Merge pull request #28 from TBMCPlugins/dev

Added mute support, fixed chat msg removal, added a bit more support for mentions, fixes etc.
This commit is contained in:
Norbi Peti 2017-05-15 02:43:08 +02:00 committed by GitHub
commit b828ccf491
14 changed files with 276 additions and 200 deletions

View file

@ -76,29 +76,29 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
try { try {
task = Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> { task = Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> {
if (mainServer == null || devServer == null) { if (mainServer == null || devServer == null) {
mainServer = event.getClient().getGuildByID("125813020357165056"); mainServer = event.getClient().getGuildByID(125813020357165056L);
devServer = event.getClient().getGuildByID("219529124321034241"); devServer = event.getClient().getGuildByID(219529124321034241L);
} }
if (mainServer == null || devServer == null) if (mainServer == null || devServer == null)
return; // Retry return; // Retry
if (!TBMCCoreAPI.IsTestServer()) { if (!TBMCCoreAPI.IsTestServer()) {
botchannel = mainServer.getChannelByID("209720707188260864"); // bot botchannel = mainServer.getChannelByID(209720707188260864L); // bot
annchannel = mainServer.getChannelByID("126795071927353344"); // announcements annchannel = mainServer.getChannelByID(126795071927353344L); // announcements
genchannel = mainServer.getChannelByID("125813020357165056"); // general genchannel = mainServer.getChannelByID(125813020357165056L); // general
chatchannel = mainServer.getChannelByID("249663564057411596"); // minecraft_chat chatchannel = mainServer.getChannelByID(249663564057411596L); // minecraft_chat
botroomchannel = devServer.getChannelByID("239519012529111040"); // bot-room botroomchannel = devServer.getChannelByID(239519012529111040L); // bot-room
officechannel = devServer.getChannelByID("219626707458457603"); // developers-office officechannel = devServer.getChannelByID(219626707458457603L); // developers-office
updatechannel = devServer.getChannelByID("233724163519414272"); // server-updates updatechannel = devServer.getChannelByID(233724163519414272L); // server-updates
dc.changeStatus(Status.game("on TBMC")); dc.online("on TBMC");
} else { } else {
botchannel = devServer.getChannelByID("239519012529111040"); // bot-room botchannel = devServer.getChannelByID(239519012529111040L); // bot-room
annchannel = botchannel; // bot-room annchannel = botchannel; // bot-room
genchannel = botchannel; // bot-room genchannel = botchannel; // bot-room
botroomchannel = botchannel;// bot-room botroomchannel = botchannel;// bot-room
chatchannel = botchannel;// bot-room chatchannel = botchannel;// bot-room
officechannel = devServer.getChannelByID("219626707458457603"); // developers-office officechannel = devServer.getChannelByID(219626707458457603L); // developers-office
updatechannel = botchannel; updatechannel = botchannel;
dc.changeStatus(Status.game("testing")); dc.online("testing");
} }
if (botchannel == null || annchannel == null || genchannel == null || botroomchannel == null if (botchannel == null || annchannel == null || genchannel == null || botroomchannel == null
|| chatchannel == null || officechannel == null || updatechannel == null) || chatchannel == null || officechannel == null || updatechannel == null)
@ -155,7 +155,7 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
sendMessageToChannel(chatchannel, "", new EmbedBuilder().withColor(Restart ? Color.ORANGE : Color.RED) sendMessageToChannel(chatchannel, "", new EmbedBuilder().withColor(Restart ? Color.ORANGE : Color.RED)
.withTitle(Restart ? "Server restarting" : "Server stopping").build()); .withTitle(Restart ? "Server restarting" : "Server stopping").build());
try { try {
dc.changeStatus(Status.game("on TBMC")); dc.online("on TBMC");
dc.logout(); dc.logout();
} catch (Exception e) { } catch (Exception e) {
TBMCCoreAPI.SendException("An error occured while disabling DiscordPlugin!", e); TBMCCoreAPI.SendException("An error occured while disabling DiscordPlugin!", e);

View file

@ -37,10 +37,10 @@ public class ConnectCommand extends DiscordCommandBase {
"Too many arguments.\nUsage: connect <Minecraftname>"); "Too many arguments.\nUsage: connect <Minecraftname>");
return; return;
} }
if (WaitingToConnect.inverse().containsKey(message.getAuthor().getID())) { if (WaitingToConnect.inverse().containsKey(message.getAuthor().getStringID())) {
DiscordPlugin.sendMessageToChannel(message.getChannel(), DiscordPlugin.sendMessageToChannel(message.getChannel(),
"Replacing " + WaitingToConnect.inverse().get(message.getAuthor().getID()) + " with " + args); "Replacing " + WaitingToConnect.inverse().get(message.getAuthor().getStringID()) + " with " + args);
WaitingToConnect.inverse().remove(message.getAuthor().getID()); WaitingToConnect.inverse().remove(message.getAuthor().getStringID());
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
OfflinePlayer p = Bukkit.getOfflinePlayer(args); OfflinePlayer p = Bukkit.getOfflinePlayer(args);
@ -50,7 +50,7 @@ public class ConnectCommand extends DiscordCommandBase {
} }
try (TBMCPlayer pl = TBMCPlayerBase.getPlayer(p.getUniqueId(), TBMCPlayer.class)) { try (TBMCPlayer pl = TBMCPlayerBase.getPlayer(p.getUniqueId(), TBMCPlayer.class)) {
DiscordPlayer dp = pl.getAs(DiscordPlayer.class); DiscordPlayer dp = pl.getAs(DiscordPlayer.class);
if (dp != null && message.getAuthor().getID().equals(dp.getDiscordID())) { if (dp != null && message.getAuthor().getStringID().equals(dp.getDiscordID())) {
DiscordPlugin.sendMessageToChannel(message.getChannel(), "You already have this account connected."); DiscordPlugin.sendMessageToChannel(message.getChannel(), "You already have this account connected.");
return; return;
} }
@ -58,7 +58,7 @@ public class ConnectCommand extends DiscordCommandBase {
TBMCCoreAPI.SendException("An error occured while connecting a Discord account!", e); TBMCCoreAPI.SendException("An error occured while connecting a Discord account!", e);
DiscordPlugin.sendMessageToChannel(message.getChannel(), "An internal error occured!\n" + e); DiscordPlugin.sendMessageToChannel(message.getChannel(), "An internal error occured!\n" + e);
} }
WaitingToConnect.put(p.getName(), message.getAuthor().getID()); WaitingToConnect.put(p.getName(), message.getAuthor().getStringID());
DiscordPlugin.sendMessageToChannel(message.getChannel(), DiscordPlugin.sendMessageToChannel(message.getChannel(),
"Pending connection - accept connection in Minecraft from the account " + args "Pending connection - accept connection in Minecraft from the account " + args
+ " before the server gets restarted. You can also adjust the Minecraft name you want to connect to with the same command."); + " before the server gets restarted. You can also adjust the Minecraft name you want to connect to with the same command.");

View file

@ -50,7 +50,7 @@ public class RoleCommand extends DiscordCommandBase {
"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("addrole")) { } else if (argsa[0].equalsIgnoreCase("addrole")) {
if (!message.getAuthor().getRolesForGuild(DiscordPlugin.mainServer).stream() if (!message.getAuthor().getRolesForGuild(DiscordPlugin.mainServer).stream()
.anyMatch(r -> r.getName().equals("Moderator"))) { .anyMatch(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;

View file

@ -30,7 +30,7 @@ public class UserinfoCommand extends DiscordCommandBase {
target = message.getAuthor(); target = message.getAuthor();
else { else {
final Optional<IUser> firstmention = message.getMentions().stream() final Optional<IUser> firstmention = message.getMentions().stream()
.filter(m -> !m.getID().equals(DiscordPlugin.dc.getOurUser().getID())).findFirst(); .filter(m -> !m.getStringID().equals(DiscordPlugin.dc.getOurUser().getStringID())).findFirst();
if (firstmention.isPresent()) if (firstmention.isPresent())
target = firstmention.get(); target = firstmention.get();
else if (args.contains("#")) { else if (args.contains("#")) {
@ -68,7 +68,7 @@ public class UserinfoCommand extends DiscordCommandBase {
target = targets.get(0); target = targets.get(0);
} }
} }
try (DiscordPlayer dp = ChromaGamerBase.getUser(target.getID(), DiscordPlayer.class)) { try (DiscordPlayer dp = ChromaGamerBase.getUser(target.getStringID(), DiscordPlayer.class)) {
StringBuilder uinfo = new StringBuilder("User info for ").append(target.getName()).append(":\n"); StringBuilder uinfo = new StringBuilder("User info for ").append(target.getName()).append(":\n");
uinfo.append(dp.getInfo(InfoTarget.Discord)); uinfo.append(dp.getInfo(InfoTarget.Discord));
DiscordPlugin.sendMessageToChannel(message.getChannel(), uinfo.toString()); DiscordPlugin.sendMessageToChannel(message.getChannel(), uinfo.toString());

View file

@ -7,7 +7,7 @@ import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.DiscordSender; import buttondevteam.discordplugin.DiscordSender;
import buttondevteam.lib.TBMCCoreAPI; import buttondevteam.lib.TBMCCoreAPI;
import sx.blah.discord.api.events.IListener; import sx.blah.discord.api.events.IListener;
import sx.blah.discord.handle.impl.events.MessageReceivedEvent; import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
import sx.blah.discord.handle.obj.IEmbed; import sx.blah.discord.handle.obj.IEmbed;
import sx.blah.discord.util.EmbedBuilder; import sx.blah.discord.util.EmbedBuilder;
@ -16,13 +16,13 @@ public class AutoUpdaterListener implements IListener<MessageReceivedEvent> {
public void handle(MessageReceivedEvent event) { public void handle(MessageReceivedEvent event) {
if (DiscordPlugin.SafeMode) if (DiscordPlugin.SafeMode)
return; return;
if (!event.getMessage().getChannel().getID().equals(DiscordPlugin.officechannel.getID())) if (!event.getMessage().getChannel().getStringID().equals(DiscordPlugin.officechannel.getStringID()))
return; return;
if (!"239123781401051138".equals(event.getMessage().getWebhookID())) if (239123781401051138L != event.getMessage().getWebhookLongID())
return; return;
if (event.getMessage().getEmbedded().size() == 0) if (event.getMessage().getEmbeds().size() == 0)
return; return;
final IEmbed embed = event.getMessage().getEmbedded().get(0); final IEmbed embed = event.getMessage().getEmbeds().get(0);
final String title = embed.getTitle(); final String title = embed.getTitle();
if (!title.contains("new commit")) if (!title.contains("new commit"))
return; return;

View file

@ -1,15 +1,37 @@
package buttondevteam.discordplugin.listeners; package buttondevteam.discordplugin.listeners;
import java.util.ArrayList;
import java.util.Random;
import buttondevteam.discordplugin.DiscordPlugin; import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.commands.DiscordCommandBase; import buttondevteam.discordplugin.commands.DiscordCommandBase;
import sx.blah.discord.api.events.IListener; import sx.blah.discord.api.events.IListener;
import sx.blah.discord.handle.impl.events.MentionEvent; import sx.blah.discord.handle.impl.events.guild.channel.message.MentionEvent;
import sx.blah.discord.handle.impl.events.MessageReceivedEvent; import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.handle.obj.IMessage;
public class CommandListener { public class CommandListener {
private static final String[] serverReadyStrings = new String[] { "In one week from now", // Ali
"Between now and the heat-death of the universe.", // Ghostise
"Soon™", "Ask again this time next month", // Ghostise
"In about 3 seconds", // Nicolai
};
private static final Random serverReadyRandom = new Random();
private static final ArrayList<Short> usableServerReadyStrings = new ArrayList<Short>(serverReadyStrings.length) {
private static final long serialVersionUID = 2213771460909848770L;
{
createUsableServerReadyStrings(this);
}
};
private static void createUsableServerReadyStrings(ArrayList<Short> list) {
for (short i = 0; i < serverReadyStrings.length; i++)
list.add(i);
}
public static IListener<?>[] getListeners() { public static IListener<?>[] getListeners() {
return new IListener[] { new IListener<MentionEvent>() { return new IListener[] { new IListener<MentionEvent>() {
@Override @Override
@ -19,9 +41,9 @@ public class CommandListener {
if (event.getMessage().getAuthor().isBot()) if (event.getMessage().getAuthor().isBot())
return; return;
final IChannel channel = event.getMessage().getChannel(); final IChannel channel = event.getMessage().getChannel();
if (!channel.getID().equals(DiscordPlugin.botchannel.getID()) && !channel.isPrivate()) if (!channel.getStringID().equals(DiscordPlugin.botchannel.getStringID()) && !channel.isPrivate())
return; return;
if (channel.getID().equals(DiscordPlugin.chatchannel.getID())) if (channel.getStringID().equals(DiscordPlugin.chatchannel.getStringID()))
return; // The chat code already handles this - Right now while testing botchannel is the same as chatchannel return; // The chat code already handles this - Right now while testing botchannel is the same as chatchannel
runCommand(event.getMessage(), true); runCommand(event.getMessage(), true);
} }
@ -30,6 +52,18 @@ public class CommandListener {
public void handle(MessageReceivedEvent event) { public void handle(MessageReceivedEvent event) {
if (DiscordPlugin.SafeMode) if (DiscordPlugin.SafeMode)
return; return;
if (event.getMessage().getContent().toLowerCase().contains("when will the server be open?")) {
int next;
/*
* if (serverReadyStrings.length <= lastServerReadyStrings.size()) { next = lastServerReadyStrings.get(0); lastServerReadyStrings.clear(); } else { next = (short) serverReadyRandom
* .nextInt(serverReadyStrings.length - lastServerReadyStrings.size()); for (short i = 0; i < lastServerReadyStrings.size(); i++) { short j = lastServerReadyStrings.get(i); if
* (next == j) next++; if (next >= serverReadyStrings.length) next = 0; } lastServerReadyStrings.add(next); }
*/
if (usableServerReadyStrings.size() == 0)
createUsableServerReadyStrings(usableServerReadyStrings);
next = usableServerReadyStrings.remove(serverReadyRandom.nextInt(usableServerReadyStrings.size()));
DiscordPlugin.sendMessageToChannel(event.getMessage().getChannel(), serverReadyStrings[next]);
}
if (!event.getMessage().getChannel().isPrivate()) if (!event.getMessage().getChannel().isPrivate())
return; return;
if (event.getMessage().getAuthor().isBot()) if (event.getMessage().getAuthor().isBot())

View file

@ -7,7 +7,7 @@ import buttondevteam.lib.TBMCDebugMessageEvent;
public class DebugMessageListener implements Listener{ public class DebugMessageListener implements Listener{
@EventHandler @EventHandler
public void onException(TBMCDebugMessageEvent e) { public void onDebugMessage(TBMCDebugMessageEvent e) {
SendMessage(e.getDebugMessage()); SendMessage(e.getDebugMessage());
e.setSent(); e.setSent();
} }

View file

@ -48,7 +48,7 @@ public class ExceptionListener implements Listener {
sb.append(sourcemessage).append("\n"); sb.append(sourcemessage).append("\n");
sb.append("```").append("\n"); sb.append("```").append("\n");
String stackTrace = Arrays.stream(ExceptionUtils.getStackTrace(e).split("\\n")) String stackTrace = Arrays.stream(ExceptionUtils.getStackTrace(e).split("\\n"))
.filter(s -> !(s.contains(" at ") && ( // .filter(s -> !(s.contains("\tat ") && ( //
s.contains("java.util") // s.contains("java.util") //
|| s.contains("java.lang") // || s.contains("java.lang") //
|| s.contains("net.minecraft.server") // || s.contains("net.minecraft.server") //

View file

@ -2,7 +2,6 @@ package buttondevteam.discordplugin.listeners;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -17,7 +16,7 @@ import buttondevteam.lib.player.ChromaGamerBase;
import buttondevteam.lib.player.TBMCPlayer; import buttondevteam.lib.player.TBMCPlayer;
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.MessageReceivedEvent; import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
import sx.blah.discord.handle.obj.*; import sx.blah.discord.handle.obj.*;
import sx.blah.discord.util.*; import sx.blah.discord.util.*;
@ -28,7 +27,9 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
return; return;
if (e.getSender() instanceof DiscordSender || e.getSender() instanceof DiscordPlayerSender) if (e.getSender() instanceof DiscordSender || e.getSender() instanceof DiscordPlayerSender)
return; return;
if (e.getChannel().equals(Channel.GlobalChat)) { if (!e.getChannel().equals(Channel.GlobalChat))
return;
synchronized (this) {
final String authorPlayer = DiscordPlugin.sanitizeString(e.getSender() instanceof Player // final String authorPlayer = DiscordPlugin.sanitizeString(e.getSender() instanceof Player //
? ((Player) e.getSender()).getDisplayName() // ? ((Player) e.getSender()).getDisplayName() //
: e.getSender().getName()); : e.getSender().getName());
@ -39,14 +40,14 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
: embed.build(); : embed.build();
final long nanoTime = System.nanoTime(); final long nanoTime = System.nanoTime();
if (lastmessage == null || lastmessage.isDeleted() if (lastmessage == null || lastmessage.isDeleted()
|| !authorPlayer.equals(lastmessage.getEmbedded().get(0).getAuthor().getName()) || !authorPlayer.equals(lastmessage.getEmbeds().get(0).getAuthor().getName())
|| lastmsgtime / 1000000000f < nanoTime / 1000000000f - 120) { || lastmsgtime / 1000000000f < nanoTime / 1000000000f - 120) {
lastmessage = DiscordPlugin.sendMessageToChannel(DiscordPlugin.chatchannel, "", embedObject); lastmessage = DiscordPlugin.sendMessageToChannel(DiscordPlugin.chatchannel, "", embedObject);
lastmsgtime = nanoTime; lastmsgtime = nanoTime;
lastmsg = e.getMessage();
} else } else
try { try {
embedObject.description = lastmessage.getEmbedded().get(0).getDescription() + "\n" lastmsg = embedObject.description = lastmsg + "\n" + embedObject.description;
+ embedObject.description;
DiscordPlugin.perform(() -> lastmessage.edit("", embedObject)); DiscordPlugin.perform(() -> lastmessage.edit("", embedObject));
} catch (MissingPermissionsException | DiscordException e1) { } catch (MissingPermissionsException | DiscordException e1) {
TBMCCoreAPI.SendException("An error occured while editing chat message!", e1); TBMCCoreAPI.SendException("An error occured while editing chat message!", e1);
@ -54,11 +55,39 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
} // TODO: Author URL } // TODO: Author URL
} }
@EventHandler
public void onChatPreprocess(TBMCChatPreprocessEvent event) {
int start = -1;
// System.out.println("A");
while ((start = event.getMessage().indexOf('@', start + 1)) != -1) {
// System.out.println("Start: " + start);
int mid = event.getMessage().indexOf('#', start + 1);
// System.out.println("Mid: " + mid);
if (mid == -1)
return;
int end_ = event.getMessage().indexOf(' ', mid + 1);
// System.out.println("End: " + end_);
if (end_ == -1)
end_ = event.getMessage().length();
final int end = end_;
final int startF = start;
// System.out.println("Name: " + event.getMessage().substring(start, mid));
// System.out.println("Disc: " + event.getMessage().substring(mid, end));
DiscordPlugin.dc.getUsersByName(event.getMessage().substring(start + 1, mid)).stream()
.filter(u -> u.getDiscriminator().equals(event.getMessage().substring(mid + 1, end))).findAny()
.ifPresent(user -> event.setMessage(event.getMessage().substring(0, startF) + "@" + user.getName()
+ (event.getMessage().length() > end ? event.getMessage().substring(end)
: ""))); // TODO: Add formatting
start = end; // Skip any @s inside the mention
}
}
private static final String[] UnconnectedCmds = new String[] { "list", "u", "shrug", "tableflip", "unflip", "mwiki", private static final String[] UnconnectedCmds = new String[] { "list", "u", "shrug", "tableflip", "unflip", "mwiki",
"yeehaw" }; "yeehaw" };
private static IMessage lastmessage = null; private static IMessage lastmessage = null;
private static long lastmsgtime = 0; private static long lastmsgtime = 0;
private static String lastmsg;
private static short lastlist = 0; private static short lastlist = 0;
private static short lastlistp = 0; private static short lastlistp = 0;
@ -71,9 +100,9 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
} }
@Override // Discord @Override // Discord
public void handle(MessageReceivedEvent event) { public void handle(sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent event) {
final IUser author = event.getMessage().getAuthor(); final IUser author = event.getMessage().getAuthor();
if (!event.getMessage().getChannel().getID().equals(DiscordPlugin.chatchannel.getID()) if (!event.getMessage().getChannel().getStringID().equals(DiscordPlugin.chatchannel.getStringID())
/* && !(event.getMessage().getChannel().isPrivate() && privatechat) */) /* && !(event.getMessage().getChannel().isPrivate() && privatechat) */)
return; return;
lastmessage = null; lastmessage = null;
@ -83,35 +112,36 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
if (CommandListener.runCommand(event.getMessage(), true)) if (CommandListener.runCommand(event.getMessage(), true))
return; return;
String dmessage = event.getMessage().getContent(); String dmessage = event.getMessage().getContent();
synchronized (this) {
try { try {
DiscordPlayer dp = ChromaGamerBase.getUser(author.getID(), DiscordPlayer.class); DiscordPlayer dp = ChromaGamerBase.getUser(author.getStringID(), DiscordPlayer.class);
final DiscordSenderBase dsender; final DiscordSenderBase dsender;
Player mcp = null; // Offline players can't really run commands Player mcp = null; // Offline players can't really run commands
final String cid; final String cid;
if ((cid = dp.getConnectedID(TBMCPlayer.class)) != null // Connected? if ((cid = dp.getConnectedID(TBMCPlayer.class)) != null // Connected?
&& (mcp = Bukkit.getPlayer(cid)) != null) { // Execute as ingame player, if online && (mcp = Bukkit.getPlayer(cid)) != null) { // Execute as ingame player, if online
if (!ConnectedSenders.containsKey(author.getID())) if (!ConnectedSenders.containsKey(author.getStringID()))
ConnectedSenders.put(author.getID(), ConnectedSenders.put(author.getStringID(),
new DiscordPlayerSender(author, event.getMessage().getChannel(), mcp)); new DiscordPlayerSender(author, event.getMessage().getChannel(), mcp));
dsender = ConnectedSenders.get(author.getID()); dsender = ConnectedSenders.get(author.getStringID());
} else { } else {
TBMCPlayer p = dp.getAs(TBMCPlayer.class); TBMCPlayer p = dp.getAs(TBMCPlayer.class);
if (!UnconnectedSenders.containsKey(author.getID())) if (!UnconnectedSenders.containsKey(author.getStringID()))
UnconnectedSenders.put(author.getID(), new DiscordSender(author, event.getMessage().getChannel(), UnconnectedSenders.put(author.getStringID(), new DiscordSender(author,
p == null ? null : p.PlayerName().get())); // Display the playername, if found event.getMessage().getChannel(), p == null ? null : p.PlayerName().get())); // Display the playername, if found
dsender = UnconnectedSenders.get(author.getID()); dsender = UnconnectedSenders.get(author.getStringID());
} }
for (IUser u : event.getMessage().getMentions()) { for (IUser u : event.getMessage().getMentions()) {
dmessage = dmessage.replace(u.mention(false), "@" + u.getName()); // TODO: IG Formatting dmessage = dmessage.replace(u.mention(false), "@" + u.getName()); // TODO: IG Formatting
final Optional<String> nick = u.getNicknameForGuild(DiscordPlugin.mainServer); final String nick = u.getNicknameForGuild(DiscordPlugin.mainServer);
dmessage = dmessage.replace(u.mention(true), "@" + (nick.isPresent() ? nick.get() : u.getName())); dmessage = dmessage.replace(u.mention(true), "@" + (nick != null ? nick : u.getName()));
} }
if (dmessage.startsWith("/")) { if (dmessage.startsWith("/")) {
final String cmd = dmessage.substring(1).toLowerCase(); final String cmd = dmessage.substring(1).toLowerCase();
if (mcp == null if (mcp == null && !Arrays.stream(UnconnectedCmds)
&& !Arrays.stream(UnconnectedCmds).anyMatch(s -> cmd.equals(s) || cmd.startsWith(s + " "))) { .anyMatch(s -> cmd.equals(s) || cmd.startsWith(s + " "))) {
// Command not whitelisted // Command not whitelisted
DiscordPlugin.sendMessageToChannel(event.getMessage().getChannel(), // TODO DiscordPlugin.sendMessageToChannel(event.getMessage().getChannel(), // TODO
"Sorry, you need to be online on the server and have your accounts connected, you can only access these commands:\n" "Sorry, you need to be online on the server and have your accounts connected, you can only access these commands:\n"
@ -139,9 +169,9 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
dmessage + (event.getMessage().getAttachments().size() > 0 ? "\n" + event.getMessage() dmessage + (event.getMessage().getAttachments().size() > 0 ? "\n" + event.getMessage()
.getAttachments().stream().map(a -> a.getUrl()).collect(Collectors.joining("\n")) .getAttachments().stream().map(a -> a.getUrl()).collect(Collectors.joining("\n"))
: "")); : ""));
event.getMessage().getChannel().getMessages().stream().forEach(m -> { event.getMessage().getChannel().getMessageHistory().stream().forEach(m -> {
try { try {
final IReaction reaction = m.getReactionByName(DiscordPlugin.DELIVERED_REACTION); final IReaction reaction = m.getReactionByUnicode(DiscordPlugin.DELIVERED_REACTION);
if (reaction != null) if (reaction != null)
DiscordPlugin.perform(() -> m.removeReaction(reaction)); DiscordPlugin.perform(() -> m.removeReaction(reaction));
} catch (Exception e) { } catch (Exception e) {
@ -156,3 +186,4 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
} }
} }
} }
}

View file

@ -8,13 +8,18 @@ import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.server.ServerCommandEvent; import org.bukkit.event.server.ServerCommandEvent;
import com.earth2me.essentials.CommandSource;
import buttondevteam.discordplugin.DiscordPlayer; import buttondevteam.discordplugin.DiscordPlayer;
import buttondevteam.discordplugin.DiscordPlugin; import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.commands.ConnectCommand; import buttondevteam.discordplugin.commands.ConnectCommand;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.player.*; import buttondevteam.lib.player.*;
import net.ess3.api.events.*; import net.ess3.api.events.*;
import sx.blah.discord.handle.obj.IRole;
import sx.blah.discord.handle.obj.IUser; import sx.blah.discord.handle.obj.IUser;
import sx.blah.discord.handle.obj.Status.StatusType; import sx.blah.discord.util.DiscordException;
import sx.blah.discord.util.MissingPermissionsException;
public class MCListener implements Listener { public class MCListener implements Listener {
@EventHandler @EventHandler
@ -22,7 +27,7 @@ public class MCListener implements Listener {
final Player p = Bukkit.getPlayer(e.GetPlayer().getUUID()); final Player p = Bukkit.getPlayer(e.GetPlayer().getUUID());
if (ConnectCommand.WaitingToConnect.containsKey(e.GetPlayer().PlayerName().get())) { if (ConnectCommand.WaitingToConnect.containsKey(e.GetPlayer().PlayerName().get())) {
IUser user = DiscordPlugin.dc IUser user = DiscordPlugin.dc
.getUserByID(ConnectCommand.WaitingToConnect.get(e.GetPlayer().PlayerName().get())); .getUserByID(Long.parseLong(ConnectCommand.WaitingToConnect.get(e.GetPlayer().PlayerName().get())));
p.sendMessage("§bTo connect with the Discord account @" + user.getName() + "#" + user.getDiscriminator() p.sendMessage("§bTo connect with the Discord account @" + user.getName() + "#" + user.getDiscriminator()
+ " do /discord accept"); + " do /discord accept");
p.sendMessage("§bIf it wasn't you, do /discord decline"); p.sendMessage("§bIf it wasn't you, do /discord decline");
@ -43,20 +48,15 @@ public class MCListener implements Listener {
if (DiscordPlugin.SafeMode) if (DiscordPlugin.SafeMode)
return; return;
DiscordPlayer dp = e.getPlayer().getAs(DiscordPlayer.class); DiscordPlayer dp = e.getPlayer().getAs(DiscordPlayer.class);
/*System.out.println("dp: " + dp);
if (dp != null)
System.out.println("dp.did: " + dp.getDiscordID());*/
if (dp == null || dp.getDiscordID() == null || dp.getDiscordID() == "") if (dp == null || dp.getDiscordID() == null || dp.getDiscordID() == "")
return; return;
IUser user = DiscordPlugin.dc.getUserByID(dp.getDiscordID()); IUser user = DiscordPlugin.dc.getUserByID(Long.parseLong(dp.getDiscordID()));
e.addInfo("Discord tag: " + user.getName() + "#" + user.getDiscriminator()); e.addInfo("Discord tag: " + user.getName() + "#" + user.getDiscriminator());
if (!user.getStatus().getType().equals(StatusType.NONE)) { e.addInfo(user.getPresence().getStatus().toString());
if (user.getStatus().getType().equals(StatusType.GAME)) if (user.getPresence().getPlayingText().isPresent())
e.addInfo("Discord status: Playing " + user.getStatus().getStatusMessage()); e.addInfo("Playing " + user.getPresence().getPlayingText().get());
else if (user.getStatus().getType().equals(StatusType.STREAM)) else if (user.getPresence().getStreamingUrl().isPresent())
e.addInfo("Discord status: Streaming " + user.getStatus().getStatusMessage() + " - " e.addInfo("Streaming " + user.getPresence().getStreamingUrl().get());
+ user.getStatus().getUrl());
}
} }
@EventHandler(priority = EventPriority.LOW) @EventHandler(priority = EventPriority.LOW)
@ -66,6 +66,8 @@ public class MCListener implements Listener {
@EventHandler @EventHandler
public void onPlayerAFK(AfkStatusChangeEvent e) { public void onPlayerAFK(AfkStatusChangeEvent e) {
if (e.isCancelled())
return;
DiscordPlugin.sendMessageToChannel(DiscordPlugin.chatchannel, DiscordPlugin.sendMessageToChannel(DiscordPlugin.chatchannel,
DiscordPlugin.sanitizeString(e.getAffected().getBase().getDisplayName()) + " is " DiscordPlugin.sanitizeString(e.getAffected().getBase().getDisplayName()) + " is "
+ (e.getValue() ? "now" : "no longer") + " AFK."); + (e.getValue() ? "now" : "no longer") + " AFK.");
@ -76,7 +78,25 @@ public class MCListener implements Listener {
DiscordPlugin.Restart = !e.getCommand().equalsIgnoreCase("stop"); // The variable is always true except if stopped DiscordPlugin.Restart = !e.getCommand().equalsIgnoreCase("stop"); // The variable is always true except if stopped
} }
/* @EventHandler
* @EventHandler public void onPlayerMute(MuteStatusChangeEvent e) { e.getAffected() } public void onPlayerMute(MuteStatusChangeEvent e) {
*/ try {
DiscordPlugin.perform(() -> {
final IRole role = DiscordPlugin.dc.getRoleByID(164090010461667328L);
final CommandSource source = e.getAffected().getSource();
if (!source.isPlayer())
return;
final IUser user = DiscordPlugin.dc.getUserByID(
Long.parseLong(TBMCPlayerBase.getPlayer(source.getPlayer().getUniqueId(), TBMCPlayer.class)
.getAs(DiscordPlayer.class).getDiscordID())); // TODO: Use long
if (e.getValue())
user.addRole(role);
else
user.removeRole(role);
});
} catch (DiscordException | MissingPermissionsException ex) {
TBMCCoreAPI.SendException("Failed to give/take Muted role to player " + e.getAffected().getName() + "!",
ex);
}
}
} }

View file

@ -1,22 +1,18 @@
package buttondevteam.discordplugin.mccommands; package buttondevteam.discordplugin.mccommands;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import buttondevteam.discordplugin.DiscordPlayer; import buttondevteam.discordplugin.DiscordPlayer;
import buttondevteam.discordplugin.commands.ConnectCommand; import buttondevteam.discordplugin.commands.ConnectCommand;
import buttondevteam.discordplugin.listeners.MCChatListener; import buttondevteam.discordplugin.listeners.MCChatListener;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.player.ChromaGamerBase; import buttondevteam.lib.player.ChromaGamerBase;
import buttondevteam.lib.player.TBMCPlayer; import buttondevteam.lib.player.TBMCPlayer;
import buttondevteam.lib.player.TBMCPlayerBase; import buttondevteam.lib.player.TBMCPlayerBase;
@CommandClass(modOnly = false, path = "accept")
public class AcceptMCCommand extends DiscordMCCommandBase { public class AcceptMCCommand extends DiscordMCCommandBase {
@Override
public String GetDiscordCommandPath() {
return "accept";
}
@Override @Override
public String[] GetHelpText(String alias) { public String[] GetHelpText(String alias) {
return new String[] { // return new String[] { //
@ -28,30 +24,20 @@ public class AcceptMCCommand extends DiscordMCCommandBase {
} }
@Override @Override
public boolean GetModOnly() { public boolean OnCommand(Player player, String alias, String[] args) {
return false; String did = ConnectCommand.WaitingToConnect.get(player.getName());
}
@Override
public boolean GetPlayerOnly() {
return true;
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
String did = ConnectCommand.WaitingToConnect.get(sender.getName());
if (did == null) { if (did == null) {
sender.sendMessage("§cYou don't have a pending connection to Discord."); player.sendMessage("§cYou don't have a pending connection to Discord.");
return true; return true;
} }
DiscordPlayer dp = ChromaGamerBase.getUser(did, DiscordPlayer.class); DiscordPlayer dp = ChromaGamerBase.getUser(did, DiscordPlayer.class);
TBMCPlayer mcp = TBMCPlayerBase.getPlayer(((Player) sender).getUniqueId(), TBMCPlayer.class); TBMCPlayer mcp = TBMCPlayerBase.getPlayer(player.getUniqueId(), TBMCPlayer.class);
dp.connectWith(mcp); dp.connectWith(mcp);
dp.save(); dp.save();
mcp.save(); mcp.save();
ConnectCommand.WaitingToConnect.remove(sender.getName()); ConnectCommand.WaitingToConnect.remove(player.getName());
MCChatListener.UnconnectedSenders.remove(did); MCChatListener.UnconnectedSenders.remove(did);
sender.sendMessage("§bAccounts connected."); player.sendMessage("§bAccounts connected.");
return true; return true;
} }

View file

@ -1,15 +1,13 @@
package buttondevteam.discordplugin.mccommands; package buttondevteam.discordplugin.mccommands;
import org.bukkit.command.CommandSender; import org.bukkit.entity.Player;
import buttondevteam.discordplugin.commands.ConnectCommand; import buttondevteam.discordplugin.commands.ConnectCommand;
import buttondevteam.lib.chat.CommandClass;
@CommandClass(modOnly = false, path = "decline")
public class DeclineMCCommand extends DiscordMCCommandBase { public class DeclineMCCommand extends DiscordMCCommandBase {
@Override
public String GetDiscordCommandPath() {
return "decline";
}
@Override @Override
public String[] GetHelpText(String alias) { public String[] GetHelpText(String alias) {
return new String[] { // return new String[] { //
@ -21,23 +19,13 @@ public class DeclineMCCommand extends DiscordMCCommandBase {
} }
@Override @Override
public boolean GetModOnly() { public boolean OnCommand(Player player, String alias, String[] args) {
return false; String did = ConnectCommand.WaitingToConnect.remove(player.getName());
}
@Override
public boolean GetPlayerOnly() {
return true;
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
String did = ConnectCommand.WaitingToConnect.remove(sender.getName());
if (did == null) { if (did == null) {
sender.sendMessage("§cYou don't have a pending connection to Discord."); player.sendMessage("§cYou don't have a pending connection to Discord.");
return true; return true;
} }
sender.sendMessage("§bPending connection declined."); player.sendMessage("§bPending connection declined.");
return true; return true;
} }

View file

@ -1,14 +1,9 @@
package buttondevteam.discordplugin.mccommands; package buttondevteam.discordplugin.mccommands;
import buttondevteam.lib.chat.TBMCCommandBase; import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.PlayerCommandBase;
public abstract class DiscordMCCommandBase extends TBMCCommandBase { @CommandClass(modOnly = false, path = "discord")
public abstract class DiscordMCCommandBase extends PlayerCommandBase {
@Override
public String GetCommandPath() {
return "discord " + GetDiscordCommandPath();
}
public abstract String GetDiscordCommandPath();
} }

View file

@ -1,5 +1,11 @@
package buttondevteam.DiscordPlugin; package buttondevteam.DiscordPlugin;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.apache.commons.lang.exception.ExceptionUtils;
import buttondevteam.lib.TBMCCoreAPI;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestCase; import junit.framework.TestCase;
import junit.framework.TestSuite; import junit.framework.TestSuite;
@ -7,32 +13,48 @@ import junit.framework.TestSuite;
/** /**
* Unit test for simple App. * Unit test for simple App.
*/ */
public class AppTest public class AppTest extends TestCase {
extends TestCase
{
/** /**
* Create the test case * Create the test case
* *
* @param testName name of the test case * @param testName
* name of the test case
*/ */
public AppTest( String testName ) public AppTest(String testName) {
{
super(testName); super(testName);
} }
/** /**
* @return the suite of tests being tested * @return the suite of tests being tested
*/ */
public static Test suite() public static Test suite() {
{
return new TestSuite(AppTest.class); return new TestSuite(AppTest.class);
} }
/** /**
* Rigourous Test :-) * Rigourous Test :-)
*/ */
public void testApp() public void testApp() {
{ /*String sourcemessage = "Test message";
Exception e = new Exception("Test exception");
StringBuilder sb = TBMCCoreAPI.IsTestServer() ? new StringBuilder()
: new StringBuilder("Coder role").append("\n");
sb.append(sourcemessage).append("\n");
sb.append("```").append("\n");
String stackTrace = Arrays.stream(ExceptionUtils.getStackTrace(e).split("\\n"))
.filter(s -> !(s.contains("\tat ") && ( //
s.contains("java.util") //
|| s.contains("java.lang") //
|| s.contains("net.minecraft.server") //
|| s.contains("sun.reflect") //
|| s.contains("org.bukkit") //
))).collect(Collectors.joining("\n"));
if (stackTrace.length() > 1800)
stackTrace = stackTrace.substring(0, 1800);
sb.append(stackTrace).append("\n");
sb.append("```");
System.out.println(sb.toString());
assertTrue(sb.toString().contains("Coder role"));*/
assertTrue(true); assertTrue(true);
} }
} }