Added and refactored some things

- Added limit to all messages sent to Discord
- Lowered limit of stack traces as the final message still exceeded
Discord's limit
- Moved common code of the senders to a separate class
- Made broadcasted messages only send once
https://github.com/TBMCPlugins/DiscordPlugin/issues/12
This commit is contained in:
Norbi Peti 2016-12-07 17:23:40 +01:00
parent 4238a23d39
commit 674c85b136
6 changed files with 91 additions and 118 deletions

View file

@ -2,8 +2,6 @@ package buttondevteam.discordplugin;
import java.net.InetSocketAddress;
import java.util.*;
import java.util.stream.Collectors;
import org.bukkit.*;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeInstance;
@ -24,29 +22,18 @@ import org.bukkit.potion.PotionEffectType;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.util.Vector;
import buttondevteam.lib.TBMCCoreAPI;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IUser;
@SuppressWarnings("deprecation")
public class DiscordPlayerSender implements Player {
private IUser user;
private IChannel channel;
public class DiscordPlayerSender extends DiscordSenderBase implements Player {
private Player player;
public DiscordPlayerSender(IUser user, Player player) {
this.user = user;
public DiscordPlayerSender(IUser user, IChannel channel, Player player) {
super(user, channel);
this.player = player;
}
public IChannel getChannel() {
return channel;
}
public void setChannel(IChannel channel) {
this.channel = channel;
}
@Override
public boolean isPermissionSet(String name) {
return player.isPermissionSet(name);
@ -112,32 +99,6 @@ public class DiscordPlayerSender implements Player {
player.setOp(value);
}
@Override
public void sendMessage(String message) {
try {
final boolean broadcast = new Exception().getStackTrace()[2].getMethodName().contains("broadcast");
String sanitizedMsg = "";
for (int i = 0; i < message.length(); i++) {
if (message.charAt(i) != '§') {
sanitizedMsg += message.charAt(i);
} else {
i++;
}
}
final String sendmsg = sanitizedMsg;
Bukkit.getScheduler().runTaskAsynchronously(DiscordPlugin.plugin, () -> DiscordPlugin
.sendMessageToChannel(channel, (broadcast ? user.mention() + " " : "") + sendmsg));
} catch (Exception e) {
TBMCCoreAPI.SendException("An error occured while sending message to DiscordSender", e);
}
player.sendMessage(message);
}
@Override
public void sendMessage(String[] messages) {
sendMessage(Arrays.stream(messages).collect(Collectors.joining("\n")));
}
@Override
public Server getServer() {
return Bukkit.getServer();

View file

@ -196,6 +196,11 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
}
public static IMessage sendMessageToChannel(IChannel channel, String message) {
if (message.length() > 1900) {
message = message.substring(0, 1900);
Bukkit.getLogger()
.warning("Message was too long to send to discord and got truncated. In " + channel.getName());
}
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(i * 100);
@ -238,4 +243,17 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
perms = permsProvider.getProvider();
return perms != null;
}
/** Removes §[char] colour codes from strings */
public static String sanitizeString(String string) {
String sanitizedString = "";
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == '§') {
i++;// Skips the data value, the 4 in "§4Alisolarflare"
} else {
sanitizedString += string.charAt(i);
}
}
return sanitizedString;
}
}

View file

@ -1,37 +1,20 @@
package buttondevteam.discordplugin;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.PermissibleBase;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionAttachment;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.permissions.*;
import org.bukkit.plugin.Plugin;
import buttondevteam.lib.TBMCCoreAPI;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IUser;
public class DiscordSender implements CommandSender {
public class DiscordSender extends DiscordSenderBase implements CommandSender {
private PermissibleBase perm = new PermissibleBase(this);
private IUser user;
private IChannel channel;
public DiscordSender(IUser user) {
this.user = user;
}
public IChannel getChannel() {
return channel;
}
public void setChannel(IChannel channel) {
this.channel = channel;
public DiscordSender(IUser user, IChannel channel) {
super(user, channel);
}
@Override
@ -100,31 +83,6 @@ public class DiscordSender implements CommandSender {
public void setOp(boolean value) { // TODO: Connect with TBMC acc
}
@Override
public void sendMessage(String message) {
try {
final boolean broadcast = new Exception().getStackTrace()[2].getMethodName().contains("broadcast");
String sanitizedMsg = "";
for (int i = 0; i < message.length(); i++) {
if (message.charAt(i) != '§') {
sanitizedMsg += message.charAt(i);
} else {
i++;
}
}
final String sendmsg = sanitizedMsg;
Bukkit.getScheduler().runTaskAsynchronously(DiscordPlugin.plugin, () -> DiscordPlugin
.sendMessageToChannel(channel, (!broadcast ? user.mention() + " " : "") + sendmsg));
} catch (Exception e) {
TBMCCoreAPI.SendException("An error occured while sending message to DiscordSender", e);
}
}
@Override
public void sendMessage(String[] messages) {
sendMessage(Arrays.stream(messages).collect(Collectors.joining("\n")));
}
@Override
public Server getServer() {
return Bukkit.getServer();

View file

@ -0,0 +1,49 @@
package buttondevteam.discordplugin;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import buttondevteam.lib.TBMCCoreAPI;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IUser;
public abstract class DiscordSenderBase implements CommandSender {
protected IUser user;
protected IChannel channel;
protected DiscordSenderBase(IUser user, IChannel channel) {
this.user = user;
this.channel = channel;
}
private List<String> broadcasts = new ArrayList<>();
@Override
public void sendMessage(String message) {
try {
final boolean broadcast = new Exception().getStackTrace()[2].getMethodName().contains("broadcast");
if (broadcast) {
if (broadcasts.contains(message))
return;
if (broadcasts.size() > 10)
broadcasts.clear();
broadcasts.add(message);
}
final String sendmsg = DiscordPlugin.sanitizeString(message);
Bukkit.getScheduler().runTaskAsynchronously(DiscordPlugin.plugin, () -> DiscordPlugin
.sendMessageToChannel(channel, (!broadcast ? user.mention() + " " : "") + sendmsg));
} catch (Exception e) {
TBMCCoreAPI.SendException("An error occured while sending message to DiscordSender", e);
}
}
@Override
public void sendMessage(String[] messages) {
sendMessage(Arrays.stream(messages).collect(Collectors.joining("\n")));
}
}

View file

@ -20,8 +20,8 @@ public class ExceptionListener implements Listener {
sb.append(sourcemessage).append("\n");
sb.append("```").append("\n");
String stackTrace = ExceptionUtils.getStackTrace(e);
if (stackTrace.length() > 2000)
stackTrace = stackTrace.substring(0, 2000);
if (stackTrace.length() > 1800)
stackTrace = stackTrace.substring(0, 1800);
sb.append(stackTrace).append("\n");
sb.append("```");
DiscordPlugin.sendMessageToChannel(DiscordPlugin.botroomchannel, sb.toString());

View file

@ -5,15 +5,11 @@ import java.util.HashMap;
import java.util.Optional;
import java.util.stream.Collectors;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import buttondevteam.discordplugin.DiscordPlayer;
import buttondevteam.discordplugin.DiscordPlayerSender;
import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.DiscordSender;
import buttondevteam.discordplugin.*;
import buttondevteam.lib.TBMCChatEvent;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.TBMCPlayer;
@ -29,23 +25,12 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
if (e.getSender() instanceof DiscordSender || e.getSender() instanceof DiscordPlayerSender)
return;
if (e.getChannel().equals(Channel.GlobalChat))
DiscordPlugin.sendMessageToChannel(DiscordPlugin.chatchannel, "<" + (e.getSender() instanceof Player
? sanitizeString(((Player) e.getSender()).getDisplayName()) :
sanitizeString(e.getSender().getName())) + "> " + sanitizeString(e.getMessage()));
DiscordPlugin.sendMessageToChannel(DiscordPlugin.chatchannel,
"<" + (e.getSender() instanceof Player
? DiscordPlugin.sanitizeString(((Player) e.getSender()).getDisplayName())
: DiscordPlugin.sanitizeString(e.getSender().getName())) + "> "
+ DiscordPlugin.sanitizeString(e.getMessage()));
}
/**Removes §[char] colour codes from strings*/
private String sanitizeString(String string){
String sanitizedString = "";
for(int i = 0; i < string.length(); i++){
if (string.charAt(i) == '§'){
i++;//Skips the data value, the 4 in "§4Alisolarflare"
}else{
sanitizedString += string.charAt(i);
}
}
return sanitizedString;
}
private static final String[] UnconnectedCmds = new String[] { "list", "u", "shrug", "tableflip", "unflip",
"mwiki" };
@ -66,26 +51,28 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
DiscordPlayer dp = TBMCPlayer.getPlayerAs(p, DiscordPlayer.class); // Online player, already loaded
return author.getID().equals(dp.getDiscordID());
}).findAny();
final CommandSender dsender;
final DiscordSenderBase dsender;
if (player.isPresent()) // Connected?
{ // Execute as ingame player
if (!ConnectedSenders.containsKey(author.getID()))
ConnectedSenders.put(author.getID(), new DiscordPlayerSender(author, player.get()));
ConnectedSenders.put(author.getID(),
new DiscordPlayerSender(author, event.getMessage().getChannel(), player.get()));
dsender = ConnectedSenders.get(author.getID());
((DiscordPlayerSender) dsender).setChannel(event.getMessage().getChannel());
} else {
if (!UnconnectedSenders.containsKey(author.getID()))
UnconnectedSenders.put(author.getID(), new DiscordSender(author));
UnconnectedSenders.put(author.getID(), new DiscordSender(author, event.getMessage().getChannel()));
dsender = UnconnectedSenders.get(author.getID());
((DiscordSender) dsender).setChannel(event.getMessage().getChannel());
}
if (event.getMessage().getContent().startsWith("/")) {
final String cmd = event.getMessage().getContent().substring(1).toLowerCase();
if (!player.isPresent() && !Arrays.stream(UnconnectedCmds).anyMatch(s -> cmd.equals(s) || cmd.startsWith(s + " "))) {
if (!player.isPresent()
&& !Arrays.stream(UnconnectedCmds).anyMatch(s -> cmd.equals(s) || cmd.startsWith(s + " "))) {
// Command not whitelisted
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"
+ Arrays.toString(UnconnectedCmds));
+ Arrays.toString(UnconnectedCmds)
+ "\nTo connect your accounts, use @ChromaBot connect in "
+ DiscordPlugin.botchannel.mention());
return;
}
Bukkit.dispatchCommand(dsender, cmd);