discord-kagebot/src/main/kotlin/moe/kageru/kagebot/command/Command.kt

71 lines
2.7 KiB
Kotlin
Raw Normal View History

package moe.kageru.kagebot.command
import com.fasterxml.jackson.annotation.JsonProperty
2019-06-15 14:15:34 +02:00
import moe.kageru.kagebot.Globals
2019-07-17 21:16:17 +02:00
import moe.kageru.kagebot.Log
import moe.kageru.kagebot.MessageUtil
import moe.kageru.kagebot.Util.applyIf
2019-07-13 15:39:50 +02:00
import moe.kageru.kagebot.config.Config
import moe.kageru.kagebot.features.MessageFeature
import org.javacord.api.entity.message.MessageAuthor
import org.javacord.api.entity.message.embed.EmbedBuilder
import org.javacord.api.event.message.MessageCreateEvent
private const val AUTHOR_PLACEHOLDER = "@@"
class Command(
val trigger: String,
private val response: String? = null,
private val permissions: Permissions?,
@JsonProperty("action")
private val actions: MessageActions?,
embed: List<String>?,
feature: String?,
matchType: String?
) {
val matchType: MatchType = matchType?.let { type ->
MatchType.values().find { it.name.equals(type, ignoreCase = true) }
?: throw IllegalArgumentException("Invalid [command.matchType]: “$matchType")
} ?: MatchType.PREFIX
val regex: Regex? = if (this.matchType == MatchType.REGEX) Regex(trigger) else null
val embed: EmbedBuilder? = embed?.let(MessageUtil::listToEmbed)
private val feature: MessageFeature? = feature?.let { Config.features.findByString(it) }
2019-11-11 19:09:58 +01:00
fun matches(msg: String) = this.matchType.matches(msg, this)
2019-07-11 20:14:22 +02:00
fun isAllowed(message: MessageCreateEvent) = permissions?.isAllowed(message) ?: true
2019-11-11 19:09:58 +01:00
fun execute(message: MessageCreateEvent) {
2019-07-17 21:16:17 +02:00
Log.info("Executing command ${this.trigger} triggered by user ${message.messageAuthor.discriminatedName} (ID: ${message.messageAuthor.id})")
2019-06-15 14:15:34 +02:00
Globals.commandCounter.incrementAndGet()
this.actions?.run(message, this)
this.response?.let {
2019-06-15 12:48:23 +02:00
message.channel.sendMessage(respond(message.messageAuthor, it))
}
this.embed?.let {
MessageUtil.sendEmbed(message.channel, embed)
}
this.feature?.handle(message)
}
private fun respond(author: MessageAuthor, response: String) =
response.applyIf(response.contains(AUTHOR_PLACEHOLDER)) {
it.replace(AUTHOR_PLACEHOLDER, MessageUtil.mention(author))
}
}
@Suppress("unused")
enum class MatchType {
PREFIX {
2019-08-30 15:27:11 +02:00
override fun matches(message: String, command: Command) = message.startsWith(command.trigger, ignoreCase = true)
},
CONTAINS {
2019-08-30 15:27:11 +02:00
override fun matches(message: String, command: Command) = message.contains(command.trigger, ignoreCase = true)
},
REGEX {
override fun matches(message: String, command: Command) = command.regex!!.matches(message)
};
abstract fun matches(message: String, command: Command): Boolean
}