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
val greetCmdRequest = ApplicationCommandRequest.builder()
.name(command.getCommandPath) //TODO: Main path
.description("A ChromaBot command.") //TODO: Description
.description("Connect your Minecraft account.") //TODO: Description
.addOption(ApplicationCommandOptionData.builder()
.name("name")
.description("Your name")

View file

@ -3,19 +3,22 @@ package buttondevteam.discordplugin.commands
import buttondevteam.discordplugin.DPUtils
import buttondevteam.lib.chat.Command2Sender
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 {
def getMessage: Message = this.message
import java.util.Optional
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 = {
if (message.isEmpty) return ()
var msg = DPUtils.sanitizeString(message)
msg = Character.toLowerCase(message.charAt(0)) + message.substring(1)
this.message.getChannel.flatMap((ch: MessageChannel) => ch.createMessage(this.message.getAuthor.map((u: User) => DPUtils.nickMention(u.getId) + ", ").orElse("") + msg)).subscribe()
//Some(message) map DPUtils.sanitizeString map { (msg: String) => Character.toLowerCase(msg.charAt(0)) + msg.substring(1) } foreach event.reply - don't even need this
event.reply(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 allows using the private Minecraft chat and other things.")) class ConnectCommand extends ICommand2DC {
@Command2.Subcommand def `def`(sender: Command2DCSender, Minecraftname: String): Boolean = {
val message = sender.getMessage
val channel = message.getChannel.block
val author = message.getAuthor.orElse(null)
if (author == null || channel == null) return true
val author = sender.event.getInteraction.getUser
println("Author is " + author.getUsername)
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)
}
//noinspection ScalaDeprecation
val p = Bukkit.getOfflinePlayer(Minecraftname)
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
}
val pl = TBMCPlayerBase.getPlayer(p.getUniqueId, classOf[TBMCPlayer])
val dp = pl.getAs(classOf[DiscordPlayer])
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
}
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")
true
}

View file

@ -11,8 +11,8 @@ import reactor.core.scala.publisher.SMono
class DebugCommand extends ICommand2DC {
@Command2.Subcommand
override def `def`(sender: Command2DCSender): Boolean = {
SMono(sender.getMessage.getAuthorAsMember)
.switchIfEmpty(Option(sender.getMessage.getAuthor.orElse(null)) //Support DMs
SMono.justOrEmpty(sender.authorAsMember)
.switchIfEmpty(Option(sender.author) //Support DMs
.map((u: User) => SMono(u.asMember(DiscordPlugin.mainServer.getId))).getOrElse(SMono.empty))
.flatMap((m: Member) => DiscordPlugin.plugin.modRole.get
.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 {
@Command2.Subcommand
def `def`(sender: Command2DCSender, @Command2.OptionalArg @Command2.TextArg user: String): Boolean = {
val message = sender.getMessage
var target: User = null
val channel = message.getChannel.block
assert(channel != null)
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 (user == null || user.isEmpty) target = sender.author
else { // TODO: Mention option
}
if (target == null) {
sender.sendMessage("An error occurred.")
@ -59,7 +27,7 @@ class UserinfoCommand extends ICommand2DC {
val dp = ChromaGamerBase.getUser(target.getId.asString, classOf[DiscordPlayer])
val uinfo = new StringBuilder("User info for ").append(target.getUsername).append(":\n")
uinfo.append(dp.getInfo(InfoTarget.Discord))
channel.createMessage(uinfo.toString).subscribe()
sender.sendMessage(uinfo.toString)
true
}

View file

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

View file

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

View file

@ -16,22 +16,20 @@ import discord4j.core.`object`.entity.channel.PrivateChannel
class MCChatCommand(private val module: MinecraftChatModule) extends ICommand2DC {
@Command2.Subcommand override def `def`(sender: Command2DCSender): Boolean = {
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
}
val message = sender.getMessage
val channel = message.getChannel.block
@SuppressWarnings(Array("OptionalGetWithoutIsPresent")) val author = message.getAuthor.get
val channel = sender.event.getInteraction.getChannel.block()
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
}
val user: DiscordPlayer = ChromaGamerBase.getUser(author.getId.asString, classOf[DiscordPlayer])
val mcchat: Boolean = !(user.isMinecraftChatEnabled)
MCChatPrivate.privateMCChat(channel, mcchat, author, user)
DPUtils.reply(message, channel, "Minecraft chat " +
val user: DiscordPlayer = ChromaGamerBase.getUser(sender.author.getId.asString, classOf[DiscordPlayer])
val mcchat: Boolean = !user.isMinecraftChatEnabled
MCChatPrivate.privateMCChat(channel, mcchat, sender.author, user)
sender.sendMessage("Minecraft chat " +
(if (mcchat) "enabled. Use '" + DiscordPlugin.getPrefix + "mcchat' again to turn it off."
else "disabled.")).subscribe()
else "disabled."))
true
// 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()
}
@EventHandler def onCommandSend(event: PlayerCommandSendEvent): Boolean = event.getCommands.add("g")
@EventHandler def onVanish(event: VanishStatusChangeEvent): Unit = {
if (event.isCancelled) return ()
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 = {
val role = checkAndGetRole(sender, rolename)
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 {
case e: Exception =>
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 = {
val role = checkAndGetRole(sender, rolename)
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 {
case e: Exception =>
TBMCCoreAPI.SendException("Error while removing role!", e, grm)