Refactoring...

This commit is contained in:
Norbi Peti 2019-04-24 16:50:00 +02:00
parent 038cb98f1a
commit 59066ce09a
16 changed files with 181 additions and 161 deletions

View file

@ -8,6 +8,7 @@ import discord4j.core.object.entity.*;
import discord4j.core.object.util.Snowflake; import discord4j.core.object.util.Snowflake;
import discord4j.core.spec.EmbedCreateSpec; import discord4j.core.spec.EmbedCreateSpec;
import lombok.val; import lombok.val;
import reactor.core.publisher.Mono;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -116,4 +117,14 @@ public final class DPUtils {
return false; return false;
} }
public static Mono<Message> reply(Message original, @Nullable MessageChannel channel, String message) {
Mono<MessageChannel> ch;
if (channel == null)
ch = original.getChannel();
else
ch = Mono.just(channel);
return ch.flatMap(chan -> chan.createMessage((original.getAuthor().isPresent()
? original.getAuthor().get().getMention() + ", " : "") + message));
}
} }

View file

@ -1,5 +1,9 @@
package buttondevteam.discordplugin; package buttondevteam.discordplugin;
import discord4j.core.object.entity.Member;
import discord4j.core.object.entity.MessageChannel;
import discord4j.core.object.entity.User;
import lombok.val;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -8,8 +12,6 @@ import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionAttachment; import org.bukkit.permissions.PermissionAttachment;
import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import sx.blah.discord.handle.obj.User;
import sx.blah.discord.handle.obj.MessageChannel;
import java.util.Set; import java.util.Set;
@ -20,7 +22,8 @@ public class DiscordSender extends DiscordSenderBase implements CommandSender {
public DiscordSender(User user, MessageChannel channel) { public DiscordSender(User user, MessageChannel channel) {
super(user, channel); super(user, channel);
name = user == null ? "Discord user" : user.getDisplayName(DiscordPlugin.mainServer); val def = "Discord user";
name = user == null ? def : user.asMember(DiscordPlugin.mainServer.getId()).blockOptional().map(Member::getDisplayName).orElse(def);
} }
public DiscordSender(User user, MessageChannel channel, String name) { public DiscordSender(User user, MessageChannel channel, String name) {

View file

@ -1,11 +0,0 @@
package buttondevteam.discordplugin;
import sx.blah.discord.handle.obj.IDiscordObject;
import sx.blah.discord.util.DiscordException;
import sx.blah.discord.util.MissingPermissionsException;
import sx.blah.discord.util.RateLimitException;
@FunctionalInterface
public interface DiscordSupplier<T extends IDiscordObject<T>> {
T get() throws DiscordException, RateLimitException, MissingPermissionsException;
}

View file

@ -18,8 +18,9 @@ public class Command2DCSender implements Command2Sender {
message = DPUtils.sanitizeString(message); message = DPUtils.sanitizeString(message);
message = Character.toLowerCase(message.charAt(0)) + message.substring(1); message = Character.toLowerCase(message.charAt(0)) + message.substring(1);
val msg = message; val msg = message;
this.message.getChannel().flatMap(ch -> ch.createMessage(this.message.getAuthorAsMember().a-> val author = this.message.getAuthorAsMember().block();
a.getNicknameMention() + ", " + msg))) if (author == null) return;
this.message.getChannel().subscribe(ch -> ch.createMessage(author.getNicknameMention() + ", " + msg));
} }
@Override @Override

View file

@ -7,13 +7,14 @@ import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.TBMCExceptionEvent; import buttondevteam.lib.TBMCExceptionEvent;
import buttondevteam.lib.architecture.Component; import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.architecture.ConfigData; import buttondevteam.lib.architecture.ConfigData;
import discord4j.core.object.entity.Guild;
import discord4j.core.object.entity.GuildChannel;
import discord4j.core.object.entity.MessageChannel;
import discord4j.core.object.entity.Role;
import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.lang.exception.ExceptionUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import sx.blah.discord.handle.obj.IGuild;
import sx.blah.discord.handle.obj.IRole;
import sx.blah.discord.handle.obj.MessageChannel;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -49,19 +50,19 @@ public class ExceptionListenerModule extends Component<DiscordPlugin> implements
try { try {
MessageChannel channel = getChannel(); MessageChannel channel = getChannel();
assert channel != null; assert channel != null;
IRole coderRole = instance.pingRole(channel.getGuild()).get(); Role coderRole = instance.pingRole(((GuildChannel) channel).getGuild().block()).get();
StringBuilder sb = TBMCCoreAPI.IsTestServer() ? new StringBuilder() StringBuilder sb = TBMCCoreAPI.IsTestServer() ? new StringBuilder()
: new StringBuilder(coderRole == null ? "" : coderRole.mention()).append("\n"); : new StringBuilder(coderRole == null ? "" : coderRole.getMention()).append("\n");
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("\tat ") || s.contains("\tat buttondevteam.")) .filter(s -> !s.contains("\tat ") || s.contains("\tat buttondevteam."))
.collect(Collectors.joining("\n")); .collect(Collectors.joining("\n"));
if (stackTrace.length() > 1800) if (sb.length() + stackTrace.length() >= 2000)
stackTrace = stackTrace.substring(0, 1800); stackTrace = stackTrace.substring(0, 1999 - sb.length());
sb.append(stackTrace).append("\n"); sb.append(stackTrace).append("\n");
sb.append("```"); sb.append("```");
DiscordPlugin.sendMessageToChannel(channel, sb.toString()); //Instance isn't null here channel.createMessage(sb.toString()).subscribe();
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
@ -78,7 +79,7 @@ public class ExceptionListenerModule extends Component<DiscordPlugin> implements
return DPUtils.channelData(getConfig(), "channel", 239519012529111040L); return DPUtils.channelData(getConfig(), "channel", 239519012529111040L);
} }
private ConfigData<IRole> pingRole(IGuild guild) { private ConfigData<Role> pingRole(Guild guild) {
return DPUtils.roleData(getConfig(), "pingRole", "Coder", guild); return DPUtils.roleData(getConfig(), "pingRole", "Coder", guild);
} }

View file

@ -7,14 +7,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 com.google.common.collect.Lists; import com.google.common.collect.Lists;
import discord4j.core.event.domain.PresenceUpdateEvent;
import discord4j.core.object.entity.*;
import discord4j.core.object.presence.Status;
import lombok.val; import lombok.val;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import sx.blah.discord.handle.impl.events.user.PresenceUpdateEvent;
import sx.blah.discord.handle.obj.*;
import sx.blah.discord.util.EmbedBuilder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -83,7 +83,7 @@ public class FunModule extends Component<DiscordPlugin> implements Listener {
public static boolean executeMemes(Message message) { public static boolean executeMemes(Message message) {
val fm = ComponentManager.getIfEnabled(FunModule.class); val fm = ComponentManager.getIfEnabled(FunModule.class);
if (fm == null) return false; if (fm == null) return false;
String msglowercased = message.getContent().toLowerCase(); String msglowercased = message.getContent().orElse("").toLowerCase();
lastlist++; lastlist++;
if (lastlist > 5) { if (lastlist > 5) {
ListC = 0; ListC = 0;
@ -91,7 +91,7 @@ public class FunModule extends Component<DiscordPlugin> implements Listener {
} }
if (msglowercased.equals("list") && Bukkit.getOnlinePlayers().size() == lastlistp && ListC++ > 2) // Lowered already if (msglowercased.equals("list") && Bukkit.getOnlinePlayers().size() == lastlistp && ListC++ > 2) // Lowered already
{ {
message.reply("Stop it. You know the answer."); DPUtils.reply(message, null, "Stop it. You know the answer.").subscribe();
lastlist = 0; lastlist = 0;
lastlistp = (short) Bukkit.getOnlinePlayers().size(); lastlistp = (short) Bukkit.getOnlinePlayers().size();
return true; //Handled return true; //Handled
@ -103,7 +103,7 @@ public class FunModule extends Component<DiscordPlugin> implements Listener {
if (usableServerReadyStrings.size() == 0) if (usableServerReadyStrings.size() == 0)
fm.createUsableServerReadyStrings(); fm.createUsableServerReadyStrings();
next = usableServerReadyStrings.remove(serverReadyRandom.nextInt(usableServerReadyStrings.size())); next = usableServerReadyStrings.remove(serverReadyRandom.nextInt(usableServerReadyStrings.size()));
DiscordPlugin.sendMessageToChannel(message.getChannel(), serverReadyStrings[next]); DPUtils.reply(message, null, serverReadyStrings[next]).subscribe();
return false; //Still process it as a command/mcchat if needed return false; //Still process it as a command/mcchat if needed
} }
return false; return false;
@ -114,7 +114,7 @@ public class FunModule extends Component<DiscordPlugin> implements Listener {
ListC = 0; ListC = 0;
} }
private ConfigData<IRole> fullHouseDevRole(IGuild guild) { private ConfigData<Role> fullHouseDevRole(Guild guild) {
return DPUtils.roleData(getConfig(), "fullHouseDevRole", "Developer", guild); return DPUtils.roleData(getConfig(), "fullHouseDevRole", "Developer", guild);
} }
@ -125,26 +125,26 @@ public class FunModule extends Component<DiscordPlugin> implements Listener {
private static long lasttime = 0; private static long lasttime = 0;
@SuppressWarnings("ConstantConditions")
public static void handleFullHouse(PresenceUpdateEvent event) { public static void handleFullHouse(PresenceUpdateEvent event) {
val fm = ComponentManager.getIfEnabled(FunModule.class); val fm = ComponentManager.getIfEnabled(FunModule.class);
if (fm == null) return; if (fm == null) return;
val channel = fm.fullHouseChannel().get(); val channel = fm.fullHouseChannel().get();
if (channel == null) return; if (channel == null) return;
val devrole = fm.fullHouseDevRole(channel.getGuild()).get(); val devrole = fm.fullHouseDevRole(((GuildChannel) channel).getGuild().block()).get();
if (devrole == null) return; if (devrole == null) return;
if (event.getOldPresence().getStatus().equals(StatusType.OFFLINE) if (event.getOld().map(p -> p.getStatus().equals(Status.OFFLINE)).orElse(false)
&& !event.getNewPresence().getStatus().equals(StatusType.OFFLINE) && !event.getCurrent().getStatus().equals(Status.OFFLINE)
&& event.getUser().getRolesForGuild(channel.getGuild()).stream() && event.getMember().flatMap(m -> m.getRoles()
.anyMatch(r -> r.getId().asLong() == devrole.getId().asLong()) .any(r -> r.getId().asLong() == devrole.getId().asLong())).block()
&& channel.getGuild().getUsersByRole(devrole).stream() && event.getGuild().flatMap(g -> g.getMembers().filter(m -> m.getRoleIds().stream().anyMatch(s -> s.equals(devrole.getId())))
.noneMatch(u -> u.getPresence().getStatus().equals(StatusType.OFFLINE)) .flatMap(Member::getPresence).all(pr -> !pr.getStatus().equals(Status.OFFLINE))).block()
&& lasttime + 10 < TimeUnit.NANOSECONDS.toHours(System.nanoTime()) && lasttime + 10 < TimeUnit.NANOSECONDS.toHours(System.nanoTime())
&& Calendar.getInstance().get(Calendar.DAY_OF_MONTH) % 5 == 0) { && Calendar.getInstance().get(Calendar.DAY_OF_MONTH) % 5 == 0) {
DiscordPlugin.sendMessageToChannel(channel, "Full house!", channel.createMessage(mcs -> mcs.setContent("Full house!").setEmbed(ecs ->
new EmbedBuilder() ecs.setImage(
.withImage(
"https://cdn.discordapp.com/attachments/249295547263877121/249687682618359808/poker-hand-full-house-aces-kings-playing-cards-15553791.png") "https://cdn.discordapp.com/attachments/249295547263877121/249687682618359808/poker-hand-full-house-aces-kings-playing-cards-15553791.png")
.build()); ));
lasttime = TimeUnit.NANOSECONDS.toHours(System.nanoTime()); lasttime = TimeUnit.NANOSECONDS.toHours(System.nanoTime());
} }
} }

View file

@ -1,15 +1,14 @@
package buttondevteam.discordplugin.listeners; package buttondevteam.discordplugin.listeners;
import buttondevteam.discordplugin.DPUtils;
import buttondevteam.discordplugin.DiscordPlugin; import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.commands.Command2DCSender; import buttondevteam.discordplugin.commands.Command2DCSender;
import buttondevteam.lib.TBMCCoreAPI; import buttondevteam.lib.TBMCCoreAPI;
import discord4j.core.object.entity.Message; import discord4j.core.object.entity.Message;
import discord4j.core.object.entity.MessageChannel; import discord4j.core.object.entity.MessageChannel;
import discord4j.core.object.entity.PrivateChannel; import discord4j.core.object.entity.PrivateChannel;
import discord4j.core.object.entity.Role;
import lombok.val; import lombok.val;
import sx.blah.discord.handle.obj.IRole;
import sx.blah.discord.handle.obj.Message;
import sx.blah.discord.handle.obj.MessageChannel;
public class CommandListener { public class CommandListener {
/** /**
@ -41,26 +40,24 @@ public class CommandListener {
final String mentionNick = member.getNicknameMention(); final String mentionNick = member.getNicknameMention();
boolean gotmention = checkanddeletemention(cmdwithargs, mention, message); boolean gotmention = checkanddeletemention(cmdwithargs, mention, message);
gotmention = checkanddeletemention(cmdwithargs, mentionNick, message) || gotmention; gotmention = checkanddeletemention(cmdwithargs, mentionNick, message) || gotmention;
for (String mentionRole : (Iterable<String>) message.getRoleMentions().filter(r -> member.getRoles().filter(r)).map(IRole::mention)::iterator) //TODO: Remove all that matches val mentions = message.getRoleMentions();
for (String mentionRole : member.getRoles().filter(r -> mentions.any(rr -> rr.getName().equals(r.getName())).blockOptional().orElse(false)).map(Role::getMention).toIterable())
gotmention = checkanddeletemention(cmdwithargs, mentionRole, message) || gotmention; // Delete all mentions gotmention = checkanddeletemention(cmdwithargs, mentionRole, message) || gotmention; // Delete all mentions
if (mentionedonly && !gotmention) { if (mentionedonly && !gotmention)
message.getChannel().setTypingStatus(false);
return false; return false;
} channel.type().subscribe();
message.getChannel().setTypingStatus(true);
String cmdwithargsString = cmdwithargs.toString(); String cmdwithargsString = cmdwithargs.toString();
try { try {
if (!DiscordPlugin.plugin.getManager().handleCommand(new Command2DCSender(message), cmdwithargsString)) if (!DiscordPlugin.plugin.getManager().handleCommand(new Command2DCSender(message), cmdwithargsString))
message.reply("Unknown command. Do " + DiscordPlugin.getPrefix() + "help for help.\n" + cmdwithargsString); DPUtils.reply(message, channel, "Unknown command. Do " + DiscordPlugin.getPrefix() + "help for help.\n" + cmdwithargsString).subscribe();
} catch (Exception e) { } catch (Exception e) {
TBMCCoreAPI.SendException("Failed to process Discord command: " + cmdwithargsString, e); TBMCCoreAPI.SendException("Failed to process Discord command: " + cmdwithargsString, e);
} }
message.getChannel().setTypingStatus(false);
return true; return true;
} }
private static boolean checkanddeletemention(StringBuilder cmdwithargs, String mention, Message message) { private static boolean checkanddeletemention(StringBuilder cmdwithargs, String mention, Message message) {
if (message.getContent().startsWith(mention)) // TODO: Resolve mentions: Compound arguments, either a mention or text if (message.getContent().orElse("").startsWith(mention)) // TODO: Resolve mentions: Compound arguments, either a mention or text
if (cmdwithargs.length() > mention.length() + 1) { if (cmdwithargs.length() > mention.length() + 1) {
int i = cmdwithargs.indexOf(" ", mention.length()); int i = cmdwithargs.indexOf(" ", mention.length());
if (i == -1) if (i == -1)

View file

@ -14,12 +14,6 @@ import discord4j.core.event.domain.role.RoleCreateEvent;
import discord4j.core.event.domain.role.RoleDeleteEvent; import discord4j.core.event.domain.role.RoleDeleteEvent;
import discord4j.core.event.domain.role.RoleUpdateEvent; import discord4j.core.event.domain.role.RoleUpdateEvent;
import lombok.val; import lombok.val;
import sx.blah.discord.api.events.IListener;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
import sx.blah.discord.handle.impl.events.guild.role.RoleCreateEvent;
import sx.blah.discord.handle.impl.events.guild.role.RoleDeleteEvent;
import sx.blah.discord.handle.impl.events.guild.role.RoleUpdateEvent;
import sx.blah.discord.handle.impl.events.user.PresenceUpdateEvent;
public class CommonListeners { public class CommonListeners {
@ -36,7 +30,8 @@ public class CommonListeners {
dispatcher.on(MessageCreateEvent.class).subscribe(event->{ dispatcher.on(MessageCreateEvent.class).subscribe(event->{
if (DiscordPlugin.SafeMode) if (DiscordPlugin.SafeMode)
return; return;
if (event.getMessage().getAuthor().isBot()) val author = event.getMessage().getAuthor();
if (!author.isPresent() || author.get().isBot())
return; return;
if (FunModule.executeMemes(event.getMessage())) if (FunModule.executeMemes(event.getMessage()))
return; return;

View file

@ -5,18 +5,22 @@ import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.commands.ConnectCommand; import buttondevteam.discordplugin.commands.ConnectCommand;
import buttondevteam.lib.player.TBMCPlayerGetInfoEvent; import buttondevteam.lib.player.TBMCPlayerGetInfoEvent;
import buttondevteam.lib.player.TBMCPlayerJoinEvent; import buttondevteam.lib.player.TBMCPlayerJoinEvent;
import discord4j.core.object.entity.Member;
import discord4j.core.object.entity.User;
import discord4j.core.object.util.Snowflake;
import lombok.val;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.server.ServerCommandEvent; import org.bukkit.event.server.ServerCommandEvent;
import sx.blah.discord.handle.obj.User;
public class MCListener implements Listener { public class MCListener implements Listener {
@EventHandler @EventHandler
public void onPlayerJoin(TBMCPlayerJoinEvent e) { public void onPlayerJoin(TBMCPlayerJoinEvent e) {
if (ConnectCommand.WaitingToConnect.containsKey(e.GetPlayer().PlayerName().get())) { if (ConnectCommand.WaitingToConnect.containsKey(e.GetPlayer().PlayerName().get())) {
@SuppressWarnings("ConstantConditions") User user = DiscordPlugin.dc @SuppressWarnings("ConstantConditions") User user = DiscordPlugin.dc
.getUserByID(Long.parseLong(ConnectCommand.WaitingToConnect.get(e.GetPlayer().PlayerName().get()))); .getUserById(Snowflake.of(ConnectCommand.WaitingToConnect.get(e.GetPlayer().PlayerName().get()))).block();
e.getPlayer().sendMessage("§bTo connect with the Discord account @" + user.getName() + "#" + user.getDiscriminator() if (user == null) return;
e.getPlayer().sendMessage("§bTo connect with the Discord account @" + user.getUsername() + "#" + user.getDiscriminator()
+ " do /discord accept"); + " do /discord accept");
e.getPlayer().sendMessage("§bIf it wasn't you, do /discord decline"); e.getPlayer().sendMessage("§bIf it wasn't you, do /discord decline");
} }
@ -29,11 +33,18 @@ public class MCListener implements Listener {
DiscordPlayer dp = e.getPlayer().getAs(DiscordPlayer.class); DiscordPlayer dp = e.getPlayer().getAs(DiscordPlayer.class);
if (dp == null || dp.getDiscordID() == null || dp.getDiscordID().equals("")) if (dp == null || dp.getDiscordID() == null || dp.getDiscordID().equals(""))
return; return;
User user = DiscordPlugin.dc.getUserByID(Long.parseLong(dp.getDiscordID())); User user = DiscordPlugin.dc.getUserById(Snowflake.of(dp.getDiscordID())).block();
e.addInfo("Discord tag: " + user.getName() + "#" + user.getDiscriminator()); if (user == null) return;
e.addInfo(user.getPresence().getStatus().toString()); e.addInfo("Discord tag: " + user.getUsername() + "#" + user.getDiscriminator());
if (user.getPresence().getActivity().isPresent() && user.getPresence().getText().isPresent()) Member member = user.asMember(DiscordPlugin.mainServer.getId()).block();
e.addInfo(user.getPresence().getActivity().get() + ": " + user.getPresence().getText().get()); if (member == null) return;
val pr = member.getPresence().block();
if (pr == null) return;
e.addInfo(pr.getStatus().toString());
if (pr.getActivity().isPresent()) {
val activity = pr.getActivity().get();
e.addInfo(activity.getType() + ": " + activity.getName());
}
} }
@EventHandler @EventHandler

View file

@ -9,15 +9,16 @@ import buttondevteam.lib.TBMCSystemChatEvent;
import buttondevteam.lib.chat.Command2; import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass; import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.player.TBMCPlayer; import buttondevteam.lib.player.TBMCPlayer;
import discord4j.core.object.entity.Message;
import discord4j.core.object.util.Permission;
import lombok.RequiredArgsConstructor;
import lombok.val; import lombok.val;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import sx.blah.discord.handle.obj.Message;
import sx.blah.discord.handle.obj.Permissions;
import sx.blah.discord.util.PermissionUtils;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Objects;
import java.util.function.Supplier; import java.util.function.Supplier;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -32,15 +33,17 @@ import java.util.stream.Collectors;
"Mentioning the bot is needed in this case because the / prefix only works in #bot.", // "Mentioning the bot is needed in this case because the / prefix only works in #bot.", //
"Invite link: <https://discordapp.com/oauth2/authorize?client_id=226443037893591041&scope=bot&permissions=268509264>" // "Invite link: <https://discordapp.com/oauth2/authorize?client_id=226443037893591041&scope=bot&permissions=268509264>" //
}) })
@RequiredArgsConstructor
public class ChannelconCommand extends ICommand2DC { public class ChannelconCommand extends ICommand2DC {
private final MinecraftChatModule module;
@Command2.Subcommand @Command2.Subcommand
public boolean remove(Command2DCSender sender) { public boolean remove(Command2DCSender sender) {
val message = sender.getMessage(); val message = sender.getMessage();
if (checkPerms(message)) return true; if (checkPerms(message)) return true;
if (MCChatCustom.removeCustomChat(message.getChannel())) if (MCChatCustom.removeCustomChat(message.getChannelId()))
message.reply("channel connection removed."); DPUtils.reply(message, null, "channel connection removed.").subscribe();
else else
message.reply("this channel isn't connected."); DPUtils.reply(message, null, "this channel isn't connected.").subscribe();
return true; return true;
} }
@ -48,13 +51,13 @@ public class ChannelconCommand extends ICommand2DC {
public boolean toggle(Command2DCSender sender, @Command2.OptionalArg String toggle) { public boolean toggle(Command2DCSender sender, @Command2.OptionalArg String toggle) {
val message = sender.getMessage(); val message = sender.getMessage();
if (checkPerms(message)) return true; if (checkPerms(message)) return true;
val cc = MCChatCustom.getCustomChat(message.getChannel()); val cc = MCChatCustom.getCustomChat(message.getChannelId());
if (cc == null) if (cc == null)
return respond(sender, "this channel isn't connected."); return respond(sender, "this channel isn't connected.");
Supplier<String> togglesString = () -> Arrays.stream(ChannelconBroadcast.values()).map(t -> t.toString().toLowerCase() + ": " + ((cc.toggles & t.flag) == 0 ? "disabled" : "enabled")).collect(Collectors.joining("\n")) Supplier<String> togglesString = () -> Arrays.stream(ChannelconBroadcast.values()).map(t -> t.toString().toLowerCase() + ": " + ((cc.toggles & t.flag) == 0 ? "disabled" : "enabled")).collect(Collectors.joining("\n"))
+ "\n\n" + TBMCSystemChatEvent.BroadcastTarget.stream().map(target -> target.getName() + ": " + (cc.brtoggles.contains(target) ? "enabled" : "disabled")).collect(Collectors.joining("\n")); + "\n\n" + TBMCSystemChatEvent.BroadcastTarget.stream().map(target -> target.getName() + ": " + (cc.brtoggles.contains(target) ? "enabled" : "disabled")).collect(Collectors.joining("\n"));
if (toggle == null) { if (toggle == null) {
message.reply("toggles:\n" + togglesString.get()); DPUtils.reply(message, null, "toggles:\n" + togglesString.get()).subscribe();
return true; return true;
} }
String arg = toggle.toUpperCase(); String arg = toggle.toUpperCase();
@ -62,7 +65,7 @@ public class ChannelconCommand extends ICommand2DC {
if (!b.isPresent()) { if (!b.isPresent()) {
val bt = TBMCSystemChatEvent.BroadcastTarget.get(arg); val bt = TBMCSystemChatEvent.BroadcastTarget.get(arg);
if (bt == null) { if (bt == null) {
message.reply("cannot find toggle. Toggles:\n" + togglesString.get()); DPUtils.reply(message, null, "cannot find toggle. Toggles:\n" + togglesString.get()).subscribe();
return true; return true;
} }
final boolean add; final boolean add;
@ -80,7 +83,7 @@ public class ChannelconCommand extends ICommand2DC {
//1 1 | 0 //1 1 | 0
// XOR // XOR
cc.toggles ^= b.get().flag; cc.toggles ^= b.get().flag;
message.reply("'" + b.get().toString().toLowerCase() + "' " + ((cc.toggles & b.get().flag) == 0 ? "disabled" : "enabled")); DPUtils.reply(message, null, "'" + b.get().toString().toLowerCase() + "' " + ((cc.toggles & b.get().flag) == 0 ? "disabled" : "enabled")).subscribe();
return true; return true;
} }
@ -88,45 +91,49 @@ public class ChannelconCommand extends ICommand2DC {
public boolean def(Command2DCSender sender, String channelID) { public boolean def(Command2DCSender sender, String channelID) {
val message = sender.getMessage(); val message = sender.getMessage();
if (checkPerms(message)) return true; if (checkPerms(message)) return true;
if (MCChatCustom.hasCustomChat(message.getChannel())) if (MCChatCustom.hasCustomChat(message.getChannelId()))
return respond(sender, "this channel is already connected to a Minecraft channel. Use `@ChromaBot channelcon remove` to remove it."); return respond(sender, "this channel is already connected to a Minecraft channel. Use `@ChromaBot channelcon remove` to remove it.");
val chan = Channel.getChannels().filter(ch -> ch.ID.equalsIgnoreCase(channelID) || (Arrays.stream(ch.IDs().get()).anyMatch(cid -> cid.equalsIgnoreCase(channelID)))).findAny(); val chan = Channel.getChannels().filter(ch -> ch.ID.equalsIgnoreCase(channelID) || (Arrays.stream(ch.IDs().get()).anyMatch(cid -> cid.equalsIgnoreCase(channelID)))).findAny();
if (!chan.isPresent()) { //TODO: Red embed that disappears over time (kinda like the highlight messages in OW) if (!chan.isPresent()) { //TODO: Red embed that disappears over time (kinda like the highlight messages in OW)
message.reply("MC channel with ID '" + channelID + "' not found! The ID is the command for it without the /."); DPUtils.reply(message, null, "MC channel with ID '" + channelID + "' not found! The ID is the command for it without the /.").subscribe();
return true; return true;
} }
val dp = DiscordPlayer.getUser(message.getAuthor().getId().asString(), DiscordPlayer.class); if (!message.getAuthor().isPresent()) return true;
val author = message.getAuthor().get();
val dp = DiscordPlayer.getUser(author.getId().asString(), DiscordPlayer.class);
val chp = dp.getAs(TBMCPlayer.class); val chp = dp.getAs(TBMCPlayer.class);
if (chp == null) { if (chp == null) {
message.reply("you need to connect your Minecraft account. On our server in " + DPUtils.botmention() + " do " + DiscordPlugin.getPrefix() + "connect <MCname>"); DPUtils.reply(message, null, "you need to connect your Minecraft account. On our server in " + DPUtils.botmention() + " do " + DiscordPlugin.getPrefix() + "connect <MCname>").subscribe();
return true; return true;
} }
DiscordConnectedPlayer dcp = new DiscordConnectedPlayer(message.getAuthor(), message.getChannel(), chp.getUUID(), Bukkit.getOfflinePlayer(chp.getUUID()).getName()); val channel = message.getChannel().block();
DiscordConnectedPlayer dcp = new DiscordConnectedPlayer(message.getAuthor().get(), channel, chp.getUUID(), Bukkit.getOfflinePlayer(chp.getUUID()).getName(), module);
//Using a fake player with no login/logout, should be fine for this event //Using a fake player with no login/logout, should be fine for this event
String groupid = chan.get().getGroupID(dcp); String groupid = chan.get().getGroupID(dcp);
if (groupid == null && !(chan.get() instanceof ChatRoom)) { //ChatRooms don't allow it unless the user joins, which happens later if (groupid == null && !(chan.get() instanceof ChatRoom)) { //ChatRooms don't allow it unless the user joins, which happens later
message.reply("sorry, you cannot use that Minecraft channel."); DPUtils.reply(message, null, "sorry, you cannot use that Minecraft channel.").subscribe();
return true; return true;
} }
if (chan.get() instanceof ChatRoom) { //ChatRooms don't work well if (chan.get() instanceof ChatRoom) { //ChatRooms don't work well
message.reply("chat rooms are not supported yet."); DPUtils.reply(message, null, "chat rooms are not supported yet.").subscribe();
return true; return true;
} }
/*if (MCChatListener.getCustomChats().stream().anyMatch(cc -> cc.groupID.equals(groupid) && cc.mcchannel.ID.equals(chan.get().ID))) { /*if (MCChatListener.getCustomChats().stream().anyMatch(cc -> cc.groupID.equals(groupid) && cc.mcchannel.ID.equals(chan.get().ID))) {
message.reply("sorry, this MC chat is already connected to a different channel, multiple channels are not supported atm."); DPUtils.reply(message, null, "sorry, this MC chat is already connected to a different channel, multiple channels are not supported atm.");
return true; return true;
}*/ //TODO: "Channel admins" that can connect channels? }*/ //TODO: "Channel admins" that can connect channels?
MCChatCustom.addCustomChat(message.getChannel(), groupid, chan.get(), message.getAuthor(), dcp, 0, new HashSet<>()); MCChatCustom.addCustomChat(channel, groupid, chan.get(), author, dcp, 0, new HashSet<>());
if (chan.get() instanceof ChatRoom) if (chan.get() instanceof ChatRoom)
message.reply("alright, connection made to the room!"); DPUtils.reply(message, null, "alright, connection made to the room!").subscribe();
else else
message.reply("alright, connection made to group `" + groupid + "`!"); DPUtils.reply(message, null, "alright, connection made to group `" + groupid + "`!").subscribe();
return true; return true;
} }
@SuppressWarnings("ConstantConditions")
private boolean checkPerms(Message message) { private boolean checkPerms(Message message) {
if (!PermissionUtils.hasPermissions(message.getChannel(), message.getAuthor(), Permissions.MANAGE_CHANNEL)) { if (!message.getAuthorAsMember().block().getBasePermissions().block().contains(Permission.MANAGE_CHANNELS)) {
message.reply("you need to have manage permissions for this channel!"); DPUtils.reply(message, null, "you need to have manage permissions for this channel!").subscribe();
return true; return true;
} }
return false; return false;
@ -140,7 +147,7 @@ public class ChannelconCommand extends ICommand2DC {
"You need to have access to the MC channel and have manage permissions on the Discord channel.", // "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 " + DPUtils.botmention() + " use " + DiscordPlugin.getPrefix() + "connect <mcname>.", // "You also need to have your Minecraft account connected. In " + DPUtils.botmention() + " use " + DiscordPlugin.getPrefix() + "connect <mcname>.", //
"Call this command from the channel you want to use.", // "Call this command from the channel you want to use.", //
"Usage: @" + DiscordPlugin.dc.getSelf().getName() + " channelcon <mcchannel>", // "Usage: " + Objects.requireNonNull(DiscordPlugin.dc.getSelf().block()).getMention() + " channelcon <mcchannel>", //
"Use the ID (command) of the channel, for example `g` for the global chat.", // "Use the ID (command) of the channel, for example `g` for the global chat.", //
"To remove a connection use @ChromaBot channelcon remove in the channel.", // "To remove a connection use @ChromaBot channelcon remove in the channel.", //
"Mentioning the bot is needed in this case because the " + DiscordPlugin.getPrefix() + " prefix only works in " + DPUtils.botmention() + ".", // "Mentioning the bot is needed in this case because the " + DiscordPlugin.getPrefix() + " prefix only works in " + DPUtils.botmention() + ".", //

View file

@ -21,13 +21,13 @@ public class MCChatCommand extends ICommand2DC {
public boolean def(Command2DCSender sender) { public boolean def(Command2DCSender sender) {
val message = sender.getMessage(); val message = sender.getMessage();
if (!message.getChannel().isPrivate()) { if (!message.getChannel().isPrivate()) {
message.reply("this command can only be issued in a direct message with the bot."); DPUtils.reply(message, null, "this command can only be issued in a direct message with the bot.");
return true; return true;
} }
try (final DiscordPlayer user = DiscordPlayer.getUser(message.getAuthor().getId().asString(), DiscordPlayer.class)) { try (final DiscordPlayer user = DiscordPlayer.getUser(message.getAuthor().getId().asString(), DiscordPlayer.class)) {
boolean mcchat = !user.isMinecraftChatEnabled(); boolean mcchat = !user.isMinecraftChatEnabled();
MCChatPrivate.privateMCChat(message.getChannel(), mcchat, message.getAuthor(), user); MCChatPrivate.privateMCChat(message.getChannel(), mcchat, message.getAuthor(), user);
message.reply("Minecraft chat " + (mcchat // DPUtils.reply(message, null, "Minecraft chat " + (mcchat //
? "enabled. Use '" + DiscordPlugin.getPrefix() + "mcchat' again to turn it off." // ? "enabled. Use '" + DiscordPlugin.getPrefix() + "mcchat' again to turn it off." //
: "disabled.")); : "disabled."));
} catch (Exception e) { } catch (Exception e) {

View file

@ -37,14 +37,14 @@ public class MCChatCustom {
} }
@Nullable @Nullable
public static CustomLMD getCustomChat(MessageChannel channel) { public static CustomLMD getCustomChat(Snowflake channel) {
return lastmsgCustom.stream().filter(lmd -> lmd.channel.getId().asLong() == channel.getId().asLong()).findAny().orElse(null); return lastmsgCustom.stream().filter(lmd -> lmd.channel.getId().asLong() == channel.asLong()).findAny().orElse(null);
} }
public static boolean removeCustomChat(MessageChannel channel) { public static boolean removeCustomChat(Snowflake channel) {
MCChatUtils.lastmsgfromd.remove(channel.getId().asLong()); MCChatUtils.lastmsgfromd.remove(channel.asLong());
return lastmsgCustom.removeIf(lmd -> { return lastmsgCustom.removeIf(lmd -> {
if (lmd.channel.getId().asLong() != channel.getId().asLong()) if (lmd.channel.getId().asLong() != channel.asLong())
return false; return false;
if (lmd.mcchannel instanceof ChatRoom) if (lmd.mcchannel instanceof ChatRoom)
((ChatRoom) lmd.mcchannel).leaveRoom(lmd.dcp); ((ChatRoom) lmd.mcchannel).leaveRoom(lmd.dcp);

View file

@ -76,13 +76,13 @@ public class MCChatUtils {
lmd.channel.edit(tce -> tce.setTopic(String.join("\n----\n", s)).setReason("Player list update")).subscribe(); //Don't wait 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<Long, HashMap<Channel, T>> senders, public static <T extends DiscordSenderBase> T addSender(HashMap<String, HashMap<Channel, T>> senders,
User user, T sender) { User user, T sender) {
return addSender(senders, user.getId().asLong(), sender); return addSender(senders, user.getId().asString(), sender);
} }
public static <T extends DiscordSenderBase> T addSender(HashMap<Long, HashMap<MessageChannel, T>> senders, public static <T extends DiscordSenderBase> T addSender(HashMap<String, HashMap<MessageChannel, T>> senders,
long did, T sender) { String 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<>();
@ -91,17 +91,17 @@ public class MCChatUtils {
return sender; return sender;
} }
public static <T extends DiscordSenderBase> T getSender(HashMap<Long, HashMap<MessageChannel, T>> senders, public static <T extends DiscordSenderBase> T getSender(HashMap<String, HashMap<MessageChannel, T>> senders,
MessageChannel channel, User user) { MessageChannel channel, User user) {
var map = senders.get(user.getId().asLong()); var map = senders.get(user.getId().asString());
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<Long, HashMap<Channel, T>> senders, public static <T extends DiscordSenderBase> T removeSender(HashMap<String, HashMap<Channel, T>> senders,
Channel channel, User user) { Channel channel, User user) {
var map = senders.get(user.getId().asLong()); var map = senders.get(user.getId().asString());
if (map != null) if (map != null)
return map.remove(channel); return map.remove(channel);
return null; return null;

View file

@ -15,7 +15,6 @@ import discord4j.core.object.util.Snowflake;
import lombok.Getter; import lombok.Getter;
import lombok.val; import lombok.val;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import sx.blah.discord.handle.obj.MessageChannel;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Objects; import java.util.Objects;

View file

@ -15,6 +15,7 @@ import lombok.val;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import java.awt.*; import java.awt.*;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -54,7 +55,7 @@ public class GameRoleModule extends Component<DiscordPlugin> {
Role role=((RoleDeleteEvent) roleEvent).getRole().orElse(null); Role role=((RoleDeleteEvent) roleEvent).getRole().orElse(null);
if(role==null) return; if(role==null) return;
if (GameRoles.remove(role.getName()) && logChannel != null) if (GameRoles.remove(role.getName()) && logChannel != null)
logChannel, "Removed " + role.getName() + " as a game role.") logChannel.createMessage("Removed " + role.getName() + " as a game role.").subscribe();
} else if (roleEvent instanceof RoleUpdateEvent) { } else if (roleEvent instanceof RoleUpdateEvent) {
val event = (RoleUpdateEvent) roleEvent; val event = (RoleUpdateEvent) roleEvent;
if(!event.getOld().isPresent()) { if(!event.getOld().isPresent()) {
@ -80,11 +81,12 @@ public class GameRoleModule extends Component<DiscordPlugin> {
} }
} }
@SuppressWarnings("ConstantConditions")
private boolean isGameRole(Role r) { private boolean isGameRole(Role r) {
if (r.getGuildId().asLong() != DiscordPlugin.mainServer.getId().asLong()) if (r.getGuildId().asLong() != DiscordPlugin.mainServer.getId().asLong())
return false; //Only allow on the main server return false; //Only allow on the main server
val rc = new Color(149, 165, 166, 0); val rc = new Color(149, 165, 166, 0);
return r.getColor().equals(rc) return r.getColor().equals(rc)
&& DiscordPlugin.dc.getSelf().block().asMember(DiscordPlugin.mainServer.getId()).block().hasHigherRoles(r); //Below one of our roles && DiscordPlugin.dc.getSelf().block().asMember(DiscordPlugin.mainServer.getId()).block().hasHigherRoles(Collections.singleton(r)).block(); //Below one of our roles
} }
} }

View file

@ -1,14 +1,13 @@
package buttondevteam.discordplugin.role; package buttondevteam.discordplugin.role;
import buttondevteam.discordplugin.DPUtils;
import buttondevteam.discordplugin.DiscordPlugin; import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.commands.Command2DCSender; import buttondevteam.discordplugin.commands.Command2DCSender;
import buttondevteam.discordplugin.commands.ICommand2DC; import buttondevteam.discordplugin.commands.ICommand2DC;
import buttondevteam.lib.TBMCCoreAPI; import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.chat.Command2; import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass; import buttondevteam.lib.chat.CommandClass;
import discord4j.core.object.entity.Role;
import lombok.val; import lombok.val;
import sx.blah.discord.handle.obj.IRole;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -27,12 +26,12 @@ public class RoleCommand extends ICommand2DC {
"This command adds a role to your account." "This command adds a role to your account."
}) })
public boolean add(Command2DCSender sender, @Command2.TextArg String rolename) { public boolean add(Command2DCSender sender, @Command2.TextArg String rolename) {
final IRole role = checkAndGetRole(sender, rolename); final Role role = checkAndGetRole(sender, rolename);
if (role == null) if (role == null)
return true; return true;
try { try {
DPUtils.perform(() -> sender.getMessage().getAuthor().addRole(role)); sender.getMessage().getAuthorAsMember()
sender.sendMessage("added role."); .subscribe(m -> m.addRole(role.getId()).subscribe(r -> sender.sendMessage("added role.")));
} catch (Exception e) { } catch (Exception e) {
TBMCCoreAPI.SendException("Error while adding role!", e); TBMCCoreAPI.SendException("Error while adding role!", e);
sender.sendMessage("an error occured while adding the role."); sender.sendMessage("an error occured while adding the role.");
@ -45,12 +44,12 @@ public class RoleCommand extends ICommand2DC {
"This command removes a role from your account." "This command removes a role from your account."
}) })
public boolean remove(Command2DCSender sender, @Command2.TextArg String rolename) { public boolean remove(Command2DCSender sender, @Command2.TextArg String rolename) {
final IRole role = checkAndGetRole(sender, rolename); final Role role = checkAndGetRole(sender, rolename);
if (role == null) if (role == null)
return true; return true;
try { try {
DPUtils.perform(() -> sender.getMessage().getAuthor().removeRole(role)); sender.getMessage().getAuthorAsMember()
sender.sendMessage("removed role."); .subscribe(m -> m.removeRole(role.getId()).subscribe(r -> sender.sendMessage("removed role.")));
} catch (Exception e) { } catch (Exception e) {
TBMCCoreAPI.SendException("Error while removing role!", e); TBMCCoreAPI.SendException("Error while removing role!", e);
sender.sendMessage("an error occured while removing the role."); sender.sendMessage("an error occured while removing the role.");
@ -63,7 +62,7 @@ public class RoleCommand extends ICommand2DC {
sender.sendMessage("list of roles:\n" + grm.GameRoles.stream().sorted().collect(Collectors.joining("\n"))); sender.sendMessage("list of roles:\n" + grm.GameRoles.stream().sorted().collect(Collectors.joining("\n")));
} }
private IRole checkAndGetRole(Command2DCSender sender, String rolename) { private Role checkAndGetRole(Command2DCSender sender, String rolename) {
String rname = rolename; String rname = rolename;
if (!grm.GameRoles.contains(rolename)) { //If not found as-is, correct case if (!grm.GameRoles.contains(rolename)) { //If not found as-is, correct case
val orn = grm.GameRoles.stream().filter(r -> r.equalsIgnoreCase(rolename)).findAny(); val orn = grm.GameRoles.stream().filter(r -> r.equalsIgnoreCase(rolename)).findAny();
@ -74,7 +73,12 @@ public class RoleCommand extends ICommand2DC {
} }
rname = orn.get(); rname = orn.get();
} }
final List<IRole> roles = DiscordPlugin.mainServer.getRolesByName(rname); val frname = rname;
final List<Role> roles = DiscordPlugin.mainServer.getRoles().filter(r -> r.getName().equals(frname)).collectList().block();
if (roles == null) {
sender.sendMessage("an error occured.");
return null;
}
if (roles.size() == 0) { if (roles.size() == 0) {
sender.sendMessage("the specified role cannot be found on Discord! Removing from the list."); sender.sendMessage("the specified role cannot be found on Discord! Removing from the list.");
grm.GameRoles.remove(rolename); grm.GameRoles.remove(rolename);