Bunch of fixes

#93
This commit is contained in:
Norbi Peti 2019-04-25 19:52:43 +02:00
parent e2e8a58c4e
commit eeb1955ebe
No known key found for this signature in database
GPG key ID: DBA4C4549A927E56
13 changed files with 145 additions and 148 deletions

View file

@ -174,7 +174,7 @@
<dependency> <dependency>
<groupId>com.discord4j</groupId> <groupId>com.discord4j</groupId>
<artifactId>discord4j-core</artifactId> <artifactId>discord4j-core</artifactId>
<version>3.0.2</version> <version>3.0.3</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-jdk14 --> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-jdk14 -->
<dependency> <dependency>
@ -200,11 +200,6 @@
<version>2.13.1</version> <version>2.13.1</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>com.github.xaanit</groupId>
<artifactId>D4J-OAuth</artifactId>
<version>master-SNAPSHOT</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>

View file

@ -58,7 +58,10 @@ public final class DPUtils {
public static ConfigData<MessageChannel> channelData(IHaveConfig config, String key, long defID) { public static ConfigData<MessageChannel> channelData(IHaveConfig config, String key, long defID) {
return config.getDataPrimDef(key, defID, id -> { return config.getDataPrimDef(key, defID, id -> {
Channel ch = DiscordPlugin.dc.getChannelById(Snowflake.of((long) id)).block(); Channel ch = DiscordPlugin.dc.getChannelById(Snowflake.of((long) id)).onErrorResume(e -> {
getLogger().warning("Failed to get channel data for " + key + "=" + id + " - " + e.getMessage());
return Mono.empty();
}).block();
if (ch instanceof MessageChannel) if (ch instanceof MessageChannel)
return (MessageChannel) ch; return (MessageChannel) ch;
else else
@ -127,4 +130,8 @@ public final class DPUtils {
? original.getAuthor().get().getMention() + ", " : "") + message)); ? original.getAuthor().get().getMention() + ", " : "") + message));
} }
public static String nickMention(Snowflake userId) {
return "<@!" + userId.asString() + ">";
}
} }

View file

@ -20,6 +20,7 @@ import buttondevteam.lib.player.ChromaGamerBase;
import com.google.common.io.Files; import com.google.common.io.Files;
import discord4j.core.DiscordClient; import discord4j.core.DiscordClient;
import discord4j.core.DiscordClientBuilder; import discord4j.core.DiscordClientBuilder;
import discord4j.core.event.domain.guild.GuildCreateEvent;
import discord4j.core.event.domain.lifecycle.ReadyEvent; import discord4j.core.event.domain.lifecycle.ReadyEvent;
import discord4j.core.object.entity.Guild; import discord4j.core.object.entity.Guild;
import discord4j.core.object.entity.MessageChannel; import discord4j.core.object.entity.MessageChannel;
@ -35,14 +36,14 @@ import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration; 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 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.time.Duration;
import java.util.List;
import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class DiscordPlugin extends ButtonPlugin { public class DiscordPlugin extends ButtonPlugin {
@ -105,15 +106,16 @@ public class DiscordPlugin extends ButtonPlugin {
} }
} }
val cb = new DiscordClientBuilder(token); val cb = new DiscordClientBuilder(token);
cb.setInitialPresence(Presence.doNotDisturb(Activity.playing("booting")));
dc = cb.build(); dc = cb.build();
dc.getEventDispatcher().on(ReadyEvent.class).subscribe(this::handleReady); dc.getEventDispatcher().on(ReadyEvent.class) // Listen for ReadyEvent(s)
/*dc.getEventDispatcher().on(ReadyEvent.class) // Listen for ReadyEvent(s)
.map(event -> event.getGuilds().size()) // Get how many guilds the bot is in .map(event -> event.getGuilds().size()) // Get how many guilds the bot is in
.flatMap(size -> dc.getEventDispatcher() .flatMap(size -> dc.getEventDispatcher()
.on(GuildCreateEvent.class) // Listen for GuildCreateEvent(s) .on(GuildCreateEvent.class) // Listen for GuildCreateEvent(s)
.take(size) // Take only the first `size` GuildCreateEvent(s) to be received .take(size) // Take only the first `size` GuildCreateEvent(s) to be received
.collectList()) // Take all received GuildCreateEvents and make it a List .collectList()) // Take all received GuildCreateEvents and make it a List
.subscribe(events -> /* All guilds have been received, client is fully connected *);*/ //TODO .subscribe(this::handleReady); /* All guilds have been received, client is fully connected */
dc.login().subscribe();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
Bukkit.getPluginManager().disablePlugin(this); Bukkit.getPluginManager().disablePlugin(this);
@ -122,41 +124,25 @@ public class DiscordPlugin extends ButtonPlugin {
public static Guild mainServer; public static Guild mainServer;
private static volatile BukkitTask task; private void handleReady(List<GuildCreateEvent> event) {
private static volatile boolean sent = false;
private void handleReady(ReadyEvent event) {
try { try {
dc.updatePresence(Presence.doNotDisturb(Activity.playing("booting"))).subscribe();
val tries = new AtomicInteger();
task = Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> {
tries.incrementAndGet();
if (tries.get() > 10) { //5 seconds
task.cancel();
getLogger().severe("Main server not found! Invite the bot and do /discord reset");
//getIConfig().getConfig().set("mainServer", 219529124321034241L); //Needed because it won't save as long as it's null - made it save
saveConfig(); //Put default there
return;
}
mainServer = MainServer().get(); //Shouldn't change afterwards mainServer = MainServer().get(); //Shouldn't change afterwards
if (mainServer == null) { if (mainServer == null) {
val guilds = dc.getGuilds(); if (event.size() == 0) {
if (guilds.count().blockOptional().orElse(0L) == 0L) getLogger().severe("Main server not found! Invite the bot and do /discord reset");
return; //If there are no guilds in cache, retry saveConfig(); //Put default there
mainServer = guilds.blockFirst(); return; //We should have all guilds by now, no need to retry
if (mainServer == null) return; }
mainServer = event.get(0).getGuild();
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.updatePresence(Presence.online(Activity.playing("Minecraft"))); dc.updatePresence(Presence.online(Activity.playing("Minecraft"))).subscribe();
} else { } else {
dc.updatePresence(Presence.online(Activity.playing("testing"))); dc.updatePresence(Presence.online(Activity.playing("testing"))).subscribe();
} }
SafeMode = false; SafeMode = false;
if (task != null)
task.cancel();
if (!sent) {
DPUtils.disableIfConfigError(null, CommandChannel(), ModRole()); //Won't disable, just prints the warning here DPUtils.disableIfConfigError(null, CommandChannel(), ModRole()); //Won't disable, just prints the warning here
Component.registerComponent(this, new GeneralEventBroadcasterModule()); Component.registerComponent(this, new GeneralEventBroadcasterModule());
@ -190,8 +176,7 @@ public class DiscordPlugin extends ButtonPlugin {
getConfig().set("serverup", true); getConfig().set("serverup", true);
saveConfig(); saveConfig();
sent = true; if (TBMCCoreAPI.IsTestServer() && !Objects.requireNonNull(dc.getSelf().block()).getUsername().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(
@ -200,8 +185,7 @@ public class DiscordPlugin extends ButtonPlugin {
} }
TBMCCoreAPI.SendUnsentExceptions(); TBMCCoreAPI.SendUnsentExceptions();
TBMCCoreAPI.SendUnsentDebugMessages(); TBMCCoreAPI.SendUnsentDebugMessages();
}
}, 0, 10);
CommonListeners.register(dc.getEventDispatcher()); CommonListeners.register(dc.getEventDispatcher());
TBMCCoreAPI.RegisterEventsForExceptions(new MCListener(), this); TBMCCoreAPI.RegisterEventsForExceptions(new MCListener(), this);
getCommand2MC().registerCommand(new DiscordMCCommand()); getCommand2MC().registerCommand(new DiscordMCCommand());
@ -253,7 +237,6 @@ public class DiscordPlugin extends ButtonPlugin {
dc.updatePresence(Presence.idle(Activity.playing("Chromacraft"))).block(); //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().block(); 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;
} catch (Exception e) { } catch (Exception e) {
TBMCCoreAPI.SendException("An error occured while disabling DiscordPlugin!", e); TBMCCoreAPI.SendException("An error occured while disabling DiscordPlugin!", e);
} }
@ -263,7 +246,7 @@ public class DiscordPlugin extends ButtonPlugin {
public static Permission perms; public static Permission perms;
public boolean setupProviders() { private boolean setupProviders() {
try { try {
Class.forName("net.milkbowl.vault.permission.Permission"); Class.forName("net.milkbowl.vault.permission.Permission");
Class.forName("net.milkbowl.vault.chat.Chat"); Class.forName("net.milkbowl.vault.chat.Chat");

View file

@ -58,7 +58,7 @@ public abstract class DiscordSenderBase implements CommandSender {
msgtosend += "\n" + sendmsg; msgtosend += "\n" + sendmsg;
if (sendtask == null) if (sendtask == null)
sendtask = Bukkit.getScheduler().runTaskLaterAsynchronously(DiscordPlugin.plugin, () -> { sendtask = Bukkit.getScheduler().runTaskLaterAsynchronously(DiscordPlugin.plugin, () -> {
channel.createMessage((!broadcast && user != null ? user.getMention() + "\n" : "") + msgtosend.trim()); channel.createMessage((!broadcast && user != null ? user.getMention() + "\n" : "") + msgtosend.trim()).subscribe();
sendtask = null; sendtask = null;
msgtosend = ""; msgtosend = "";
}, 4); // Waits a 0.2 second to gather all/most of the different messages }, 4); // Waits a 0.2 second to gather all/most of the different messages

View file

@ -18,9 +18,12 @@ 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;
val author = this.message.getAuthorAsMember().block(); /*this.message.getAuthorAsMember().flatMap(author ->
if (author == null) return; this.message.getChannel().flatMap(ch ->
this.message.getChannel().subscribe(ch -> ch.createMessage(author.getNicknameMention() + ", " + msg)); ch.createMessage(author.getNicknameMention() + ", " + msg))).subscribe();*/
this.message.getChannel().flatMap(ch ->
ch.createMessage(this.message.getAuthor().map(u -> DPUtils.nickMention(u.getId()) + ", ").orElse("")
+ msg)).subscribe();
} }
@Override @Override

View file

@ -1,5 +1,6 @@
package buttondevteam.discordplugin.commands; package buttondevteam.discordplugin.commands;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass; import buttondevteam.lib.chat.CommandClass;
@CommandClass(helpText = { @CommandClass(helpText = {
@ -7,12 +8,17 @@ import buttondevteam.lib.chat.CommandClass;
"Shows some info about a command or lists the available commands.", // "Shows some info about a command or lists the available commands.", //
}) })
public class HelpCommand extends ICommand2DC { public class HelpCommand extends ICommand2DC {
@Override @Command2.Subcommand
public boolean def(Command2DCSender sender, String args) { public boolean def(Command2DCSender sender, @Command2.TextArg @Command2.OptionalArg String args) {
if (args.length() == 0) if (args == null || args.length() == 0)
sender.sendMessage(getManager().getCommandsText()); sender.sendMessage(getManager().getCommandsText());
else {
String[] ht = getManager().getHelpText(args);
if (ht == null)
sender.sendMessage("Command not found: " + args);
else else
sender.sendMessage("Soon:tm:"); //TODO sender.sendMessage(ht);
}
return true; return true;
} }
} }

View file

@ -22,7 +22,7 @@ public class CommandListener {
if (!message.getContent().isPresent()) if (!message.getContent().isPresent())
return false; //Pin messages and such, let the mcchat listener deal with it return false; //Pin messages and such, let the mcchat listener deal with it
final MessageChannel channel = message.getChannel().block(); final MessageChannel channel = message.getChannel().block();
@SuppressWarnings("OptionalGetWithoutIsPresent") val content = message.getContent().get(); val content = message.getContent().get();
if (channel == null) return false; if (channel == null) return false;
if (!mentionedonly) { //mentionedonly conditions are in CommonListeners if (!mentionedonly) { //mentionedonly conditions are in CommonListeners
if (!(channel instanceof PrivateChannel) if (!(channel instanceof PrivateChannel)
@ -57,6 +57,7 @@ public class CommandListener {
} }
private static boolean checkanddeletemention(StringBuilder cmdwithargs, String mention, Message message) { private static boolean checkanddeletemention(StringBuilder cmdwithargs, String mention, Message message) {
final char prefix = DiscordPlugin.getPrefix();
if (message.getContent().orElse("").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());
@ -67,14 +68,16 @@ public class CommandListener {
for (; i < cmdwithargs.length() && cmdwithargs.charAt(i) == ' '; i++) for (; i < cmdwithargs.length() && cmdwithargs.charAt(i) == ' '; i++)
; //Removes any space before the command ; //Removes any space before the command
cmdwithargs.delete(0, i); cmdwithargs.delete(0, i);
cmdwithargs.insert(0, DiscordPlugin.getPrefix()); //Always use the prefix for processing cmdwithargs.insert(0, prefix); //Always use the prefix for processing
} else } else
cmdwithargs.replace(0, cmdwithargs.length(), DiscordPlugin.getPrefix() + "help"); cmdwithargs.replace(0, cmdwithargs.length(), prefix + "help");
else { else {
if (cmdwithargs.length() == 0)
cmdwithargs.replace(0, cmdwithargs.length(), prefix + "help");
else if (cmdwithargs.charAt(0) != prefix)
cmdwithargs.insert(0, prefix);
return false; //Don't treat / as mention, mentions can be used in public mcchat return false; //Don't treat / as mention, mentions can be used in public mcchat
} }
if (cmdwithargs.length() == 0)
cmdwithargs.replace(0, cmdwithargs.length(), DiscordPlugin.getPrefix() + "help");
return true; return true;
} }
} }

View file

@ -33,6 +33,8 @@ public class CommonListeners {
val author = event.getMessage().getAuthor(); val author = event.getMessage().getAuthor();
if (!author.isPresent() || author.get().isBot()) if (!author.isPresent() || author.get().isBot())
return; return;
//System.out.println("Author: "+author.get());
//System.out.println("Bot: "+author.get().isBot());
if (FunModule.executeMemes(event.getMessage())) if (FunModule.executeMemes(event.getMessage()))
return; return;
try { try {
@ -42,6 +44,7 @@ public class CommonListeners {
|| event.getMessage().getContent().orElse("").contains("channelcon")) //Only 'channelcon' is allowed in other channels || event.getMessage().getContent().orElse("").contains("channelcon")) //Only 'channelcon' is allowed in other channels
handled = CommandListener.runCommand(event.getMessage(), true); //#bot is handled here handled = CommandListener.runCommand(event.getMessage(), true); //#bot is handled here
if (handled) return; if (handled) return;
//System.out.println("Message handling");
val mcchat = Component.getComponents().get(MinecraftChatModule.class); val mcchat = Component.getComponents().get(MinecraftChatModule.class);
if (mcchat != null && mcchat.isEnabled()) //ComponentManager.isEnabled() searches the component again if (mcchat != null && mcchat.isEnabled()) //ComponentManager.isEnabled() searches the component again
handled = ((MinecraftChatModule) mcchat).getListener().handleDiscord(event); //Also runs Discord commands in chat channels handled = ((MinecraftChatModule) mcchat).getListener().handleDiscord(event); //Also runs Discord commands in chat channels

View file

@ -5,7 +5,6 @@ import buttondevteam.core.component.channel.ChatRoom;
import buttondevteam.discordplugin.DiscordConnectedPlayer; import buttondevteam.discordplugin.DiscordConnectedPlayer;
import buttondevteam.lib.TBMCSystemChatEvent; import buttondevteam.lib.TBMCSystemChatEvent;
import discord4j.core.object.entity.MessageChannel; import discord4j.core.object.entity.MessageChannel;
import discord4j.core.object.entity.TextChannel;
import discord4j.core.object.entity.User; import discord4j.core.object.entity.User;
import discord4j.core.object.util.Snowflake; import discord4j.core.object.util.Snowflake;
import lombok.NonNull; import lombok.NonNull;
@ -65,7 +64,7 @@ public class MCChatCustom {
private CustomLMD(@NonNull MessageChannel channel, @NonNull User user, private CustomLMD(@NonNull MessageChannel channel, @NonNull User user,
@NonNull String groupid, @NonNull Channel mcchannel, @NonNull DiscordConnectedPlayer dcp, int toggles, Set<TBMCSystemChatEvent.BroadcastTarget> brtoggles) { @NonNull String groupid, @NonNull Channel mcchannel, @NonNull DiscordConnectedPlayer dcp, int toggles, Set<TBMCSystemChatEvent.BroadcastTarget> brtoggles) {
super((TextChannel) channel, user); super(channel, user);
groupID = groupid; groupID = groupid;
this.mcchannel = mcchannel; this.mcchannel = mcchannel;
this.dcp = dcp; this.dcp = dcp;

View file

@ -236,6 +236,7 @@ public class MCChatListener implements Listener {
if (CommandListener.runCommand(ev.getMessage(), true)) if (CommandListener.runCommand(ev.getMessage(), true))
return true; //Allow running commands in chat channels return true; //Allow running commands in chat channels
MCChatUtils.resetLastMessage(channel); MCChatUtils.resetLastMessage(channel);
//System.out.println("Message: "+ev.getMessage().getAuthor().toString());
recevents.add(ev); recevents.add(ev);
if (rectask != null) if (rectask != null)
return true; return true;

View file

@ -7,7 +7,6 @@ import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.lib.player.TBMCPlayer; import buttondevteam.lib.player.TBMCPlayer;
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.TextChannel;
import discord4j.core.object.entity.User; import discord4j.core.object.entity.User;
import lombok.val; import lombok.val;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -44,7 +43,7 @@ public class MCChatPrivate {
if (!start) if (!start)
MCChatUtils.lastmsgfromd.remove(channel.getId().asLong()); MCChatUtils.lastmsgfromd.remove(channel.getId().asLong());
return start // return start //
? lastmsgPerUser.add(new MCChatUtils.LastMsgData((TextChannel) channel, user)) // Doesn't support group DMs ? lastmsgPerUser.add(new MCChatUtils.LastMsgData(channel, user)) // Doesn't support group DMs
: lastmsgPerUser.removeIf(lmd -> lmd.channel.getId().asLong() == channel.getId().asLong()); : lastmsgPerUser.removeIf(lmd -> lmd.channel.getId().asLong() == channel.getId().asLong());
} }

View file

@ -9,7 +9,6 @@ import buttondevteam.lib.TBMCSystemChatEvent;
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.message.MessageCreateEvent;
import discord4j.core.object.entity.MessageChannel; import discord4j.core.object.entity.MessageChannel;
import discord4j.core.object.util.Snowflake; import discord4j.core.object.util.Snowflake;
import lombok.Getter; import lombok.Getter;
@ -74,7 +73,6 @@ public class MinecraftChatModule extends Component<DiscordPlugin> {
protected void enable() { protected void enable() {
if (DPUtils.disableIfConfigError(this, chatChannel())) return; if (DPUtils.disableIfConfigError(this, chatChannel())) return;
listener = new MCChatListener(this); listener = new MCChatListener(this);
DiscordPlugin.dc.getEventDispatcher().on(MessageCreateEvent.class).subscribe(listener::handleDiscord);
TBMCCoreAPI.RegisterEventsForExceptions(listener, getPlugin()); TBMCCoreAPI.RegisterEventsForExceptions(listener, getPlugin());
TBMCCoreAPI.RegisterEventsForExceptions(new MCListener(this), getPlugin());//These get undone if restarting/resetting - it will ignore events if disabled TBMCCoreAPI.RegisterEventsForExceptions(new MCListener(this), getPlugin());//These get undone if restarting/resetting - it will ignore events if disabled
getPlugin().getManager().registerCommand(new MCChatCommand()); getPlugin().getManager().registerCommand(new MCChatCommand());

View file

@ -104,9 +104,9 @@ public class DiscordMCCommand extends ICommand2MC {
} }
DiscordPlugin.mainServer.getInvites().limitRequest(1) DiscordPlugin.mainServer.getInvites().limitRequest(1)
.switchIfEmpty(Mono.fromRunnable(() -> sender.sendMessage("§cNo invites found for the server."))) .switchIfEmpty(Mono.fromRunnable(() -> sender.sendMessage("§cNo invites found for the server.")))
.subscribe(inv -> {//TODO: Needs manage server perms .subscribe(inv -> {
sender.sendMessage("§bInvite link: https://discord.gg/" + inv.getCode()); sender.sendMessage("§bInvite link: https://discord.gg/" + inv.getCode());
}); }, e -> sender.sendMessage("§cThe invite link is not set and the bot has no permission to get it."));
} }
@Override @Override