Skip to content

Commit

Permalink
Major refactor and migrate to MongoDB async driver
Browse files Browse the repository at this point in the history
  • Loading branch information
WinG4merBR committed Jan 24, 2025
1 parent 40394eb commit f3e439c
Show file tree
Hide file tree
Showing 23 changed files with 314 additions and 183 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import kotlinx.serialization.Serializable

@Serializable
data class ActivityUpdateRequest(
val name: String,
val type: Int,
val name: String = "uwu",
val type: Int = 0,
val url: String? = null,
val status: String? = "online",
)
10 changes: 5 additions & 5 deletions common/src/main/kotlin/net/cakeyfox/common/Constants.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,18 @@ object Constants {
const val SUPPORT_SERVER_ID = "768267522670723094"


fun getDefaultActivity(environment: String, clusterName: String?): String {
fun getDefaultActivity(activity: String, environment: String, clusterName: String?): String {
if (clusterName != null) {
return when(environment) {
"development" -> "https://youtu.be/0OIqlp2U9EQ | Cluster: $clusterName"
"production" -> "foxybot.win · /help | Cluster: $clusterName"
else -> "foxybot.win · /help | Cluster: $clusterName"
"production" -> "$activity | Cluster: $clusterName"
else -> "$activity | Cluster: $clusterName"
}
} else {
return when(environment) {
"development" -> "https://youtu.be/0OIqlp2U9EQ"
"production" -> "foxybot.win · /help"
else -> "foxybot.win · /help"
"production" -> activity
else -> activity
}
}
}
Expand Down
7 changes: 4 additions & 3 deletions foxy/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ dependencies {
implementation(libs.deviousjda)
implementation("club.minnced:jda-ktx:${Versions.JDA_KTX}")

// DB
implementation("org.mongodb:mongodb-driver-sync:${Versions.MONGODB}")
// MongoDB
implementation("org.mongodb:bson-kotlinx:5.3.0")
implementation("org.mongodb:mongodb-driver-kotlin-coroutine:5.3.0")

// Ktor
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
Expand All @@ -39,7 +40,7 @@ dependencies {
implementation("io.ktor:ktor-server-content-negotiation:${Versions.KTOR}")
implementation("io.ktor:ktor-server-auth:${Versions.KTOR}")


// ThreadFactoryBuilder
implementation("com.google.guava:guava:32.1.3-jre")

// Caching
Expand Down
15 changes: 10 additions & 5 deletions foxy/src/main/kotlin/net/cakeyfox/foxy/FoxyInstance.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import net.cakeyfox.foxy.command.component.FoxyComponentManager
import net.cakeyfox.foxy.listeners.GuildListener
import net.cakeyfox.foxy.listeners.InteractionsListener
import net.cakeyfox.foxy.listeners.MessageListener
import net.cakeyfox.foxy.utils.ActivityUpdater
import net.cakeyfox.foxy.utils.config.FoxyConfig
import net.cakeyfox.foxy.utils.FoxyUtils
import net.cakeyfox.foxy.utils.analytics.TopggStatsSender
Expand Down Expand Up @@ -46,18 +45,20 @@ class FoxyInstance(
lateinit var interactionManager: FoxyComponentManager
lateinit var httpClient: HttpClient
lateinit var selfUser: User

private lateinit var foxyInternalAPI: FoxyInternalAPI
private lateinit var topggStatsSender: TopggStatsSender
private lateinit var environment: String

private val activeJobs = ThreadUtils.activeJobs
private val currentClusterName = if (config.discord.clusters.size < 2) null else currentCluster.name
private val coroutineExecutor = ThreadUtils.createThreadPool("CoroutineExecutor [%d]")

val threadPoolManager = ThreadPoolManager()
val coroutineDispatcher = coroutineExecutor.asCoroutineDispatcher()

suspend fun start() {
val logger = KotlinLogging.logger(this::class.jvmName)
val activityUpdater = ActivityUpdater(this)
FoxyInternalAPI(this)

environment = config.environment
mongoClient = MongoDBClient()
Expand Down Expand Up @@ -88,10 +89,13 @@ class FoxyInstance(
MessageListener(this)
)
.setAutoReconnect(true)
.setStatus(OnlineStatus.ONLINE)
.setStatus(
OnlineStatus.fromKey(mongoClient.utils.bot.getBotSettings().status)
)
.setActivity(
Activity.customStatus(
Constants.getDefaultActivity(
mongoClient.utils.bot.getActivity(),
config.environment,
currentClusterName
)
Expand All @@ -115,6 +119,7 @@ class FoxyInstance(

selfUser = shardManager.shards.first().selfUser
topggStatsSender = TopggStatsSender(this)
foxyInternalAPI = FoxyInternalAPI(this)

Runtime.getRuntime().addShutdownHook(thread(false) {
try {
Expand All @@ -126,7 +131,7 @@ class FoxyInstance(
}
httpClient.close()
mongoClient.close()
activityUpdater.shutdown()
foxyInternalAPI.stop()

activeJobs.forEach {
logger.info { "Cancelling job $it" }
Expand Down
20 changes: 18 additions & 2 deletions foxy/src/main/kotlin/net/cakeyfox/foxy/FoxyLauncher.kt
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,25 @@ object FoxyLauncher {

val config = readConfigFile<FoxyConfig>(configFile)
val hostname = HostnameUtils.getHostname()
val currentCluster = config.discord.clusters.find { it.id == hostname }
val clusterId = if (config.discord.getClusterIdFromHostname) {
try {
// If the hostname is in the expected format, extract the ID after the "-"
hostname.split("-")[1].toInt()
} catch (e: IndexOutOfBoundsException) {
logger.error { "Invalid hostname ($hostname)! The hostname must contain '-' followed by a numeric ID (e.g., foxy-1)." }
exitProcess(1)
} catch (e: NumberFormatException) {
logger.error { "Invalid ID in hostname ($hostname)! The value after '-' must be a number (e.g., foxy-1)." }
exitProcess(1)
}

} else {
config.discord.replicaId
}

val currentCluster = config.discord.clusters.find { it.id == clusterId }
?: run {
logger.error { "Cluster $hostname not found in config file" }
logger.error { "Cluster $hostname (${clusterId}) not found in config file" }
exitProcess(1)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class FoxyComponentManager(
) = createButton(targetUser.idLong, style, emoji, label, builder, callback)

fun createLinkButton(
emoji: Emoji? = null,
emoji: String? = null,
label: String = "",
url: String,
builder: (ButtonBuilder).() -> (Unit) = {},
Expand All @@ -56,7 +56,7 @@ class FoxyComponentManager(
builder
)

fun createButton(
private fun createButton(
targetUserId: Long,
style: ButtonStyle,
emoji: String? = null,
Expand All @@ -83,8 +83,8 @@ class FoxyComponentManager(
callback.invoke(it)
}

fun linkButton(
emoji: Emoji? = null,
private fun linkButton(
emoji: String? = null,
label: String = "",
url: String,
builder: (ButtonBuilder).() -> (Unit) = {},
Expand All @@ -93,7 +93,7 @@ class FoxyComponentManager(
ButtonStyle.LINK,
url,
label,
emoji
Emoji.fromFormatted("<:emoji:$emoji")
).let {
ButtonBuilder(it).apply(builder).button
}
Expand All @@ -112,7 +112,7 @@ class FoxyComponentManager(
style,
ComponentId(buttonId).toString(),
label,
emoji?.let { foxy.shardManager.getEmojiById(it) }
emoji?.let { Emoji.fromFormatted("<:emoji:$emoji") }
).let {
ButtonBuilder(it).apply(builder).button
}
Expand Down Expand Up @@ -149,7 +149,7 @@ class FoxyComponentManager(
callback.invoke(context, strings)
}

fun stringSelectMenu(
private fun stringSelectMenu(
builder: (StringSelectMenu.Builder).() -> (Unit) = {},
callback: suspend (FoxyInteractionContext, List<String>) -> (Unit)
): StringSelectMenu {
Expand All @@ -160,7 +160,7 @@ class FoxyComponentManager(
.build()
}

fun modal(
private fun modal(
title: String,
builder: (ModalBuilder).() -> (Unit) = {},
callback: suspend (FoxyInteractionContext) -> (Unit)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ class DailyExecutor: FoxyCommandExecutor() {

actionRow(
context.foxy.interactionManager.createLinkButton(
context.foxy.shardManager.getEmojiById(FoxyEmotes.FoxyPetPet),
FoxyEmotes.FoxyPetPet,
context.locale["daily.embed.redeemDaily"],
Constants.DAILY
),

context.foxy.interactionManager.createLinkButton(
context.foxy.shardManager.getEmojiById(FoxyEmotes.FoxyDaily),
FoxyEmotes.FoxyDaily,
context.locale["daily.embed.buyMore"],
Constants.PREMIUM
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ class PingExecutor : FoxyCommandExecutor() {
val totalShards = context.jda.shardInfo.shardTotal
val minClusterShards = context.foxy.currentCluster.minShard
val maxClusterShards = context.foxy.currentCluster.maxShard
val currentClusterId = context.foxy.currentCluster.id
val currentClusterName = context.foxy.currentCluster.name

context.reply {
embed {
Expand All @@ -34,7 +36,8 @@ class PingExecutor : FoxyCommandExecutor() {

field {
name = pretty(FoxyEmotes.FoxyDrinkingCoffee, "Cluster:")
value = "`${context.foxy.currentCluster.name}` **(Shard ${minClusterShards}/${maxClusterShards})**"
value =
"Cluster $currentClusterId - `${currentClusterName}` **[$minClusterShards-$maxClusterShards]**"
inline = false
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ class AntiRaidModule(
val userId = event.user.id
val antiRaidSettings = guildInfo.antiRaidModule


timestamps.add(currentTimestamp)

if ((timestamps?.size ?: 0) > antiRaidSettings.newUsersThreshold) {
Expand Down
71 changes: 0 additions & 71 deletions foxy/src/main/kotlin/net/cakeyfox/foxy/utils/ActivityUpdater.kt

This file was deleted.

2 changes: 1 addition & 1 deletion foxy/src/main/kotlin/net/cakeyfox/foxy/utils/FoxyUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ class FoxyUtils(

actionRow(
foxy.interactionManager.createLinkButton(
context.jda.getEmojiById(FoxyEmotes.FoxyCupcake),
FoxyEmotes.FoxyCupcake,
context.locale["ban.appealButton"],
Constants.UNBAN_FORM_URL
)
Expand Down
Loading

0 comments on commit f3e439c

Please sign in to comment.