Started converting to new D4J

#93
This commit is contained in:
Norbi Peti 2019-04-17 13:52:01 +02:00
parent 55c61cef98
commit d8d75c063b
5 changed files with 249 additions and 464 deletions

View file

@ -173,8 +173,8 @@
<!-- https://mvnrepository.com/artifact/com.discord4j/Discord4J --> <!-- https://mvnrepository.com/artifact/com.discord4j/Discord4J -->
<dependency> <dependency>
<groupId>com.discord4j</groupId> <groupId>com.discord4j</groupId>
<artifactId>Discord4J</artifactId> <artifactId>discord4j-core</artifactId>
<version>2.10.1</version> <version>3.0.2</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-jdk14 --> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-jdk14 -->
<dependency> <dependency>

View file

@ -1,15 +1,14 @@
package buttondevteam.discordplugin; package buttondevteam.discordplugin;
import buttondevteam.discordplugin.mcchat.MCChatUtils; import buttondevteam.discordplugin.mcchat.MCChatUtils;
import discord4j.core.object.entity.Message;
import discord4j.core.object.entity.MessageChannel;
import lombok.Getter; import lombok.Getter;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitScheduler;
import sx.blah.discord.api.internal.json.objects.EmbedObject; import reactor.core.publisher.Mono;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.util.EmbedBuilder;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.awt.*; import java.util.function.Function;
public class ChromaBot { public class ChromaBot {
/** /**
@ -33,111 +32,24 @@ public class ChromaBot {
instance = null; instance = null;
} }
/**
* Send a message to the chat channel and private chats.
*
* @param message
* The message to send, duh
*/
public void sendMessage(String message) {
MCChatUtils.forAllMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, message));
}
/** /**
* Send a message to the chat channels and private chats. * Send a message to the chat channels and private chats.
* *
* @param message * @param message
* The message to send, duh * The message to send, duh (use {@link MessageChannel#createMessage(String)})
* @param embed
* Custom fancy stuff, use {@link EmbedBuilder} to create one
*/ */
public void sendMessage(String message, EmbedObject embed) { public void sendMessage(Function<MessageChannel, Mono<Message>> message) {
MCChatUtils.forAllMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, message, embed)); MCChatUtils.forAllMCChat(ch -> message.apply(ch).subscribe());
} }
/** /**
* Send a message to the chat channels, private chats and custom chats. * Send a message to the chat channels, private chats and custom chats.
* *
* @param message The message to send, duh * @param message The message to send, duh
* @param embed Custom fancy stuff, use {@link EmbedBuilder} to create one
* @param toggle The toggle type for channelcon * @param toggle The toggle type for channelcon
*/ */
public void sendMessageCustomAsWell(String message, EmbedObject embed, @Nullable ChannelconBroadcast toggle) { public void sendMessageCustomAsWell(Function<MessageChannel, Mono<Message>> message, @Nullable ChannelconBroadcast toggle) {
MCChatUtils.forCustomAndAllMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, message, embed), toggle, false); MCChatUtils.forCustomAndAllMCChat(ch -> message.apply(ch).subscribe(), toggle, false);
}
/**
* Send a message to an arbitrary channel. This will not send it to the private chats.
*
* @param channel
* The channel to send to, use the channel variables in {@link DiscordPlugin}
* @param message
* The message to send, duh
* @param embed
* Custom fancy stuff, use {@link EmbedBuilder} to create one
*/
public void sendMessage(IChannel channel, String message, EmbedObject embed) {
DiscordPlugin.sendMessageToChannel(channel, message, embed);
}
/**
* Send a fancy message to the chat channels. This will show a bold text with a colored line.
*
* @param message
* The message to send, duh
* @param color
* The color of the line before the text
*/
public void sendMessage(String message, Color color) {
MCChatUtils.forAllMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, message,
new EmbedBuilder().withTitle(message).withColor(color).build()));
}
/**
* Send a fancy message to the chat channels. This will show a bold text with a colored line.
*
* @param message
* The message to send, duh
* @param color
* The color of the line before the text
* @param mcauthor
* The name of the Minecraft player who is the author of this message
*/
public void sendMessage(String message, Color color, String mcauthor) {
MCChatUtils.forAllMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, message,
DPUtils.embedWithHead(new EmbedBuilder().withTitle(message).withColor(color), mcauthor).build()));
}
/**
* Send a fancy message to the chat channels. This will show a bold text with a colored line.
*
* @param message
* The message to send, duh
* @param color
* The color of the line before the text
* @param authorname
* The name of the author of this message
* @param authorimg
* The URL of the avatar image for this message's author
*/
public void sendMessage(String message, Color color, String authorname, String authorimg) {
MCChatUtils.forAllMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, message, new EmbedBuilder()
.withTitle(message).withColor(color).withAuthorName(authorname).withAuthorIcon(authorimg).build()));
}
/**
* Send a message to the chat channels. This will show a bold text with a colored line.
*
* @param message
* The message to send, duh
* @param color
* The color of the line before the text
* @param sender
* The player who sends this message
*/
public void sendMessage(String message, Color color, Player sender) {
MCChatUtils.forAllMCChat(ch -> DiscordPlugin.sendMessageToChannel(ch, message, DPUtils
.embedWithHead(new EmbedBuilder().withTitle(message).withColor(color), sender.getName()).build()));
} }
public void updatePlayerList() { public void updatePlayerList() {

View file

@ -4,20 +4,14 @@ import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.architecture.Component; import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.architecture.ConfigData; import buttondevteam.lib.architecture.ConfigData;
import buttondevteam.lib.architecture.IHaveConfig; import buttondevteam.lib.architecture.IHaveConfig;
import discord4j.core.object.entity.Channel;
import discord4j.core.object.entity.Guild;
import discord4j.core.object.entity.Role;
import discord4j.core.object.util.Snowflake;
import lombok.val; import lombok.val;
import org.bukkit.Bukkit;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IGuild;
import sx.blah.discord.handle.obj.IIDLinkedObject;
import sx.blah.discord.handle.obj.IRole;
import sx.blah.discord.util.EmbedBuilder; import sx.blah.discord.util.EmbedBuilder;
import sx.blah.discord.util.RequestBuffer;
import sx.blah.discord.util.RequestBuffer.IRequest;
import sx.blah.discord.util.RequestBuffer.IVoidRequest;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@ -53,55 +47,6 @@ public final class DPUtils {
return sanitizedString; return sanitizedString;
} }
/**
* 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, long timeout, TimeUnit unit) throws TimeoutException, InterruptedException {
if (DiscordPlugin.SafeMode)
return null;
if (Bukkit.isPrimaryThread()) // TODO: Ignore shutdown message <--
// throw new RuntimeException("Tried to wait for a Discord request on the main thread. This could cause lag.");
getLogger().warning("Waiting for a Discord request on the main thread!");
return RequestBuffer.request(action).get(timeout, unit); // Let the pros handle this
}
/**
* 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) {
if (DiscordPlugin.SafeMode)
return null;
if (Bukkit.isPrimaryThread()) // TODO: Ignore shutdown message <--
// throw new RuntimeException("Tried to wait for a Discord request on the main thread. This could cause lag.");
getLogger().warning("Waiting for a Discord request on the main thread!");
return RequestBuffer.request(action).get(); // Let the pros handle this
}
/**
* Performs Discord actions, retrying when ratelimited.
*/
public static Void perform(IVoidRequest action) {
if (DiscordPlugin.SafeMode)
return null;
if (Bukkit.isPrimaryThread())
throw new RuntimeException("Tried to wait for a Discord request on the main thread. This could cause lag.");
return RequestBuffer.request(action).get(); // Let the pros handle this
}
public static void performNoWait(IVoidRequest action) {
if (DiscordPlugin.SafeMode)
return;
RequestBuffer.request(action);
}
public static <T> void performNoWait(IRequest<T> action) {
if (DiscordPlugin.SafeMode)
return;
RequestBuffer.request(action);
}
public static String escape(String message) { public static String escape(String message) {
return message.replaceAll("([*_~])", Matcher.quoteReplacement("\\")+"$1"); return message.replaceAll("([*_~])", Matcher.quoteReplacement("\\")+"$1");
} }
@ -112,20 +57,19 @@ public final class DPUtils {
return DiscordPlugin.plugin.getLogger(); return DiscordPlugin.plugin.getLogger();
} }
public static ConfigData<IChannel> channelData(IHaveConfig config, String key, long defID) { public static ConfigData<Channel> channelData(IHaveConfig config, String key, long defID) {
return config.getDataPrimDef(key, defID, id -> DiscordPlugin.dc.getChannelByID((long) id), IIDLinkedObject::getLongID); //We can afford to search for the channel in the cache once (instead of using mainServer) return config.getDataPrimDef(key, defID, id -> DiscordPlugin.dc.getChannelById(Snowflake.of((long) id)).block(), ch -> ch.getId().asLong()); //We can afford to search for the channel in the cache once (instead of using mainServer)
} }
public static ConfigData<IRole> roleData(IHaveConfig config, String key, String defName) { public static ConfigData<Role> roleData(IHaveConfig config, String key, String defName) {
return roleData(config, key, defName, DiscordPlugin.mainServer); return roleData(config, key, defName, DiscordPlugin.mainServer);
} }
public static ConfigData<IRole> roleData(IHaveConfig config, String key, String defName, IGuild guild) { public static ConfigData<Role> roleData(IHaveConfig config, String key, String defName, Guild guild) {
return config.getDataPrimDef(key, defName, name -> { return config.getDataPrimDef(key, defName, name -> {
if (!(name instanceof String)) return null; if (!(name instanceof String)) return null;
val roles = guild.getRolesByName((String) name); return guild.getRoles().filter(r -> r.getName().equals(name)).blockFirst();
return roles.size() > 0 ? roles.get(0) : null; }, r -> r.getId().asLong());
}, IIDLinkedObject::getLongID);
} }
/** /**
@ -134,10 +78,10 @@ public final class DPUtils {
* @return The string for mentioning the channel * @return The string for mentioning the channel
*/ */
public static String botmention() { public static String botmention() {
IChannel channel; Channel channel;
if (DiscordPlugin.plugin == null if (DiscordPlugin.plugin == null
|| (channel = DiscordPlugin.plugin.CommandChannel().get()) == null) return "#bot"; || (channel = DiscordPlugin.plugin.CommandChannel().get()) == null) return "#bot";
return channel.mention(); return channel.getMention();
} }
/** /**

View file

@ -11,15 +11,23 @@ import buttondevteam.discordplugin.mcchat.MCChatPrivate;
import buttondevteam.discordplugin.mcchat.MCChatUtils; import buttondevteam.discordplugin.mcchat.MCChatUtils;
import buttondevteam.discordplugin.mcchat.MinecraftChatModule; import buttondevteam.discordplugin.mcchat.MinecraftChatModule;
import buttondevteam.discordplugin.mccommands.DiscordMCCommand; import buttondevteam.discordplugin.mccommands.DiscordMCCommand;
import buttondevteam.discordplugin.mccommands.DiscordMCCommandBase;
import buttondevteam.discordplugin.role.GameRoleModule; import buttondevteam.discordplugin.role.GameRoleModule;
import buttondevteam.lib.TBMCCoreAPI; import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.architecture.ButtonPlugin; import buttondevteam.lib.architecture.ButtonPlugin;
import buttondevteam.lib.architecture.Component; import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.architecture.ConfigData; import buttondevteam.lib.architecture.ConfigData;
import buttondevteam.lib.chat.TBMCChatAPI;
import buttondevteam.lib.player.ChromaGamerBase; import buttondevteam.lib.player.ChromaGamerBase;
import com.google.common.io.Files; import com.google.common.io.Files;
import discord4j.core.DiscordClient;
import discord4j.core.DiscordClientBuilder;
import discord4j.core.event.domain.lifecycle.ReadyEvent;
import discord4j.core.object.entity.Channel;
import discord4j.core.object.entity.Guild;
import discord4j.core.object.entity.Role;
import discord4j.core.object.presence.Activity;
import discord4j.core.object.presence.Presence;
import discord4j.core.object.reaction.ReactionEmoji;
import discord4j.core.object.util.Snowflake;
import lombok.Getter; import lombok.Getter;
import lombok.val; import lombok.val;
import net.milkbowl.vault.permission.Permission; import net.milkbowl.vault.permission.Permission;
@ -28,27 +36,17 @@ import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.scheduler.BukkitTask; 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.internal.json.objects.EmbedObject;
import sx.blah.discord.handle.impl.events.ReadyEvent;
import sx.blah.discord.handle.impl.obj.ReactionEmoji;
import sx.blah.discord.handle.obj.*;
import sx.blah.discord.util.EmbedBuilder;
import sx.blah.discord.util.RequestBuffer;
import java.awt.*; import java.awt.*;
import java.io.File; import java.io.File;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class DiscordPlugin extends ButtonPlugin implements IListener<ReadyEvent> { public class DiscordPlugin extends ButtonPlugin {
public static IDiscordClient dc; public static DiscordClient dc;
public static DiscordPlugin plugin; public static DiscordPlugin plugin;
public static boolean SafeMode = true; public static boolean SafeMode = true;
@Getter @Getter
@ -63,15 +61,15 @@ public class DiscordPlugin extends ButtonPlugin implements IListener<ReadyEvent>
return plugin.Prefix().get(); return plugin.Prefix().get();
} }
public ConfigData<IGuild> MainServer() { public ConfigData<Guild> MainServer() {
return getIConfig().getDataPrimDef("mainServer", 219529124321034241L, id -> dc.getGuildByID((long) id), IIDLinkedObject::getLongID); return getIConfig().getDataPrimDef("mainServer", 219529124321034241L, id -> dc.getGuildById(Snowflake.of((long) id)).block(), g -> g.getId().asLong());
} }
public ConfigData<IChannel> CommandChannel() { public ConfigData<Channel> CommandChannel() {
return DPUtils.channelData(getIConfig(), "commandChannel", 239519012529111040L); return DPUtils.channelData(getIConfig(), "commandChannel", 239519012529111040L);
} }
public ConfigData<IRole> ModRole() { public ConfigData<Role> ModRole() {
return DPUtils.roleData(getIConfig(), "modRole", "Moderator"); return DPUtils.roleData(getIConfig(), "modRole", "Moderator");
} }
@ -81,15 +79,15 @@ public class DiscordPlugin extends ButtonPlugin implements IListener<ReadyEvent>
getLogger().info("Initializing..."); getLogger().info("Initializing...");
plugin = this; plugin = this;
manager = new Command2DC(); manager = new Command2DC();
ClientBuilder cb = new ClientBuilder(); String token;
File tokenFile = new File("TBMC", "Token.txt"); File tokenFile = new File("TBMC", "Token.txt");
if (tokenFile.exists()) //Legacy support if (tokenFile.exists()) //Legacy support
//noinspection UnstableApiUsage //noinspection UnstableApiUsage
cb.withToken(Files.readFirstLine(tokenFile, StandardCharsets.UTF_8)); token = Files.readFirstLine(tokenFile, StandardCharsets.UTF_8);
else { else {
File privateFile = new File(getDataFolder(), "private.yml"); File privateFile = new File(getDataFolder(), "private.yml");
val conf = YamlConfiguration.loadConfiguration(privateFile); val conf = YamlConfiguration.loadConfiguration(privateFile);
String token = conf.getString("token"); token = conf.getString("token");
if (token == null) { if (token == null) {
conf.set("token", "Token goes here"); conf.set("token", "Token goes here");
conf.save(privateFile); conf.save(privateFile);
@ -97,26 +95,25 @@ public class DiscordPlugin extends ButtonPlugin implements IListener<ReadyEvent>
getLogger().severe("Token not found! Set it in private.yml"); getLogger().severe("Token not found! Set it in private.yml");
Bukkit.getPluginManager().disablePlugin(this); Bukkit.getPluginManager().disablePlugin(this);
return; return;
} else
cb.withToken(token);
} }
dc = cb.login(); }
dc.getDispatcher().registerListener(this); val cb = new DiscordClientBuilder(token);
dc = cb.build();
dc.getEventDispatcher().on(ReadyEvent.class).subscribe(this::handleReady);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
Bukkit.getPluginManager().disablePlugin(this); Bukkit.getPluginManager().disablePlugin(this);
} }
} }
public static IGuild mainServer; public static Guild mainServer;
private static volatile BukkitTask task; private static volatile BukkitTask task;
private static volatile boolean sent = false; private static volatile boolean sent = false;
@Override public void handleReady(ReadyEvent event) {
public void handle(ReadyEvent event) {
try { try {
dc.changePresence(StatusType.DND, ActivityType.PLAYING, "booting"); dc.updatePresence(Presence.doNotDisturb(Activity.playing("booting"))).subscribe();
val tries = new AtomicInteger(); val tries = new AtomicInteger();
task = Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> { task = Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> {
tries.incrementAndGet(); tries.incrementAndGet();
@ -130,16 +127,17 @@ public class DiscordPlugin extends ButtonPlugin implements IListener<ReadyEvent>
mainServer = MainServer().get(); //Shouldn't change afterwards mainServer = MainServer().get(); //Shouldn't change afterwards
if (mainServer == null) { if (mainServer == null) {
val guilds = dc.getGuilds(); val guilds = dc.getGuilds();
if (guilds.size() == 0) if (guilds.count().blockOptional().orElse(0L) == 0L)
return; //If there are no guilds in cache, retry return; //If there are no guilds in cache, retry
mainServer = guilds.get(0); mainServer = guilds.blockFirst();
if (mainServer == null) return;
getLogger().warning("Main server set to first one: " + mainServer.getName()); getLogger().warning("Main server set to first one: " + mainServer.getName());
MainServer().set(mainServer); //Save in config MainServer().set(mainServer); //Save in config
} }
if (!TBMCCoreAPI.IsTestServer()) { //Don't change conditions here, see mainServer=devServer=null in onDisable() if (!TBMCCoreAPI.IsTestServer()) { //Don't change conditions here, see mainServer=devServer=null in onDisable()
dc.changePresence(StatusType.ONLINE, ActivityType.PLAYING, "Minecraft"); dc.updatePresence(Presence.online(Activity.playing("Minecraft")));
} else { } else {
dc.changePresence(StatusType.ONLINE, ActivityType.PLAYING, "testing"); dc.updatePresence(Presence.online(Activity.playing("testing")));
} }
SafeMode = false; SafeMode = false;
if (task != null) if (task != null)
@ -179,7 +177,7 @@ public class DiscordPlugin extends ButtonPlugin implements IListener<ReadyEvent>
getConfig().set("serverup", true); getConfig().set("serverup", true);
saveConfig(); saveConfig();
sent = true; sent = true;
if (TBMCCoreAPI.IsTestServer() && !dc.getOurUser().getName().toLowerCase().contains("test")) { if (TBMCCoreAPI.IsTestServer() && !event.getSelf().getUsername().toLowerCase().contains("test")) {
TBMCCoreAPI.SendException( TBMCCoreAPI.SendException(
"Won't load because we're in testing mode and not using a separate account.", "Won't load because we're in testing mode and not using a separate account.",
new Exception( new Exception(
@ -211,29 +209,21 @@ public class DiscordPlugin extends ButtonPlugin implements IListener<ReadyEvent>
@Override @Override
public void pluginPreDisable() { public void pluginPreDisable() {
if (ChromaBot.getInstance() == null) return; //Failed to load if (ChromaBot.getInstance() == null) return; //Failed to load
EmbedObject embed; MCChatUtils.forCustomAndAllMCChat(ch -> ch.createEmbed(ecs -> {
if (DiscordMCCommand.resetting) if (DiscordMCCommand.resetting)
embed = new EmbedBuilder().withColor(Color.ORANGE).withTitle("Discord plugin restarting").build(); ecs.setColor(Color.ORANGE).setTitle("Discord plugin restarting");
else else
embed = new EmbedBuilder().withColor(Restart ? Color.ORANGE : Color.RED) ecs.setColor(Restart ? Color.ORANGE : Color.RED)
.withTitle(Restart ? "Server restarting" : "Server stopping") .setTitle(Restart ? "Server restarting" : "Server stopping")
.withDescription( .setDescription(
Bukkit.getOnlinePlayers().size() > 0 Bukkit.getOnlinePlayers().size() > 0
? (DPUtils ? (DPUtils
.sanitizeString(Bukkit.getOnlinePlayers().stream() .sanitizeString(Bukkit.getOnlinePlayers().stream()
.map(Player::getDisplayName).collect(Collectors.joining(", "))) .map(Player::getDisplayName).collect(Collectors.joining(", ")))
+ (Bukkit.getOnlinePlayers().size() == 1 ? " was " : " were ") + (Bukkit.getOnlinePlayers().size() == 1 ? " was " : " were ")
+ "kicked the hell out.") //TODO: Make configurable + "kicked the hell out.") //TODO: Make configurable
: "") //If 'restart' is disabled then this isn't shown even if joinleave is enabled : ""); //If 'restart' is disabled then this isn't shown even if joinleave is enabled
.build(); }).block(Duration.ofSeconds(5)), ChannelconBroadcast.RESTART, false);
MCChatUtils.forCustomAndAllMCChat(ch -> {
try {
DiscordPlugin.sendMessageToChannelWait(ch, "",
embed, 5, TimeUnit.SECONDS);
} catch (TimeoutException | InterruptedException e) {
e.printStackTrace();
}
}, ChannelconBroadcast.RESTART, false);
ChromaBot.getInstance().updatePlayerList(); ChromaBot.getInstance().updatePlayerList();
} }
@ -247,8 +237,8 @@ public class DiscordPlugin extends ButtonPlugin implements IListener<ReadyEvent>
try { try {
SafeMode = true; // Stop interacting with Discord SafeMode = true; // Stop interacting with Discord
ChromaBot.delete(); ChromaBot.delete();
dc.changePresence(StatusType.IDLE, ActivityType.PLAYING, "Chromacraft"); //No longer using the same account for testing dc.updatePresence(Presence.idle(Activity.playing("Chromacraft"))).block(); //No longer using the same account for testing
dc.logout(); dc.logout().block();
//Configs are emptied so channels and servers are fetched again //Configs are emptied so channels and servers are fetched again
sent = false; sent = false;
} catch (Exception e) { } catch (Exception e) {
@ -256,67 +246,7 @@ public class DiscordPlugin extends ButtonPlugin implements IListener<ReadyEvent>
} }
} }
public static final ReactionEmoji DELIVERED_REACTION = ReactionEmoji.of(""); public static final ReactionEmoji DELIVERED_REACTION = ReactionEmoji.unicode("");
public static void sendMessageToChannel(IChannel channel, String message) {
sendMessageToChannel(channel, message, null);
}
public static void sendMessageToChannel(IChannel channel, String message, EmbedObject embed) {
try {
sendMessageToChannel(channel, message, embed, false);
} catch (TimeoutException | InterruptedException e) {
e.printStackTrace(); //Shouldn't happen, as we're not waiting on the result
}
}
public static IMessage sendMessageToChannelWait(IChannel channel, String message) throws TimeoutException, InterruptedException {
return sendMessageToChannelWait(channel, message, null);
}
public static IMessage sendMessageToChannelWait(IChannel channel, String message, EmbedObject embed) throws TimeoutException, InterruptedException {
return sendMessageToChannel(channel, message, embed, true);
}
public static IMessage sendMessageToChannelWait(IChannel channel, String message, EmbedObject embed, long timeout, TimeUnit unit) throws TimeoutException, InterruptedException {
return sendMessageToChannel(channel, message, embed, true, timeout, unit);
}
private static IMessage sendMessageToChannel(IChannel channel, String message, EmbedObject embed, boolean wait) throws TimeoutException, InterruptedException {
return sendMessageToChannel(channel, message, embed, wait, -1, null);
}
private static IMessage sendMessageToChannel(IChannel channel, String message, EmbedObject embed, boolean wait, long timeout, TimeUnit unit) throws TimeoutException, InterruptedException {
if (message.length() > 1980) {
message = message.substring(0, 1980);
DPUtils.getLogger()
.warning("Message was too long to send to discord and got truncated. In " + channel.getName());
}
try {
MCChatUtils.resetLastMessage(channel); // If this is a chat message, it'll be set again
final String content = message;
RequestBuffer.IRequest<IMessage> r = () -> embed == null ? channel.sendMessage(content)
: channel.sendMessage(content, embed, false);
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 (TimeoutException | InterruptedException e) {
throw e;
} catch (Exception e) {
DPUtils.getLogger().warning(
"Failed to deliver message to Discord! Channel: " + channel.getName() + " Message: " + message);
throw new RuntimeException(e);
}
}
public static Permission perms; public static Permission perms;

View file

@ -5,6 +5,10 @@ import buttondevteam.core.component.channel.Channel;
import buttondevteam.discordplugin.*; import buttondevteam.discordplugin.*;
import buttondevteam.discordplugin.broadcaster.GeneralEventBroadcasterModule; import buttondevteam.discordplugin.broadcaster.GeneralEventBroadcasterModule;
import buttondevteam.lib.TBMCSystemChatEvent; import buttondevteam.lib.TBMCSystemChatEvent;
import discord4j.core.object.entity.Message;
import discord4j.core.object.entity.MessageChannel;
import discord4j.core.object.entity.TextChannel;
import discord4j.core.object.entity.User;
import io.netty.util.collection.LongObjectHashMap; import io.netty.util.collection.LongObjectHashMap;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.experimental.var; import lombok.experimental.var;
@ -16,9 +20,6 @@ import org.bukkit.event.HandlerList;
import org.bukkit.plugin.AuthorNagException; import org.bukkit.plugin.AuthorNagException;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredListener; import org.bukkit.plugin.RegisteredListener;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IMessage;
import sx.blah.discord.handle.obj.IUser;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.Arrays; import java.util.Arrays;
@ -34,23 +35,21 @@ public class MCChatUtils {
/** /**
* May contain P&lt;DiscordID&gt; as key for public chat * May contain P&lt;DiscordID&gt; as key for public chat
*/ */
public static final HashMap<String, HashMap<IChannel, DiscordSender>> UnconnectedSenders = new HashMap<>(); public static final HashMap<String, HashMap<Channel, DiscordSender>> UnconnectedSenders = new HashMap<>();
public static final HashMap<String, HashMap<IChannel, DiscordConnectedPlayer>> ConnectedSenders = new HashMap<>(); public static final HashMap<String, HashMap<Channel, DiscordConnectedPlayer>> ConnectedSenders = new HashMap<>();
/** /**
* May contain P&lt;DiscordID&gt; as key for public chat * May contain P&lt;DiscordID&gt; as key for public chat
*/ */
public static final HashMap<String, HashMap<IChannel, DiscordPlayerSender>> OnlineSenders = new HashMap<>(); public static final HashMap<String, HashMap<Channel, DiscordPlayerSender>> OnlineSenders = new HashMap<>();
static @Nullable LastMsgData lastmsgdata; static @Nullable LastMsgData lastmsgdata;
static LongObjectHashMap<IMessage> lastmsgfromd = new LongObjectHashMap<>(); // Last message sent by a Discord user, used for clearing checkmarks static LongObjectHashMap<Message> lastmsgfromd = new LongObjectHashMap<>(); // Last message sent by a Discord user, used for clearing checkmarks
private static MinecraftChatModule module; private static MinecraftChatModule module;
public static void updatePlayerList() { public static void updatePlayerList() {
if (notEnabled()) return; if (notEnabled()) return;
DPUtils.performNoWait(() -> {
if (lastmsgdata != null) if (lastmsgdata != null)
updatePL(lastmsgdata); updatePL(lastmsgdata);
MCChatCustom.lastmsgCustom.forEach(MCChatUtils::updatePL); MCChatCustom.lastmsgCustom.forEach(MCChatUtils::updatePL);
});
} }
private static boolean notEnabled() { private static boolean notEnabled() {
@ -64,8 +63,8 @@ public class MCChatUtils {
} }
private static void updatePL(LastMsgData lmd) { private static void updatePL(LastMsgData lmd) {
String topic = lmd.channel.getTopic(); String topic = lmd.channel.getTopic().orElse("");
if (topic == null || topic.length() == 0) if (topic.length() == 0)
topic = ".\n----\nMinecraft chat\n----\n."; topic = ".\n----\nMinecraft chat\n----\n.";
String[] s = topic.split("\\n----\\n"); String[] s = topic.split("\\n----\\n");
if (s.length < 3) if (s.length < 3)
@ -74,16 +73,16 @@ public class MCChatUtils {
+ " online"; + " online";
s[s.length - 1] = "Players: " + Bukkit.getOnlinePlayers().stream() s[s.length - 1] = "Players: " + Bukkit.getOnlinePlayers().stream()
.map(p -> DPUtils.sanitizeString(p.getDisplayName())).collect(Collectors.joining(", ")); .map(p -> DPUtils.sanitizeString(p.getDisplayName())).collect(Collectors.joining(", "));
lmd.channel.changeTopic(String.join("\n----\n", s)); lmd.channel.edit(tce -> tce.setTopic(String.join("\n----\n", s)).setReason("Player list update")).subscribe(); //Don't wait
} }
public static <T extends DiscordSenderBase> T addSender(HashMap<String, HashMap<IChannel, T>> senders, public static <T extends DiscordSenderBase> T addSender(HashMap<Long, HashMap<Channel, T>> senders,
IUser user, T sender) { User user, T sender) {
return addSender(senders, user.getStringID(), sender); return addSender(senders, user.getId().asLong(), sender);
} }
public static <T extends DiscordSenderBase> T addSender(HashMap<String, HashMap<IChannel, T>> senders, public static <T extends DiscordSenderBase> T addSender(HashMap<Long, HashMap<Channel, T>> senders,
String did, T sender) { long did, T sender) {
var map = senders.get(did); var map = senders.get(did);
if (map == null) if (map == null)
map = new HashMap<>(); map = new HashMap<>();
@ -92,23 +91,23 @@ public class MCChatUtils {
return sender; return sender;
} }
public static <T extends DiscordSenderBase> T getSender(HashMap<String, HashMap<IChannel, T>> senders, public static <T extends DiscordSenderBase> T getSender(HashMap<Long, HashMap<Channel, T>> senders,
IChannel channel, IUser user) { Channel channel, User user) {
var map = senders.get(user.getStringID()); var map = senders.get(user.getId().asLong());
if (map != null) if (map != null)
return map.get(channel); return map.get(channel);
return null; return null;
} }
public static <T extends DiscordSenderBase> T removeSender(HashMap<String, HashMap<IChannel, T>> senders, public static <T extends DiscordSenderBase> T removeSender(HashMap<Long, HashMap<Channel, T>> senders,
IChannel channel, IUser user) { Channel channel, User user) {
var map = senders.get(user.getStringID()); var map = senders.get(user.getId().asLong());
if (map != null) if (map != null)
return map.remove(channel); return map.remove(channel);
return null; return null;
} }
public static void forAllMCChat(Consumer<IChannel> action) { public static void forAllMCChat(Consumer<MessageChannel> action) {
if (notEnabled()) return; if (notEnabled()) return;
action.accept(module.chatChannel().get()); action.accept(module.chatChannel().get());
for (LastMsgData data : MCChatPrivate.lastmsgPerUser) for (LastMsgData data : MCChatPrivate.lastmsgPerUser)
@ -123,7 +122,7 @@ public class MCChatUtils {
* @param toggle The toggle to check * @param toggle The toggle to check
* @param hookmsg Whether the message is also sent from the hook * @param hookmsg Whether the message is also sent from the hook
*/ */
public static void forCustomAndAllMCChat(Consumer<IChannel> action, @Nullable ChannelconBroadcast toggle, boolean hookmsg) { public static void forCustomAndAllMCChat(Consumer<MessageChannel> action, @Nullable ChannelconBroadcast toggle, boolean hookmsg) {
if (notEnabled()) return; if (notEnabled()) return;
if (!GeneralEventBroadcasterModule.isHooked() || !hookmsg) if (!GeneralEventBroadcasterModule.isHooked() || !hookmsg)
forAllMCChat(action); forAllMCChat(action);
@ -141,7 +140,7 @@ public class MCChatUtils {
* @param sender The sender to check perms of or null to send to all that has it toggled * @param sender The sender to check perms of or null to send to all that has it toggled
* @param toggle The toggle to check or null to send to all allowed * @param toggle The toggle to check or null to send to all allowed
*/ */
public static void forAllowedCustomMCChat(Consumer<IChannel> action, @Nullable CommandSender sender, @Nullable ChannelconBroadcast toggle) { public static void forAllowedCustomMCChat(Consumer<MessageChannel> action, @Nullable CommandSender sender, @Nullable ChannelconBroadcast toggle) {
if (notEnabled()) return; if (notEnabled()) return;
MCChatCustom.lastmsgCustom.stream().filter(clmd -> { MCChatCustom.lastmsgCustom.stream().filter(clmd -> {
//new TBMCChannelConnectFakeEvent(sender, clmd.mcchannel).shouldSendTo(clmd.dcp) - Thought it was this simple hehe - Wait, it *should* be this simple //new TBMCChannelConnectFakeEvent(sender, clmd.mcchannel).shouldSendTo(clmd.dcp) - Thought it was this simple hehe - Wait, it *should* be this simple
@ -161,19 +160,19 @@ public class MCChatUtils {
* @param toggle The toggle to check or null to send to all allowed * @param toggle The toggle to check or null to send to all allowed
* @param hookmsg Whether the message is also sent from the hook * @param hookmsg Whether the message is also sent from the hook
*/ */
public static void forAllowedCustomAndAllMCChat(Consumer<IChannel> action, @Nullable CommandSender sender, @Nullable ChannelconBroadcast toggle, boolean hookmsg) { public static void forAllowedCustomAndAllMCChat(Consumer<MessageChannel> action, @Nullable CommandSender sender, @Nullable ChannelconBroadcast toggle, boolean hookmsg) {
if (notEnabled()) return; if (notEnabled()) return;
if (!GeneralEventBroadcasterModule.isHooked() || !hookmsg) if (!GeneralEventBroadcasterModule.isHooked() || !hookmsg)
forAllMCChat(action); forAllMCChat(action);
forAllowedCustomMCChat(action, sender, toggle); forAllowedCustomMCChat(action, sender, toggle);
} }
public static Consumer<IChannel> send(String message) { public static Consumer<MessageChannel> send(String message) {
return ch -> DiscordPlugin.sendMessageToChannel(ch, DPUtils.sanitizeString(message)); return ch -> ch.createMessage(DPUtils.sanitizeString(message)).subscribe();
} }
public static void forAllowedMCChat(Consumer<IChannel> action, TBMCSystemChatEvent event) { public static void forAllowedMCChat(Consumer<MessageChannel> action, TBMCSystemChatEvent event) {
if (notEnabled()) return; if (notEnabled()) return
if (event.getChannel().isGlobal()) if (event.getChannel().isGlobal())
action.accept(module.chatChannel().get()); action.accept(module.chatChannel().get());
for (LastMsgData data : MCChatPrivate.lastmsgPerUser) for (LastMsgData data : MCChatPrivate.lastmsgPerUser)
@ -189,7 +188,7 @@ public class MCChatUtils {
/** /**
* This method will find the best sender to use: if the player is online, use that, if not but connected then use that etc. * This method will find the best sender to use: if the player is online, use that, if not but connected then use that etc.
*/ */
static DiscordSenderBase getSender(IChannel channel, final IUser author) { static DiscordSenderBase getSender(Channel channel, final User author) {
//noinspection OptionalGetWithoutIsPresent //noinspection OptionalGetWithoutIsPresent
return Stream.<Supplier<Optional<DiscordSenderBase>>>of( // https://stackoverflow.com/a/28833677/2703239 return Stream.<Supplier<Optional<DiscordSenderBase>>>of( // https://stackoverflow.com/a/28833677/2703239
() -> Optional.ofNullable(getSender(OnlineSenders, channel, author)), // Find first non-null () -> Optional.ofNullable(getSender(OnlineSenders, channel, author)), // Find first non-null
@ -205,7 +204,7 @@ public class MCChatUtils {
* *
* @param channel The channel to reset in - the process is slightly different for the public, private and custom chats * @param channel The channel to reset in - the process is slightly different for the public, private and custom chats
*/ */
public static void resetLastMessage(IChannel channel) { public static void resetLastMessage(Channel channel) {
if (notEnabled()) return; if (notEnabled()) return;
if (channel.getLongID() == module.chatChannel().get().getLongID()) { if (channel.getLongID() == module.chatChannel().get().getLongID()) {
(lastmsgdata == null ? lastmsgdata = new LastMsgData(module.chatChannel().get(), null) (lastmsgdata == null ? lastmsgdata = new LastMsgData(module.chatChannel().get(), null)
@ -286,11 +285,11 @@ public class MCChatUtils {
@RequiredArgsConstructor @RequiredArgsConstructor
public static class LastMsgData { public static class LastMsgData {
public IMessage message; public Message message;
public long time; public long time;
public String content; public String content;
public final IChannel channel; public final TextChannel channel;
public Channel mcchannel; public Channel mcchannel;
public final IUser user; public final User user;
} }
} }