Update sender to support slash commands

This commit is contained in:
Norbi Peti 2022-07-21 02:24:53 +02:00
parent 0610ee434b
commit ac3e6655e6
No known key found for this signature in database
GPG key ID: DBA4C4549A927E56
10 changed files with 42 additions and 73 deletions

View file

@ -17,7 +17,7 @@ class Command2DC extends Command2[ICommand2DC, Command2DCSender] {
super.registerCommand(command, DiscordPlugin.getPrefix) //Needs to be configurable for the helps super.registerCommand(command, DiscordPlugin.getPrefix) //Needs to be configurable for the helps
val greetCmdRequest = ApplicationCommandRequest.builder() val greetCmdRequest = ApplicationCommandRequest.builder()
.name(command.getCommandPath) //TODO: Main path .name(command.getCommandPath) //TODO: Main path
.description("A ChromaBot command.") //TODO: Description .description("Connect your Minecraft account.") //TODO: Description
.addOption(ApplicationCommandOptionData.builder() .addOption(ApplicationCommandOptionData.builder()
.name("name") .name("name")
.description("Your name") .description("Your name")

View file

@ -3,19 +3,22 @@ package buttondevteam.discordplugin.commands
import buttondevteam.discordplugin.DPUtils import buttondevteam.discordplugin.DPUtils
import buttondevteam.lib.chat.Command2Sender import buttondevteam.lib.chat.Command2Sender
import discord4j.core.`object`.entity.channel.MessageChannel import discord4j.core.`object`.entity.channel.MessageChannel
import discord4j.core.`object`.entity.{Message, User} import discord4j.core.`object`.entity.{Member, Message, User}
import discord4j.core.event.domain.interaction.ChatInputInteractionEvent
class Command2DCSender(val message: Message) extends Command2Sender { import java.util.Optional
def getMessage: Message = this.message import reactor.core.scala.publisher.javaOptional2ScalaOption;
class Command2DCSender(val event: ChatInputInteractionEvent) extends Command2Sender {
val authorAsMember: Option[Member] = event.getInteraction.getMember
val author: User = event.getInteraction.getUser
override def sendMessage(message: String): Unit = { override def sendMessage(message: String): Unit = {
if (message.isEmpty) return () if (message.isEmpty) return ()
var msg = DPUtils.sanitizeString(message) //Some(message) map DPUtils.sanitizeString map { (msg: String) => Character.toLowerCase(msg.charAt(0)) + msg.substring(1) } foreach event.reply - don't even need this
msg = Character.toLowerCase(message.charAt(0)) + message.substring(1) event.reply(message);
this.message.getChannel.flatMap((ch: MessageChannel) => ch.createMessage(this.message.getAuthor.map((u: User) => DPUtils.nickMention(u.getId) + ", ").orElse("") + msg)).subscribe()
} }
override def sendMessage(message: Array[String]): Unit = sendMessage(String.join("\n", message: _*)) override def sendMessage(message: Array[String]): Unit = sendMessage(String.join("\n", message: _*))
override def getName: String = Option(message.getAuthor.orElse(null)).map(_.getUsername).getOrElse("Discord") override def getName: String = authorAsMember.flatMap(_.getNickname).getOrElse(author.getUsername)
} }

View file

@ -21,28 +21,26 @@ import org.bukkit.entity.Player
"This command lets you connect your account with a Minecraft account." + "This command lets you connect your account with a Minecraft account." +
" This allows using the private Minecraft chat and other things.")) class ConnectCommand extends ICommand2DC { " This allows using the private Minecraft chat and other things.")) class ConnectCommand extends ICommand2DC {
@Command2.Subcommand def `def`(sender: Command2DCSender, Minecraftname: String): Boolean = { @Command2.Subcommand def `def`(sender: Command2DCSender, Minecraftname: String): Boolean = {
val message = sender.getMessage val author = sender.event.getInteraction.getUser
val channel = message.getChannel.block println("Author is " + author.getUsername)
val author = message.getAuthor.orElse(null)
if (author == null || channel == null) return true
if (ConnectCommand.WaitingToConnect.inverse.containsKey(author.getId.asString)) { if (ConnectCommand.WaitingToConnect.inverse.containsKey(author.getId.asString)) {
channel.createMessage("Replacing " + ConnectCommand.WaitingToConnect.inverse.get(author.getId.asString) + " with " + Minecraftname).subscribe() sender.event.reply("Replacing " + ConnectCommand.WaitingToConnect.inverse.get(author.getId.asString) + " with " + Minecraftname).subscribe()
ConnectCommand.WaitingToConnect.inverse.remove(author.getId.asString) ConnectCommand.WaitingToConnect.inverse.remove(author.getId.asString)
} }
//noinspection ScalaDeprecation //noinspection ScalaDeprecation
val p = Bukkit.getOfflinePlayer(Minecraftname) val p = Bukkit.getOfflinePlayer(Minecraftname)
if (p == null) { if (p == null) {
channel.createMessage("The specified Minecraft player cannot be found").subscribe() sender.event.reply("The specified Minecraft player cannot be found").subscribe()
return true return true
} }
val pl = TBMCPlayerBase.getPlayer(p.getUniqueId, classOf[TBMCPlayer]) val pl = TBMCPlayerBase.getPlayer(p.getUniqueId, classOf[TBMCPlayer])
val dp = pl.getAs(classOf[DiscordPlayer]) val dp = pl.getAs(classOf[DiscordPlayer])
if (dp != null && author.getId.asString == dp.getDiscordID) { if (dp != null && author.getId.asString == dp.getDiscordID) {
channel.createMessage("You already have this account connected.").subscribe() sender.event.reply("You already have this account connected.").subscribe()
return true return true
} }
ConnectCommand.WaitingToConnect.put(p.getName, author.getId.asString) ConnectCommand.WaitingToConnect.put(p.getName, author.getId.asString)
channel.createMessage("Alright! Now accept the connection in Minecraft from the account " + Minecraftname + " before the next server restart. You can also adjust the Minecraft name you want to connect to by running this command again.").subscribe() sender.event.reply("Alright! Now accept the connection in Minecraft from the account " + Minecraftname + " before the next server restart. You can also adjust the Minecraft name you want to connect to by running this command again.").subscribe()
if (p.isOnline) p.asInstanceOf[Player].sendMessage("§bTo connect with the Discord account " + author.getUsername + "#" + author.getDiscriminator + " do /discord accept") if (p.isOnline) p.asInstanceOf[Player].sendMessage("§bTo connect with the Discord account " + author.getUsername + "#" + author.getDiscriminator + " do /discord accept")
true true
} }

View file

@ -11,8 +11,8 @@ import reactor.core.scala.publisher.SMono
class DebugCommand extends ICommand2DC { class DebugCommand extends ICommand2DC {
@Command2.Subcommand @Command2.Subcommand
override def `def`(sender: Command2DCSender): Boolean = { override def `def`(sender: Command2DCSender): Boolean = {
SMono(sender.getMessage.getAuthorAsMember) SMono.justOrEmpty(sender.authorAsMember)
.switchIfEmpty(Option(sender.getMessage.getAuthor.orElse(null)) //Support DMs .switchIfEmpty(Option(sender.author) //Support DMs
.map((u: User) => SMono(u.asMember(DiscordPlugin.mainServer.getId))).getOrElse(SMono.empty)) .map((u: User) => SMono(u.asMember(DiscordPlugin.mainServer.getId))).getOrElse(SMono.empty))
.flatMap((m: Member) => DiscordPlugin.plugin.modRole.get .flatMap((m: Member) => DiscordPlugin.plugin.modRole.get
.map(mr => m.getRoleIds.stream.anyMatch((r: Snowflake) => r == mr.getId)) .map(mr => m.getRoleIds.stream.anyMatch((r: Snowflake) => r == mr.getId))

View file

@ -16,41 +16,9 @@ import scala.jdk.CollectionConverters.ListHasAsScala
class UserinfoCommand extends ICommand2DC { class UserinfoCommand extends ICommand2DC {
@Command2.Subcommand @Command2.Subcommand
def `def`(sender: Command2DCSender, @Command2.OptionalArg @Command2.TextArg user: String): Boolean = { def `def`(sender: Command2DCSender, @Command2.OptionalArg @Command2.TextArg user: String): Boolean = {
val message = sender.getMessage
var target: User = null var target: User = null
val channel = message.getChannel.block if (user == null || user.isEmpty) target = sender.author
assert(channel != null) else { // TODO: Mention option
if (user == null || user.isEmpty) target = message.getAuthor.orElse(null)
else {
val firstmention = message.getUserMentions.asScala.find((m: User) => !(m.getId.asString == DiscordPlugin.dc.getSelfId.asString))
if (firstmention.isDefined) target = firstmention.get
else if (user.contains("#")) {
val targettag = user.split("#")
val targets = getUsers(message, targettag(0))
if (targets.isEmpty) {
channel.createMessage("The user cannot be found (by name): " + user).subscribe()
return true
}
targets.collectFirst {
case user => user.getDiscriminator.equalsIgnoreCase(targettag(1))
}
if (target == null) {
channel.createMessage("The user cannot be found (by discriminator): " + user + "(Found " + targets.size + " users with the name.)").subscribe()
return true
}
}
else {
val targets = getUsers(message, user)
if (targets.isEmpty) {
channel.createMessage("The user cannot be found on Discord: " + user).subscribe()
return true
}
if (targets.size > 1) {
channel.createMessage("Multiple users found with that (nick)name. Please specify the whole tag, like ChromaBot#6338 or use a ping.").subscribe()
return true
}
target = targets.head
}
} }
if (target == null) { if (target == null) {
sender.sendMessage("An error occurred.") sender.sendMessage("An error occurred.")
@ -59,7 +27,7 @@ class UserinfoCommand extends ICommand2DC {
val dp = ChromaGamerBase.getUser(target.getId.asString, classOf[DiscordPlayer]) val dp = ChromaGamerBase.getUser(target.getId.asString, classOf[DiscordPlayer])
val uinfo = new StringBuilder("User info for ").append(target.getUsername).append(":\n") val uinfo = new StringBuilder("User info for ").append(target.getUsername).append(":\n")
uinfo.append(dp.getInfo(InfoTarget.Discord)) uinfo.append(dp.getInfo(InfoTarget.Discord))
channel.createMessage(uinfo.toString).subscribe() sender.sendMessage(uinfo.toString)
true true
} }

View file

@ -1,5 +1,6 @@
package buttondevteam.discordplugin.listeners package buttondevteam.discordplugin.listeners
import buttondevteam.discordplugin.commands.{Command2DCSender, ConnectCommand}
import buttondevteam.discordplugin.fun.FunModule import buttondevteam.discordplugin.fun.FunModule
import buttondevteam.discordplugin.mcchat.MinecraftChatModule import buttondevteam.discordplugin.mcchat.MinecraftChatModule
import buttondevteam.discordplugin.role.GameRoleModule import buttondevteam.discordplugin.role.GameRoleModule
@ -40,9 +41,12 @@ object CommonListeners {
SFlux(dispatcher.on(classOf[RoleDeleteEvent])).subscribe(GameRoleModule.handleRoleEvent) SFlux(dispatcher.on(classOf[RoleDeleteEvent])).subscribe(GameRoleModule.handleRoleEvent)
SFlux(dispatcher.on(classOf[RoleUpdateEvent])).subscribe(GameRoleModule.handleRoleEvent) SFlux(dispatcher.on(classOf[RoleUpdateEvent])).subscribe(GameRoleModule.handleRoleEvent)
SFlux(dispatcher.on(classOf[ChatInputInteractionEvent], event => { SFlux(dispatcher.on(classOf[ChatInputInteractionEvent], event => {
if(event.getCommandName() eq "help") if(event.getCommandName() equals "connect") {
event.reply("Hello there") println("Message: "+event.getInteraction.getMessage.isPresent)
else val asd = Mono.just(new ConnectCommand().`def`(new Command2DCSender(event)))
println("Ran connect command")
asd
} else
Mono.empty() Mono.empty()
})).subscribe() })).subscribe()
} }

View file

@ -34,7 +34,7 @@ import javax.annotation.Nullable
)) ))
class ChannelconCommand(private val module: MinecraftChatModule) extends ICommand2DC { class ChannelconCommand(private val module: MinecraftChatModule) extends ICommand2DC {
@Command2.Subcommand def remove(sender: Command2DCSender): Boolean = { @Command2.Subcommand def remove(sender: Command2DCSender): Boolean = {
val message = sender.getMessage val message: Message = null // TODO
if (checkPerms(message, null)) return true if (checkPerms(message, null)) return true
else if (MCChatCustom.removeCustomChat(message.getChannelId)) else if (MCChatCustom.removeCustomChat(message.getChannelId))
DPUtils.reply(message, SMono.empty, "channel connection removed.").subscribe() DPUtils.reply(message, SMono.empty, "channel connection removed.").subscribe()
@ -44,7 +44,7 @@ class ChannelconCommand(private val module: MinecraftChatModule) extends IComman
} }
@Command2.Subcommand def toggle(sender: Command2DCSender, @Command2.OptionalArg toggle: String): Boolean = { @Command2.Subcommand def toggle(sender: Command2DCSender, @Command2.OptionalArg toggle: String): Boolean = {
val message = sender.getMessage val message: Message = null // TODO
if (checkPerms(message, null)) { if (checkPerms(message, null)) {
return true return true
} }
@ -93,7 +93,7 @@ class ChannelconCommand(private val module: MinecraftChatModule) extends IComman
} }
@Command2.Subcommand def `def`(sender: Command2DCSender, channelID: String): Boolean = { @Command2.Subcommand def `def`(sender: Command2DCSender, channelID: String): Boolean = {
val message = sender.getMessage val message: Message = null // TODO
if (!(module.allowCustomChat.get)) { if (!(module.allowCustomChat.get)) {
sender.sendMessage("channel connection is not allowed on this Minecraft server.") sender.sendMessage("channel connection is not allowed on this Minecraft server.")
return true return true

View file

@ -16,22 +16,20 @@ import discord4j.core.`object`.entity.channel.PrivateChannel
class MCChatCommand(private val module: MinecraftChatModule) extends ICommand2DC { class MCChatCommand(private val module: MinecraftChatModule) extends ICommand2DC {
@Command2.Subcommand override def `def`(sender: Command2DCSender): Boolean = { @Command2.Subcommand override def `def`(sender: Command2DCSender): Boolean = {
if (!module.allowPrivateChat.get) { if (!module.allowPrivateChat.get) {
sender.sendMessage("using the private chat is not allowed on this Minecraft server.") sender.sendMessage("Using the private chat is not allowed on this Minecraft server.")
return true return true
} }
val message = sender.getMessage val channel = sender.event.getInteraction.getChannel.block()
val channel = message.getChannel.block
@SuppressWarnings(Array("OptionalGetWithoutIsPresent")) val author = message.getAuthor.get
if (!channel.isInstanceOf[PrivateChannel]) { if (!channel.isInstanceOf[PrivateChannel]) {
DPUtils.reply(message, channel, "this command can only be issued in a direct message with the bot.").subscribe() sender.sendMessage("This command can only be issued in a direct message with the bot.")
return true return true
} }
val user: DiscordPlayer = ChromaGamerBase.getUser(author.getId.asString, classOf[DiscordPlayer]) val user: DiscordPlayer = ChromaGamerBase.getUser(sender.author.getId.asString, classOf[DiscordPlayer])
val mcchat: Boolean = !(user.isMinecraftChatEnabled) val mcchat: Boolean = !user.isMinecraftChatEnabled
MCChatPrivate.privateMCChat(channel, mcchat, author, user) MCChatPrivate.privateMCChat(channel, mcchat, sender.author, user)
DPUtils.reply(message, channel, "Minecraft chat " + sender.sendMessage("Minecraft chat " +
(if (mcchat) "enabled. Use '" + DiscordPlugin.getPrefix + "mcchat' again to turn it off." (if (mcchat) "enabled. Use '" + DiscordPlugin.getPrefix + "mcchat' again to turn it off."
else "disabled.")).subscribe() else "disabled."))
true true
// TODO: Pin channel switching to indicate the current channel // TODO: Pin channel switching to indicate the current channel
} }

View file

@ -136,8 +136,6 @@ class MCListener(val module: MinecraftChatModule) extends Listener {
.filter(_.startsWith(token)).map("@" + _).doOnNext(event.getCompletions.add(_)).blockLast() .filter(_.startsWith(token)).map("@" + _).doOnNext(event.getCompletions.add(_)).blockLast()
} }
@EventHandler def onCommandSend(event: PlayerCommandSendEvent): Boolean = event.getCommands.add("g")
@EventHandler def onVanish(event: VanishStatusChangeEvent): Unit = { @EventHandler def onVanish(event: VanishStatusChangeEvent): Unit = {
if (event.isCancelled) return () if (event.isCancelled) return ()
Bukkit.getScheduler.runTask(DiscordPlugin.plugin, () => MCChatUtils.updatePlayerList()) Bukkit.getScheduler.runTask(DiscordPlugin.plugin, () => MCChatUtils.updatePlayerList())

View file

@ -14,7 +14,7 @@ import reactor.core.publisher.Mono
)) def add(sender: Command2DCSender, @Command2.TextArg rolename: String): Boolean = { )) def add(sender: Command2DCSender, @Command2.TextArg rolename: String): Boolean = {
val role = checkAndGetRole(sender, rolename) val role = checkAndGetRole(sender, rolename)
if (role == null) return true if (role == null) return true
try sender.getMessage.getAuthorAsMember.flatMap(m => m.addRole(role.getId).switchIfEmpty(Mono.fromRunnable(() => sender.sendMessage("added role.")))).subscribe() try sender.authorAsMember.foreach(m => m.addRole(role.getId).subscribe(_ => sender.sendMessage("Added role.")))
catch { catch {
case e: Exception => case e: Exception =>
TBMCCoreAPI.SendException("Error while adding role!", e, grm) TBMCCoreAPI.SendException("Error while adding role!", e, grm)
@ -29,7 +29,7 @@ import reactor.core.publisher.Mono
)) def remove(sender: Command2DCSender, @Command2.TextArg rolename: String): Boolean = { )) def remove(sender: Command2DCSender, @Command2.TextArg rolename: String): Boolean = {
val role = checkAndGetRole(sender, rolename) val role = checkAndGetRole(sender, rolename)
if (role == null) return true if (role == null) return true
try sender.getMessage.getAuthorAsMember.flatMap(m => m.removeRole(role.getId).switchIfEmpty(Mono.fromRunnable(() => sender.sendMessage("removed role.")))).subscribe() try sender.authorAsMember.foreach(m => m.removeRole(role.getId).subscribe(_ => sender.sendMessage("Removed role.")))
catch { catch {
case e: Exception => case e: Exception =>
TBMCCoreAPI.SendException("Error while removing role!", e, grm) TBMCCoreAPI.SendException("Error while removing role!", e, grm)