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.spec.EmbedCreateSpec;
import lombok.val;
import reactor.core.publisher.Mono;
import javax.annotation.Nullable;
import java.util.logging.Logger;
@ -116,4 +117,14 @@ public final class DPUtils {
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;
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.Server;
import org.bukkit.command.CommandSender;
@ -8,8 +12,6 @@ import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionAttachment;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.Plugin;
import sx.blah.discord.handle.obj.User;
import sx.blah.discord.handle.obj.MessageChannel;
import java.util.Set;
@ -20,7 +22,8 @@ public class DiscordSender extends DiscordSenderBase implements CommandSender {
public DiscordSender(User user, MessageChannel 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) {

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 = Character.toLowerCase(message.charAt(0)) + message.substring(1);
val msg = message;
this.message.getChannel().flatMap(ch -> ch.createMessage(this.message.getAuthorAsMember().a->
a.getNicknameMention() + ", " + msg)))
val author = this.message.getAuthorAsMember().block();
if (author == null) return;
this.message.getChannel().subscribe(ch -> ch.createMessage(author.getNicknameMention() + ", " + msg));
}
@Override

View file

@ -7,13 +7,14 @@ import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.TBMCExceptionEvent;
import buttondevteam.lib.architecture.Component;
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.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
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.Arrays;
@ -49,19 +50,19 @@ public class ExceptionListenerModule extends Component<DiscordPlugin> implements
try {
MessageChannel channel = getChannel();
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()
: new StringBuilder(coderRole == null ? "" : coderRole.mention()).append("\n");
: new StringBuilder(coderRole == null ? "" : coderRole.getMention()).append("\n");
sb.append(sourcemessage).append("\n");
sb.append("```").append("\n");
String stackTrace = Arrays.stream(ExceptionUtils.getStackTrace(e).split("\\n"))
.filter(s -> !s.contains("\tat ") || s.contains("\tat buttondevteam."))
.collect(Collectors.joining("\n"));
if (stackTrace.length() > 1800)
stackTrace = stackTrace.substring(0, 1800);
if (sb.length() + stackTrace.length() >= 2000)
stackTrace = stackTrace.substring(0, 1999 - sb.length());
sb.append(stackTrace).append("\n");
sb.append("```");
DiscordPlugin.sendMessageToChannel(channel, sb.toString()); //Instance isn't null here
channel.createMessage(sb.toString()).subscribe();
} catch (Exception ex) {
ex.printStackTrace();
}
@ -78,7 +79,7 @@ public class ExceptionListenerModule extends Component<DiscordPlugin> implements
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);
}

View file

@ -7,14 +7,14 @@ import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.architecture.ConfigData;
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 org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
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.Arrays;
@ -25,26 +25,26 @@ import java.util.stream.IntStream;
public class FunModule extends Component<DiscordPlugin> implements Listener {
private static final String[] serverReadyStrings = new String[]{"In one week from now", // Ali
"Between now and the heat-death of the universe.", // Ghostise
"Soon™", "Ask again this time next month", // Ghostise
"In about 3 seconds", // Nicolai
"After we finish 8 plugins", // Ali
"Tomorrow.", // Ali
"After one tiiiny feature", // Ali
"Next commit", // Ali
"After we finish strangling Towny", // Ali
"When we kill every *fucking* bug", // Ali
"Once the server stops screaming.", // Ali
"After HL3 comes out", // Ali
"Next time you ask", // Ali
"When will *you* be open?" // Ali
"Between now and the heat-death of the universe.", // Ghostise
"Soon™", "Ask again this time next month", // Ghostise
"In about 3 seconds", // Nicolai
"After we finish 8 plugins", // Ali
"Tomorrow.", // Ali
"After one tiiiny feature", // Ali
"Next commit", // Ali
"After we finish strangling Towny", // Ali
"When we kill every *fucking* bug", // Ali
"Once the server stops screaming.", // Ali
"After HL3 comes out", // Ali
"Next time you ask", // Ali
"When will *you* be open?" // Ali
};
/**
* Questions that the bot will choose a random answer to give to.
*/
private ConfigData<String[]> serverReadyQuestions() {
return getConfig().getData("serverReady", ()->new String[]{"when will the server be open",
return getConfig().getData("serverReady", () -> new String[]{"when will the server be open",
"when will the server be ready", "when will the server be done", "when will the server be complete",
"when will the server be finished", "when's the server ready", "when's the server open",
"Vhen vill ze server be open?"});
@ -83,7 +83,7 @@ public class FunModule extends Component<DiscordPlugin> implements Listener {
public static boolean executeMemes(Message message) {
val fm = ComponentManager.getIfEnabled(FunModule.class);
if (fm == null) return false;
String msglowercased = message.getContent().toLowerCase();
String msglowercased = message.getContent().orElse("").toLowerCase();
lastlist++;
if (lastlist > 5) {
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
{
message.reply("Stop it. You know the answer.");
DPUtils.reply(message, null, "Stop it. You know the answer.").subscribe();
lastlist = 0;
lastlistp = (short) Bukkit.getOnlinePlayers().size();
return true; //Handled
@ -103,7 +103,7 @@ public class FunModule extends Component<DiscordPlugin> implements Listener {
if (usableServerReadyStrings.size() == 0)
fm.createUsableServerReadyStrings();
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;
@ -114,7 +114,7 @@ public class FunModule extends Component<DiscordPlugin> implements Listener {
ListC = 0;
}
private ConfigData<IRole> fullHouseDevRole(IGuild guild) {
private ConfigData<Role> fullHouseDevRole(Guild 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;
@SuppressWarnings("ConstantConditions")
public static void handleFullHouse(PresenceUpdateEvent event) {
val fm = ComponentManager.getIfEnabled(FunModule.class);
if (fm == null) return;
val channel = fm.fullHouseChannel().get();
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 (event.getOldPresence().getStatus().equals(StatusType.OFFLINE)
&& !event.getNewPresence().getStatus().equals(StatusType.OFFLINE)
&& event.getUser().getRolesForGuild(channel.getGuild()).stream()
.anyMatch(r -> r.getId().asLong() == devrole.getId().asLong())
&& channel.getGuild().getUsersByRole(devrole).stream()
.noneMatch(u -> u.getPresence().getStatus().equals(StatusType.OFFLINE))
if (event.getOld().map(p -> p.getStatus().equals(Status.OFFLINE)).orElse(false)
&& !event.getCurrent().getStatus().equals(Status.OFFLINE)
&& event.getMember().flatMap(m -> m.getRoles()
.any(r -> r.getId().asLong() == devrole.getId().asLong())).block()
&& event.getGuild().flatMap(g -> g.getMembers().filter(m -> m.getRoleIds().stream().anyMatch(s -> s.equals(devrole.getId())))
.flatMap(Member::getPresence).all(pr -> !pr.getStatus().equals(Status.OFFLINE))).block()
&& lasttime + 10 < TimeUnit.NANOSECONDS.toHours(System.nanoTime())
&& Calendar.getInstance().get(Calendar.DAY_OF_MONTH) % 5 == 0) {
DiscordPlugin.sendMessageToChannel(channel, "Full house!",
new EmbedBuilder()
.withImage(
"https://cdn.discordapp.com/attachments/249295547263877121/249687682618359808/poker-hand-full-house-aces-kings-playing-cards-15553791.png")
.build());
channel.createMessage(mcs -> mcs.setContent("Full house!").setEmbed(ecs ->
ecs.setImage(
"https://cdn.discordapp.com/attachments/249295547263877121/249687682618359808/poker-hand-full-house-aces-kings-playing-cards-15553791.png")
));
lasttime = TimeUnit.NANOSECONDS.toHours(System.nanoTime());
}
}

View file

@ -1,15 +1,14 @@
package buttondevteam.discordplugin.listeners;
import buttondevteam.discordplugin.DPUtils;
import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.commands.Command2DCSender;
import buttondevteam.lib.TBMCCoreAPI;
import discord4j.core.object.entity.Message;
import discord4j.core.object.entity.MessageChannel;
import discord4j.core.object.entity.PrivateChannel;
import discord4j.core.object.entity.Role;
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 {
/**
@ -41,26 +40,24 @@ public class CommandListener {
final String mentionNick = member.getNicknameMention();
boolean gotmention = checkanddeletemention(cmdwithargs, mention, message);
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
if (mentionedonly && !gotmention) {
message.getChannel().setTypingStatus(false);
if (mentionedonly && !gotmention)
return false;
}
message.getChannel().setTypingStatus(true);
channel.type().subscribe();
String cmdwithargsString = cmdwithargs.toString();
try {
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) {
TBMCCoreAPI.SendException("Failed to process Discord command: " + cmdwithargsString, e);
}
message.getChannel().setTypingStatus(false);
return true;
}
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) {
int i = cmdwithargs.indexOf(" ", mention.length());
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.RoleUpdateEvent;
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 {
@ -36,7 +30,8 @@ public class CommonListeners {
dispatcher.on(MessageCreateEvent.class).subscribe(event->{
if (DiscordPlugin.SafeMode)
return;
if (event.getMessage().getAuthor().isBot())
val author = event.getMessage().getAuthor();
if (!author.isPresent() || author.get().isBot())
return;
if (FunModule.executeMemes(event.getMessage()))
return;

View file

@ -5,39 +5,50 @@ import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.commands.ConnectCommand;
import buttondevteam.lib.player.TBMCPlayerGetInfoEvent;
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.Listener;
import org.bukkit.event.server.ServerCommandEvent;
import sx.blah.discord.handle.obj.User;
public class MCListener implements Listener {
@EventHandler
public void onPlayerJoin(TBMCPlayerJoinEvent e) {
if (ConnectCommand.WaitingToConnect.containsKey(e.GetPlayer().PlayerName().get())) {
@SuppressWarnings("ConstantConditions") User user = DiscordPlugin.dc
.getUserByID(Long.parseLong(ConnectCommand.WaitingToConnect.get(e.GetPlayer().PlayerName().get())));
e.getPlayer().sendMessage("§bTo connect with the Discord account @" + user.getName() + "#" + user.getDiscriminator()
.getUserById(Snowflake.of(ConnectCommand.WaitingToConnect.get(e.GetPlayer().PlayerName().get()))).block();
if (user == null) return;
e.getPlayer().sendMessage("§bTo connect with the Discord account @" + user.getUsername() + "#" + user.getDiscriminator()
+ " do /discord accept");
e.getPlayer().sendMessage("§bIf it wasn't you, do /discord decline");
}
}
@EventHandler
public void onGetInfo(TBMCPlayerGetInfoEvent e) {
if (DiscordPlugin.SafeMode)
return;
DiscordPlayer dp = e.getPlayer().getAs(DiscordPlayer.class);
if (dp == null || dp.getDiscordID() == null || dp.getDiscordID().equals(""))
return;
User user = DiscordPlugin.dc.getUserByID(Long.parseLong(dp.getDiscordID()));
e.addInfo("Discord tag: " + user.getName() + "#" + user.getDiscriminator());
e.addInfo(user.getPresence().getStatus().toString());
if (user.getPresence().getActivity().isPresent() && user.getPresence().getText().isPresent())
e.addInfo(user.getPresence().getActivity().get() + ": " + user.getPresence().getText().get());
}
@EventHandler
public void onGetInfo(TBMCPlayerGetInfoEvent e) {
if (DiscordPlugin.SafeMode)
return;
DiscordPlayer dp = e.getPlayer().getAs(DiscordPlayer.class);
if (dp == null || dp.getDiscordID() == null || dp.getDiscordID().equals(""))
return;
User user = DiscordPlugin.dc.getUserById(Snowflake.of(dp.getDiscordID())).block();
if (user == null) return;
e.addInfo("Discord tag: " + user.getUsername() + "#" + user.getDiscriminator());
Member member = user.asMember(DiscordPlugin.mainServer.getId()).block();
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
public void onServerCommand(ServerCommandEvent e) {
DiscordPlugin.Restart = !e.getCommand().equalsIgnoreCase("stop"); // The variable is always true except if stopped
}
@EventHandler
public void onServerCommand(ServerCommandEvent e) {
DiscordPlugin.Restart = !e.getCommand().equalsIgnoreCase("stop"); // The variable is always true except if stopped
}
}

View file

@ -9,15 +9,16 @@ import buttondevteam.lib.TBMCSystemChatEvent;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.player.TBMCPlayer;
import discord4j.core.object.entity.Message;
import discord4j.core.object.util.Permission;
import lombok.RequiredArgsConstructor;
import lombok.val;
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.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.function.Supplier;
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.", //
"Invite link: <https://discordapp.com/oauth2/authorize?client_id=226443037893591041&scope=bot&permissions=268509264>" //
})
@RequiredArgsConstructor
public class ChannelconCommand extends ICommand2DC {
private final MinecraftChatModule module;
@Command2.Subcommand
public boolean remove(Command2DCSender sender) {
val message = sender.getMessage();
if (checkPerms(message)) return true;
if (MCChatCustom.removeCustomChat(message.getChannel()))
message.reply("channel connection removed.");
if (MCChatCustom.removeCustomChat(message.getChannelId()))
DPUtils.reply(message, null, "channel connection removed.").subscribe();
else
message.reply("this channel isn't connected.");
DPUtils.reply(message, null, "this channel isn't connected.").subscribe();
return true;
}
@ -48,13 +51,13 @@ public class ChannelconCommand extends ICommand2DC {
public boolean toggle(Command2DCSender sender, @Command2.OptionalArg String toggle) {
val message = sender.getMessage();
if (checkPerms(message)) return true;
val cc = MCChatCustom.getCustomChat(message.getChannel());
val cc = MCChatCustom.getCustomChat(message.getChannelId());
if (cc == null)
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"))
+ "\n\n" + TBMCSystemChatEvent.BroadcastTarget.stream().map(target -> target.getName() + ": " + (cc.brtoggles.contains(target) ? "enabled" : "disabled")).collect(Collectors.joining("\n"));
if (toggle == null) {
message.reply("toggles:\n" + togglesString.get());
DPUtils.reply(message, null, "toggles:\n" + togglesString.get()).subscribe();
return true;
}
String arg = toggle.toUpperCase();
@ -62,7 +65,7 @@ public class ChannelconCommand extends ICommand2DC {
if (!b.isPresent()) {
val bt = TBMCSystemChatEvent.BroadcastTarget.get(arg);
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;
}
final boolean add;
@ -80,7 +83,7 @@ public class ChannelconCommand extends ICommand2DC {
//1 1 | 0
// XOR
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;
}
@ -88,45 +91,49 @@ public class ChannelconCommand extends ICommand2DC {
public boolean def(Command2DCSender sender, String channelID) {
val message = sender.getMessage();
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.");
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)
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;
}
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);
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;
}
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
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
message.reply("sorry, you cannot use that Minecraft channel.");
DPUtils.reply(message, null, "sorry, you cannot use that Minecraft channel.").subscribe();
return true;
}
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;
}
/*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;
}*/ //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)
message.reply("alright, connection made to the room!");
DPUtils.reply(message, null, "alright, connection made to the room!").subscribe();
else
message.reply("alright, connection made to group `" + groupid + "`!");
DPUtils.reply(message, null, "alright, connection made to group `" + groupid + "`!").subscribe();
return true;
}
@SuppressWarnings("ConstantConditions")
private boolean checkPerms(Message message) {
if (!PermissionUtils.hasPermissions(message.getChannel(), message.getAuthor(), Permissions.MANAGE_CHANNEL)) {
message.reply("you need to have manage permissions for this channel!");
if (!message.getAuthorAsMember().block().getBasePermissions().block().contains(Permission.MANAGE_CHANNELS)) {
DPUtils.reply(message, null, "you need to have manage permissions for this channel!").subscribe();
return true;
}
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 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.", //
"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.", //
"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() + ".", //

View file

@ -21,13 +21,13 @@ public class MCChatCommand extends ICommand2DC {
public boolean def(Command2DCSender sender) {
val message = sender.getMessage();
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;
}
try (final DiscordPlayer user = DiscordPlayer.getUser(message.getAuthor().getId().asString(), DiscordPlayer.class)) {
boolean mcchat = !user.isMinecraftChatEnabled();
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." //
: "disabled."));
} catch (Exception e) {

View file

@ -37,14 +37,14 @@ public class MCChatCustom {
}
@Nullable
public static CustomLMD getCustomChat(MessageChannel channel) {
return lastmsgCustom.stream().filter(lmd -> lmd.channel.getId().asLong() == channel.getId().asLong()).findAny().orElse(null);
public static CustomLMD getCustomChat(Snowflake channel) {
return lastmsgCustom.stream().filter(lmd -> lmd.channel.getId().asLong() == channel.asLong()).findAny().orElse(null);
}
public static boolean removeCustomChat(MessageChannel channel) {
MCChatUtils.lastmsgfromd.remove(channel.getId().asLong());
public static boolean removeCustomChat(Snowflake channel) {
MCChatUtils.lastmsgfromd.remove(channel.asLong());
return lastmsgCustom.removeIf(lmd -> {
if (lmd.channel.getId().asLong() != channel.getId().asLong())
if (lmd.channel.getId().asLong() != channel.asLong())
return false;
if (lmd.mcchannel instanceof ChatRoom)
((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
}
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) {
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,
long did, T sender) {
public static <T extends DiscordSenderBase> T addSender(HashMap<String, HashMap<MessageChannel, T>> senders,
String did, T sender) {
var map = senders.get(did);
if (map == null)
map = new HashMap<>();
@ -91,17 +91,17 @@ public class MCChatUtils {
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) {
var map = senders.get(user.getId().asLong());
var map = senders.get(user.getId().asString());
if (map != null)
return map.get(channel);
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) {
var map = senders.get(user.getId().asLong());
var map = senders.get(user.getId().asString());
if (map != null)
return map.remove(channel);
return null;

View file

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

View file

@ -15,6 +15,7 @@ import lombok.val;
import org.bukkit.Bukkit;
import java.awt.*;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@ -54,7 +55,7 @@ public class GameRoleModule extends Component<DiscordPlugin> {
Role role=((RoleDeleteEvent) roleEvent).getRole().orElse(null);
if(role==null) return;
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) {
val event = (RoleUpdateEvent) roleEvent;
if(!event.getOld().isPresent()) {
@ -80,11 +81,12 @@ public class GameRoleModule extends Component<DiscordPlugin> {
}
}
@SuppressWarnings("ConstantConditions")
private boolean isGameRole(Role r) {
if (r.getGuildId().asLong() != DiscordPlugin.mainServer.getId().asLong())
return false; //Only allow on the main server
val rc = new Color(149, 165, 166, 0);
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;
import buttondevteam.discordplugin.DPUtils;
import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.commands.Command2DCSender;
import buttondevteam.discordplugin.commands.ICommand2DC;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import discord4j.core.object.entity.Role;
import lombok.val;
import sx.blah.discord.handle.obj.IRole;
import java.util.List;
import java.util.stream.Collectors;
@ -27,12 +26,12 @@ public class RoleCommand extends ICommand2DC {
"This command adds a role to your account."
})
public boolean add(Command2DCSender sender, @Command2.TextArg String rolename) {
final IRole role = checkAndGetRole(sender, rolename);
final Role role = checkAndGetRole(sender, rolename);
if (role == null)
return true;
try {
DPUtils.perform(() -> sender.getMessage().getAuthor().addRole(role));
sender.sendMessage("added role.");
sender.getMessage().getAuthorAsMember()
.subscribe(m -> m.addRole(role.getId()).subscribe(r -> sender.sendMessage("added role.")));
} catch (Exception e) {
TBMCCoreAPI.SendException("Error while adding role!", e);
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."
})
public boolean remove(Command2DCSender sender, @Command2.TextArg String rolename) {
final IRole role = checkAndGetRole(sender, rolename);
final Role role = checkAndGetRole(sender, rolename);
if (role == null)
return true;
try {
DPUtils.perform(() -> sender.getMessage().getAuthor().removeRole(role));
sender.sendMessage("removed role.");
sender.getMessage().getAuthorAsMember()
.subscribe(m -> m.removeRole(role.getId()).subscribe(r -> sender.sendMessage("removed role.")));
} catch (Exception e) {
TBMCCoreAPI.SendException("Error while removing role!", e);
sender.sendMessage("an error occured while removing the role.");
@ -61,9 +60,9 @@ public class RoleCommand extends ICommand2DC {
@Command2.Subcommand
public void list(Command2DCSender sender) {
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;
if (!grm.GameRoles.contains(rolename)) { //If not found as-is, correct case
val orn = grm.GameRoles.stream().filter(r -> r.equalsIgnoreCase(rolename)).findAny();
@ -73,18 +72,23 @@ public class RoleCommand extends ICommand2DC {
return null;
}
rname = orn.get();
}
final List<IRole> roles = DiscordPlugin.mainServer.getRolesByName(rname);
if (roles.size() == 0) {
sender.sendMessage("the specified role cannot be found on Discord! Removing from the list.");
grm.GameRoles.remove(rolename);
return null;
}
if (roles.size() > 1) {
sender.sendMessage("there are multiple roles with this name. Why are there multiple roles with this name?");
return null;
}
return roles.get(0);
}
}
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) {
sender.sendMessage("the specified role cannot be found on Discord! Removing from the list.");
grm.GameRoles.remove(rolename);
return null;
}
if (roles.size() > 1) {
sender.sendMessage("there are multiple roles with this name. Why are there multiple roles with this name?");
return null;
}
return roles.get(0);
}
}