Fixes, channelcon, emoji

Limited timeout for shutdown message
Added some unconnected commands
Fixed mcchat tasks on shutdown
Added /rp as an allowed channel
Changed help texts to use /command syntax
Added channelcon remove
Added emoji parsing
This commit is contained in:
Norbi Peti 2018-06-08 01:48:07 +02:00
parent b60c4f5090
commit b8814030e2
No known key found for this signature in database
GPG key ID: DBA4C4549A927E56
9 changed files with 95 additions and 37 deletions

15
pom.xml
View file

@ -151,12 +151,11 @@
<version>1.12.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.discord4j/Discord4J -->
<dependency>
<groupId>com.github.austinv11</groupId>
<artifactId>Discord4j</artifactId>
<version>master-SNAPSHOT</version>
<!-- <classifier>shaded</classifier> --> <!-- Include this line if you want a shaded jar (all the Discord4J dependencies
bundled into one jar) -->
<groupId>com.discord4j</groupId>
<artifactId>Discord4J</artifactId>
<version>2.10.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-jdk14 -->
<dependency>
@ -213,6 +212,10 @@
<version>2.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.vdurmont</groupId>
<artifactId>emoji-java</artifactId>
<version>4.0.0</version>
</dependency>
</dependencies>
</project>

View file

@ -1,11 +1,15 @@
package buttondevteam.discordplugin;
import buttondevteam.lib.TBMCCoreAPI;
import org.bukkit.Bukkit;
import sx.blah.discord.util.EmbedBuilder;
import sx.blah.discord.util.RequestBuffer;
import sx.blah.discord.util.RequestBuffer.IRequest;
import sx.blah.discord.util.RequestBuffer.IVoidRequest;
import javax.annotation.Nullable;
import java.util.concurrent.TimeUnit;
public final class DPUtils {
public static EmbedBuilder embedWithHead(EmbedBuilder builder, String playername) {
@ -34,16 +38,35 @@ public final class DPUtils {
/**
* Performs Discord actions, retrying when ratelimited. May return null if action fails too many times or in safe mode.
*/
public static <T> T perform(IRequest<T> action) {
@Nullable
public static <T> T perform(IRequest<T> action, long timeout, TimeUnit unit) {
if (DiscordPlugin.SafeMode)
return null;
if (Thread.currentThread() == DiscordPlugin.mainThread) // TODO: Ignore shutdown message <--
// throw new RuntimeException("Tried to wait for a Discord request on the main thread. This could cause lag.");
Bukkit.getLogger().warning("Waiting for a Discord request on the main thread!");
try {
return RequestBuffer.request(action).get(timeout, unit); // Let the pros handle this
} catch (Exception e) {
TBMCCoreAPI.SendException("Couldn't perform Discord action!", e);
return null;
}
}
/**
* Performs Discord actions, retrying when ratelimited. May return null if action fails too many times or in safe mode.
*/
@Nullable
public static <T> T perform(IRequest<T> action) {
System.out.println("performA");
if (DiscordPlugin.SafeMode)
return null;
if (DiscordPlugin.SafeMode)
return null;
System.out.println("performB");
if (Thread.currentThread() == DiscordPlugin.mainThread) // TODO: Ignore shutdown message <--
// throw new RuntimeException("Tried to wait for a Discord request on the main thread. This could cause lag.");
// throw new RuntimeException("Tried to wait for a Discord request on the main thread. This could cause lag.");
Bukkit.getLogger().warning("Waiting for a Discord request on the main thread!");
return RequestBuffer.request(action).get(); // Let the pros handle this
}
return RequestBuffer.request(action).get(); // Let the pros handle this
}
/**
* Performs Discord actions, retrying when ratelimited.

View file

@ -32,6 +32,7 @@ import java.awt.*;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
@ -243,7 +244,7 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
+ (Bukkit.getOnlinePlayers().size() == 1 ? " was " : " were ")
+ "asked *politely* to leave the server for a bit.")
: "")
.build()));
.build(), 5, TimeUnit.SECONDS));
System.out.println("XY");
ChromaBot.getInstance().updatePlayerList();
try {
@ -349,12 +350,25 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
return sendMessageToChannel(channel, message, embed, true);
}
public static IMessage sendMessageToChannelWait(IChannel channel, String message, EmbedObject embed, long timeout, TimeUnit unit) {
System.out.println("lol!");
return sendMessageToChannel(channel, message, embed, true, timeout, unit);
}
private static IMessage sendMessageToChannel(IChannel channel, String message, EmbedObject embed, boolean wait) {
return sendMessageToChannel(channel, message, embed, wait, -1, null);
}
private static IMessage sendMessageToChannel(IChannel channel, String message, EmbedObject embed, boolean wait, long timeout, TimeUnit unit) {
System.out.println("lolwut");
if (message.length() > 1980) {
System.out.println("wut");
message = message.substring(0, 1980);
Bukkit.getLogger()
.warning("Message was too long to send to discord and got truncated. In " + channel.getName());
System.out.println("wat");
}
System.out.println("wot");
try {
System.out.println("sendA");
if (channel == chatchannel)
@ -366,10 +380,16 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
RequestBuffer.IRequest<IMessage> r = () -> embed == null ? channel.sendMessage(content)
: channel.sendMessage(content, embed, false);
System.out.println("sendC");
if (wait)
return DPUtils.perform(r);
else {
DPUtils.performNoWait(r);
if (wait) {
if (unit != null)
return DPUtils.perform(r, timeout, unit);
else
return DPUtils.perform(r);
} else {
if (unit != null)
plugin.getLogger().warning("Tried to set timeout for non-waiting call.");
else
DPUtils.performNoWait(r);
return null;
}
} catch (Exception e) {

View file

@ -28,9 +28,14 @@ public class ChannelconCommand extends DiscordCommandBase {
message.reply("you need to have manage permissions for this channel!");
return true;
}
//TODO: What if they no longer have permission to view the channel
if (MCChatListener.hasCustomChat(message.getChannel())) { //TODO: Remove command
message.reply("this channel is already connected to a Minecraft channel.");
//TODO: What if they no longer have permission to view the channel - check on some message events and startup - if somebody who can view the channel (on both platforms) has their accounts connected, keep it
if (MCChatListener.hasCustomChat(message.getChannel())) {
if (args.equalsIgnoreCase("remove")) {
MCChatListener.removeCustomChat(message.getChannel());
message.reply("channel connection removed.");
return true;
}
message.reply("this channel is already connected to a Minecraft channel. Use `/channelcon remove` to remove it.");
return true;
}
val chan = Channel.getChannels().stream().filter(ch -> ch.ID.equalsIgnoreCase(args) || (ch.IDs != null && Arrays.stream(ch.IDs).anyMatch(cid -> cid.equalsIgnoreCase(args)))).findAny();
@ -40,7 +45,7 @@ public class ChannelconCommand extends DiscordCommandBase {
}
val chp = DiscordPlayer.getUser(message.getAuthor().getStringID(), DiscordPlayer.class).getAs(TBMCPlayer.class);
if (chp == null) {
message.reply("you need to connect your Minecraft account. In #bot do @ChromaBot connect <MCname>");
message.reply("you need to connect your Minecraft account. In this channel or on our server in #bot do /connect <MCname>");
return true;
}
val ev = new TBMCChannelConnectEvent(new DiscordConnectedPlayer(message.getAuthor(), message.getChannel(), chp.getUUID(), Bukkit.getOfflinePlayer(chp.getUUID()).getName()), chan.get());
@ -57,11 +62,12 @@ public class ChannelconCommand extends DiscordCommandBase {
@Override
public String[] getHelpText() {
return new String[]{ //
"§6---- Channel connect ---", //
"---- Channel connect ---", //
"This command allows you to connect a Minecraft channel to a Discord channel (just like how the global chat is connected to #minecraft-chat).", //
"You need to have access to the MC channel and have manage permissions on the Discord channel.", //
"You also need to have your Minecraft account connected. In #bot use @ChromaBot connect <mcname>.", //
"Call this command from the channel you want to use. Usage: @ChromaBot channelcon <mcchannel>", //
"You also need to have your Minecraft account connected. In #bot use /connect <mcname>.", //
"Call this command from the channel you want to use. Usage: /channelcon <mcchannel>", //
"To remove a connection use /channelcon remove in the channel.", //
"Invite link: https://discordapp.com/oauth2/authorize?client_id=226443037893591041&scope=bot" //
};
}

View file

@ -25,8 +25,7 @@ public class MCChatCommand extends DiscordCommandBase {
MCChatListener.privateMCChat(message.getChannel(), mcchat, message.getAuthor(), user);
DiscordPlugin.sendMessageToChannel(message.getChannel(),
"Minecraft chat " + (mcchat //
? "enabled. Use '" + message.getClient().getOurUser().mention()
+ " mcchat' (with the mention) to disable." //
? "enabled. Use '/mcchat' to disable." //
: "disabled."));
} catch (Exception e) {
TBMCCoreAPI.SendException("Error while setting mcchat for user" + message.getAuthor().getName(), e);

View file

@ -145,7 +145,7 @@ public class CommandListener {
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 no color.");
DiscordPlugin.sendMessageToChannel(DiscordPlugin.modlogchannel, "Added " + event.getNewRole().getName() + " as game role because it has the default color.");
}
}};
}

View file

@ -10,6 +10,7 @@ import buttondevteam.lib.chat.Channel;
import buttondevteam.lib.chat.ChatRoom;
import buttondevteam.lib.chat.TBMCChatAPI;
import buttondevteam.lib.player.TBMCPlayer;
import com.vdurmont.emoji.EmojiParser;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.bukkit.Bukkit;
@ -57,7 +58,8 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
sendrunnable = () -> {
sendthread = Thread.currentThread();
processMCToDiscord();
sendtask = Bukkit.getScheduler().runTaskAsynchronously(DiscordPlugin.plugin, sendrunnable);
if (DiscordPlugin.plugin.isEnabled()) //Don't run again if shutting down
sendtask = Bukkit.getScheduler().runTaskAsynchronously(DiscordPlugin.plugin, sendrunnable);
};
sendtask = Bukkit.getScheduler().runTaskAsynchronously(DiscordPlugin.plugin, sendrunnable);
}
@ -170,7 +172,7 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
}
private static final String[] UnconnectedCmds = new String[]{"list", "u", "shrug", "tableflip", "unflip", "mwiki",
"yeehaw", "lenny"};
"yeehaw", "lenny", "rp", "plugins"};
private static LastMsgData lastmsgdata;
private static short lastlist = 0;
@ -327,7 +329,8 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
recrun = () -> { //Don't return in a while loop next time
recthread = Thread.currentThread();
processDiscordToMC();
rectask = Bukkit.getScheduler().runTaskAsynchronously(DiscordPlugin.plugin, recrun); //Continue message processing
if (DiscordPlugin.plugin.isEnabled()) //Don't run again if shutting down
rectask = Bukkit.getScheduler().runTaskAsynchronously(DiscordPlugin.plugin, recrun); //Continue message processing
};
rectask = Bukkit.getScheduler().runTaskAsynchronously(DiscordPlugin.plugin, recrun); //Start message processing
}
@ -353,6 +356,9 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
dmessage = dmessage.replace(u.mention(true), "@" + (nick != null ? nick : u.getName()));
}
dmessage = EmojiParser.parseToAliases(dmessage, EmojiParser.FitzpatrickAction.PARSE); //Converts emoji to text- TODO: Add option to disable (resource pack?)
dmessage = dmessage.replaceAll(":(\\S+)\\|type_(?:(\\d)|(1)_2):", ":$1::skin-tone-$2:"); //Convert to Discord's format so it still shows up
BiConsumer<Channel, String> sendChatMessage = (channel, msg) -> //
TBMCChatAPI.SendChatMessage(channel, dsender,
msg + (event.getMessage().getAttachments().size() > 0 ? "\n" + event.getMessage()
@ -375,10 +381,11 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
+ Arrays.stream(UnconnectedCmds).map(uc -> "/" + uc)
.collect(Collectors.joining(", "))
+ (user.getConnectedID(TBMCPlayer.class) == null
? "\nTo access your commands, first please connect your accounts, using @ChromaBot connect in "
? "\nTo access your commands, first please connect your accounts, using /connect in "
+ DiscordPlugin.botchannel.mention()
+ "\nThen you can access all of your regular commands (even offline) in private chat: DM me `mcchat`!"
: "\nYou can access all of your regular commands (even offline) in private chat: DM me `mcchat`!"));
+ "\nThen y"
: "\nY")
+ "ou can access all of your regular commands (even offline) in private chat: DM me `mcchat`!");
return;
}
if (lastlist > 5) {
@ -395,13 +402,13 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
Optional<Channel> ch = Channel.getChannels().stream()
.filter(c -> c.ID.equalsIgnoreCase(topcmd)
|| (c.IDs != null && c.IDs.length > 0
&& Arrays.stream(c.IDs).noneMatch(id -> id.equalsIgnoreCase(topcmd)))).findAny();
&& Arrays.stream(c.IDs).anyMatch(id -> id.equalsIgnoreCase(topcmd)))).findAny();
if (!ch.isPresent())
Bukkit.getScheduler().runTask(DiscordPlugin.plugin,
() -> VanillaCommandListener.runBukkitOrVanillaCommand(dsender, cmd));
else {
Channel chc = ch.get();
if (!chc.ID.equals(Channel.GlobalChat.ID) && !event.getMessage().getChannel().isPrivate())
if (!chc.ID.equals(Channel.GlobalChat.ID) && !chc.ID.equals("rp") && !event.getMessage().getChannel().isPrivate())
dsender.sendMessage(
"You can only talk in global in the public chat. DM `mcchat` to enable private chat to talk in the other channels.");
else {

View file

@ -17,7 +17,7 @@ public class AcceptMCCommand extends DiscordMCCommandBase {
return new String[] { //
"§6---- Accept Discord connection ----", //
"Accept a pending connection between your Discord and Minecraft account.", //
"To start the connection process, do §b@ChromaBot connect <MCname>§r in the #bot channel on Discord", //
"To start the connection process, do §b/connect <MCname>§r in the #bot channel on Discord", //
"Usage: /" + alias + " accept" //
};
}

View file

@ -12,7 +12,7 @@ public class DeclineMCCommand extends DiscordMCCommandBase {
return new String[] { //
"§6---- Decline Discord connection ----", //
"Decline a pending connection between your Discord and Minecraft account.", //
"To start the connection process, do §b@ChromaBot connect <MCname>§r in the #bot channel on Discord", //
"To start the connection process, do §b/connect <MCname>§r in the #bot channel on Discord", //
"Usage: /" + alias + " decline" //
};
}