Skip to content

Commit

Permalink
Add command to change Loritta's activity status
Browse files Browse the repository at this point in the history
  • Loading branch information
MrPowerGamerBR committed Aug 9, 2023
1 parent 53441ef commit fdd31ef
Show file tree
Hide file tree
Showing 5 changed files with 127 additions and 21 deletions.
18 changes: 10 additions & 8 deletions build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
kotlin("jvm") version "1.7.10"
kotlin("plugin.serialization") version "1.7.10"
kotlin("jvm") version "1.8.21"
kotlin("plugin.serialization") version "1.8.21"
id("com.google.cloud.tools.jib") version "3.1.4"
id("net.perfectdreams.i18nhelper.plugin") version "0.0.5-SNAPSHOT"
}
Expand Down Expand Up @@ -43,7 +43,8 @@ dependencies {
implementation("net.perfectdreams.sequins.text:text-utils:1.0.0")

// Pudding
api("net.perfectdreams.loritta.cinnamon.pudding:client:0.0.2-20220306.142003-161")
api("net.perfectdreams.loritta.cinnamon.pudding:client:0.0.2-SNAPSHOT")
implementation("net.perfectdreams.loritta:loritta-serializable-commons-jvm:2023-20230809.170349-3")

// Remove this after everything has been migrated to InteraKTions Unleashed
implementation("dev.kord:kord-rest:0.8.x-lori-fork-20221109.172532-14")
Expand Down Expand Up @@ -72,11 +73,12 @@ dependencies {
// Database
implementation("org.postgresql:postgresql:42.3.3")
implementation("com.zaxxer:HikariCP:5.0.1")
implementation("org.jetbrains.exposed:exposed-core:0.37.3")
implementation("org.jetbrains.exposed:exposed-dao:0.37.3")
implementation("org.jetbrains.exposed:exposed-jdbc:0.37.3")
implementation("net.perfectdreams.exposedpowerutils:postgres-power-utils:1.0.0")
implementation("net.perfectdreams.exposedpowerutils:postgres-java-time:1.0.0")
implementation("org.jetbrains.exposed:exposed-core:0.41.1")
implementation("org.jetbrains.exposed:exposed-dao:0.41.1")
implementation("org.jetbrains.exposed:exposed-jdbc:0.41.1")
implementation("net.perfectdreams.exposedpowerutils:postgres-power-utils:1.2.1")
implementation("net.perfectdreams.exposedpowerutils:postgres-java-time:1.2.1")
api("net.perfectdreams.exposedpowerutils:exposed-power-utils:1.2.1")

testImplementation("org.junit.jupiter:junit-jupiter:5.8.2")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.8.2")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,22 @@ package net.perfectdreams.loritta.helper

import dev.kord.rest.service.RestClient
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.launch
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import mu.KotlinLogging
import net.dv8tion.jda.api.JDA
import net.dv8tion.jda.api.JDABuilder
import net.dv8tion.jda.api.entities.Activity
import net.dv8tion.jda.api.requests.GatewayIntent
import net.dv8tion.jda.api.utils.MemberCachePolicy
import net.perfectdreams.loritta.cinnamon.pudding.utils.exposed.createOrUpdatePostgreSQLEnum
import net.perfectdreams.exposedpowerutils.sql.createOrUpdatePostgreSQLEnum
import net.perfectdreams.loritta.helper.interactions.commands.vanilla.LoriToolsCommand
import net.perfectdreams.loritta.helper.listeners.*
import net.perfectdreams.loritta.helper.network.Databases
Expand All @@ -39,6 +44,8 @@ import net.perfectdreams.loritta.helper.utils.topsonhos.TopSonhosRankingSender
import net.perfectdreams.loritta.morenitta.interactions.InteractionsListener
import net.perfectdreams.loritta.morenitta.interactions.InteractivityManager
import net.perfectdreams.loritta.morenitta.interactions.commands.UnleashedCommandManager
import net.perfectdreams.loritta.serializable.dashboard.requests.LorittaDashboardRPCRequest
import net.perfectdreams.loritta.serializable.dashboard.responses.LorittaDashboardRPCResponse
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.transactions.transaction
import java.time.LocalDateTime
Expand Down Expand Up @@ -188,4 +195,13 @@ class LorittaHelper(val config: LorittaHelperConfig, val fanArtsConfig: FanArtsC
fun launch(block: suspend CoroutineScope.() -> Unit) = GlobalScope.launch(executor) {
block.invoke(this)
}

suspend inline fun <reified T : LorittaDashboardRPCResponse> makeLorittaRPCRequest(rpc: LorittaDashboardRPCRequest): T {
return Json.decodeFromString<T>(
http.post("${config.lorittaApi.url.removeSuffix("/")}/api/v1/rpc") {
header("Authorization", config.lorittaApi.token)
setBody(Json.encodeToString<LorittaDashboardRPCRequest>(rpc))
}.bodyAsText()
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,43 @@ import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.http.content.*
import kotlinx.datetime.toKotlinInstant
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import mu.KotlinLogging
import net.dv8tion.jda.api.entities.Activity
import net.dv8tion.jda.api.entities.UserSnowflake
import net.perfectdreams.loritta.cinnamon.pudding.tables.BannedUsers
import net.perfectdreams.loritta.helper.LorittaHelper
import net.perfectdreams.loritta.helper.LorittaHelperKord
import net.perfectdreams.loritta.helper.utils.Constants
import mu.KotlinLogging
import net.dv8tion.jda.api.entities.UserSnowflake
import net.perfectdreams.loritta.helper.tables.EconomyState
import net.perfectdreams.loritta.helper.utils.Constants
import net.perfectdreams.loritta.helper.utils.extensions.await
import net.perfectdreams.loritta.helper.utils.slash.LoriToolsUtils
import net.perfectdreams.loritta.helper.utils.slash.PermissionLevel
import net.perfectdreams.loritta.morenitta.interactions.commands.*
import net.perfectdreams.loritta.morenitta.interactions.commands.options.ApplicationCommandOptions
import net.perfectdreams.loritta.morenitta.interactions.styled
import net.perfectdreams.loritta.serializable.dashboard.requests.LorittaDashboardRPCRequest
import net.perfectdreams.loritta.serializable.dashboard.responses.LorittaDashboardRPCResponse
import net.perfectdreams.pantufa.rpc.BanSparklyPowerPlayerLorittaBannedRequest
import net.perfectdreams.pantufa.rpc.BanSparklyPowerPlayerLorittaBannedResponse
import net.perfectdreams.pantufa.rpc.PantufaRPCRequest
import net.perfectdreams.pantufa.rpc.PantufaRPCResponse
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.transactions.transaction
import java.awt.Color
import java.time.DateTimeException
import java.time.Duration
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
import java.util.*


class LoriToolsCommand(val helper: LorittaHelper) : SlashCommandDeclarationWrapper {
override fun command() = slashCommand("loritools", "Ferramentas de administração relacionadas a Loritta") {
subcommand("loriban", "Bane alguém de usar a Loritta") {
Expand All @@ -48,6 +60,10 @@ class LoriToolsCommand(val helper: LorittaHelper) : SlashCommandDeclarationWrapp
subcommand("economy", "Altera o estado da economia da Loritta") {
executor = LoriEconomyStateExecutor(helper)
}

subcommand("status", "Altera o status da Loritta") {
executor = LoriStatusExecutor(helper)
}
}

class LoriBanExecutor(helper: LorittaHelper) : HelperExecutor(helper, PermissionLevel.ADMIN) {
Expand Down Expand Up @@ -334,7 +350,7 @@ class LoriToolsCommand(val helper: LorittaHelper) : SlashCommandDeclarationWrapp
}

when (result) {
is LoriBanRenameExecutor.UserBanRenamedResult -> {
is UserBanRenamedResult -> {
context.reply(true) {
content = "Motivo do ban foi alterado! <:lori_heart:853052040425766923>"
}
Expand All @@ -348,7 +364,7 @@ class LoriToolsCommand(val helper: LorittaHelper) : SlashCommandDeclarationWrapp
Color(214, 0, 255)
)
}
is LoriBanRenameExecutor.UserIsNotBannedResult -> {
is UserIsNotBannedResult -> {
context.reply(true) {
content = "O usuário $userId (<@$userId>) não está banido, então não dá para alterar o motivo do ban dele!"
}
Expand Down Expand Up @@ -397,11 +413,76 @@ class LoriToolsCommand(val helper: LorittaHelper) : SlashCommandDeclarationWrapp
}
}
}
}

private sealed class BanRenameResult
class LoriStatusExecutor(helper: LorittaHelper) : HelperExecutor(helper, PermissionLevel.ADMIN) {
companion object {
// Define the format of the input string
private val formatter = DateTimeFormatter.ofPattern("HH:mm dd/MM/yyyy")
private var zoneId = ZoneId.of("America/Sao_Paulo")
}

private object UserIsNotBannedResult : BanRenameResult()
inner class Options : ApplicationCommandOptions() {
val text = string("text", "Texto do novo status")
val type = string("type", "Tipo do novo status") {
Activity.ActivityType.values().forEach {
choice(it.name, it.name)
}
}
val priority = long("priority", "Prioridade do status, de menor para maior (por padrão é melhor deixar 0, e 1 para substituir um status já existente)")
val startsAt = string("starts_at", "Quando o status ficará visível (horário GMT-3)")
val endsAt = string("ends_at", "Quando o status deixará de ser visível (horário GMT-3)")
val streamUrl = optionalString("stream_url", "URL da Stream, caso o tipo seja STREAMING")
}

private object UserBanRenamedResult : BanRenameResult()
override val options = Options()

override suspend fun executeHelper(context: ApplicationCommandContext, args: SlashCommandArguments) {
context.deferChannelMessage(false)

val text = args[options.text]
val type = args[options.type]
val priority = args[options.priority].toInt()
val startsAt = args[options.startsAt]
val endsAt = args[options.endsAt]
val streamUrl = args[options.streamUrl]

// Parse the string into a LocalDateTime object
val startsAtLocalDateTime = try {
LocalDateTime.parse(startsAt, formatter)
} catch (e: DateTimeParseException) {
context.reply(false) {
styled("Não foi possível parsear a data que você passou...")
}
return
}

// Convert LocalDateTime to Instant using UTC (or desired) time zone offset
val startsAtInstant = startsAtLocalDateTime.toInstant(zoneId.rules.getOffset(startsAtLocalDateTime))

// Parse the string into a LocalDateTime object
val endsAtLocalDateTime = try {
LocalDateTime.parse(startsAt, formatter)
} catch (e: DateTimeParseException) {
context.reply(false) {
styled("Não foi possível parsear a data que você passou...")
}
return
}

// Convert LocalDateTime to Instant using UTC (or desired) time zone offset
val endsAtInstant = endsAtLocalDateTime.toInstant(zoneId.rules.getOffset(endsAtLocalDateTime))

context.loritta.makeLorittaRPCRequest<LorittaDashboardRPCResponse.UpdateLorittaActivityResponse>(
LorittaDashboardRPCRequest.UpdateLorittaActivityRequest(
text,
type,
priority,
startsAtInstant.toKotlinInstant(),
endsAtInstant.toKotlinInstant(),
streamUrl
)
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,20 @@ class LorittaHelperConfig(
val secretKey: String,
val lorittaDatabase: DatabaseConfig? = null,
val helperDatabase: DatabaseConfig? = null,
val pantufaUrl: String? = null
val pantufaUrl: String? = null,
val lorittaApi: LorittaAPIConfig
) {
@Serializable
class DatabaseConfig constructor(
class DatabaseConfig(
val databaseName: String,
val address: String,
val username: String,
val password: String
)

@Serializable
class LorittaAPIConfig(
val url: String,
val token: String
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class DailyOnlyEcoCommandsCatcher(database: Database) : DailyCatcher<ReportOnlyE
}

override suspend fun catch(channel: Channel<ReportOnlyEcoCatcher>) {
val dailies = transaction(Connection.TRANSACTION_READ_UNCOMMITTED, 5, database) {
val dailies = transaction(Connection.TRANSACTION_READ_UNCOMMITTED, 5, db = database) {
Dailies.select {
Dailies.receivedAt greaterEq DailyCatcherManager.yesterdayAtMidnight() and (Dailies.receivedAt lessEq DailyCatcherManager.yesterdayBeforeDaySwitch())
}.toList()
Expand All @@ -52,7 +52,7 @@ class DailyOnlyEcoCommandsCatcher(database: Database) : DailyCatcher<ReportOnlyE
for ((chunkedIndex, chunkedDaily) in dailies.chunked(CHUNKED_EXECUTED_COMMAND_LOGS_COUNT).withIndex()) {
logger.info { "Doing bulk command stats... Current index: $chunkedIndex" }
val start = System.currentTimeMillis()
val commands = transaction(Connection.TRANSACTION_READ_UNCOMMITTED, 5, database) {
val commands = transaction(Connection.TRANSACTION_READ_UNCOMMITTED, 5, db = database) {
ExecutedCommandsLog.slice(ExecutedCommandsLog.command, ExecutedCommandsLog.userId, commandCountField)
.select {
ExecutedCommandsLog.sentAt greaterEq DailyCatcherManager.fourteenDaysAgo() and (
Expand Down

0 comments on commit fdd31ef

Please sign in to comment.