Skip to content

Commit

Permalink
Bump deps and add stats command
Browse files Browse the repository at this point in the history
  • Loading branch information
ToxicMushroom committed Jan 25, 2024
1 parent 61ac238 commit 74db9ca
Show file tree
Hide file tree
Showing 5 changed files with 130 additions and 41 deletions.
6 changes: 3 additions & 3 deletions bot/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ val kotlinX = "1.7.3" // https://mvnrepository.com/artifact/org.jetbrains.kotlin
val kotlin = "1.9.21"
val scrimage = "4.1.0"

val jda = "5.0.0-beta.18"
val kordEx = "1.6.4-SNAPSHOT"
val kordKommons = "0.0.12-SNAPSHOT"
val jda = "5.0.0-beta.20"
val kordEx = "1.6.6-SNAPSHOT"
val kordKommons = "0.0.13-SNAPSHOT"
val kandy_version = "0.5.0"
dependencies {
implementation("net.dv8tion:JDA:$jda")
Expand Down
4 changes: 4 additions & 0 deletions bot/src/main/kotlin/me/melijn/bot/Melijn.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import com.kotlindiscord.kord.extensions.builders.ExtensibleBotBuilder
import com.kotlindiscord.kord.extensions.koin.KordExContext
import com.kotlindiscord.kord.extensions.usagelimits.ratelimits.DefaultRateLimiter
import com.kotlindiscord.kord.extensions.utils.getKoin
import com.kotlindiscord.kord.extensions.utils.scheduling.TaskConfig
import com.zaxxer.hikari.pool.HikariPool.PoolInitializationException
import dev.minn.jda.ktx.jdabuilder.injectKTX
import dev.schlaubi.lavakord.LavaKord
Expand Down Expand Up @@ -36,6 +37,7 @@ import net.dv8tion.jda.api.utils.cache.CacheFlag
import org.koin.dsl.bind
import org.koin.dsl.module
import java.net.InetAddress
import java.util.concurrent.Executors
import javax.imageio.ImageIO
import kotlin.system.exitProcess

Expand Down Expand Up @@ -71,6 +73,8 @@ object Melijn {
kord {
setShardsTotal(PodInfo.shardCount)
setShards(PodInfo.shardList)
setEventPool(Executors.newVirtualThreadPerTaskExecutor())
setCallbackPool(Executors.newVirtualThreadPerTaskExecutor())
enableCache(CacheFlag.VOICE_STATE, CacheFlag.ACTIVITY, CacheFlag.EMOJI)
setMemberCachePolicy(MemberCachePolicy.lru(1000).unloadUnless(MemberCachePolicy.VOICE))
injectKTX()
Expand Down
69 changes: 31 additions & 38 deletions bot/src/main/kotlin/me/melijn/bot/commands/DevExtension.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,13 @@ import com.kotlindiscord.kord.extensions.extensions.Extension
import com.kotlindiscord.kord.extensions.extensions.chatCommand
import com.kotlindiscord.kord.extensions.extensions.publicSlashCommand
import com.kotlindiscord.kord.extensions.types.respond
import com.sun.management.OperatingSystemMXBean
import dev.minn.jda.ktx.coroutines.await
import dev.minn.jda.ktx.generics.getChannel
import dev.minn.jda.ktx.messages.InlineEmbed
import me.melijn.apkordex.command.KordExtension
import me.melijn.bot.utils.JDAUtil.createMessage
import me.melijn.bot.utils.JvmUsage
import me.melijn.bot.utils.KordExUtils.bail
import me.melijn.bot.utils.KordExUtils.guildChatCommand
import me.melijn.bot.utils.KordExUtils.respond
Expand All @@ -23,10 +26,16 @@ import me.melijn.bot.web.api.WebManager
import me.melijn.kordkommons.utils.StringUtils
import net.dv8tion.jda.api.entities.Activity
import net.dv8tion.jda.api.entities.RichPresence
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel
import net.dv8tion.jda.api.entities.channel.middleman.GuildMessageChannel
import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel
import net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
import net.dv8tion.jda.internal.entities.channel.mixin.middleman.MessageChannelMixin
import org.koin.core.component.inject
import org.springframework.boot.ansi.AnsiColor
import java.lang.management.ManagementFactory
import java.text.DecimalFormat

@KordExtension
class DevExtension : Extension() {
Expand All @@ -48,52 +57,36 @@ class DevExtension : Extension() {
}
}
}

chatCommand {
name = "stats"

action {
val bean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean::class.java)
val (totalMem, usedMem, totalJVMMem, usedJVMMem) = JvmUsage.current(bean)
val blue = StringsUtil.ansiFormat(AnsiColor.BLUE)
val reset = StringsUtil.ansiFormat(AnsiColor.DEFAULT)
respond {
content = """```ANSI
|${blue}Memory usage${reset}: ${usedMem}/${totalMem} MB
|${blue}JVM Mem usage${reset}: $usedJVMMem/$totalJVMMem MB
|${blue}Threads${reset}: ${Thread.activeCount()}/${Thread.getAllStackTraces().size}
|${blue}CPU Load${reset}: ${DecimalFormat("###.###%").format(bean.processCpuLoad)}
|${blue}Cores${reset}: ${bean.availableProcessors}
|```""".trimMargin()
}
}
}
publicSlashCommand {
name = "test"
description = "test"

action {
val webManager by inject<WebManager>()

respond {
content = "blub"
}
}
}
// publicSlashCommand {
// name = "testsub"
// description = "test"
// publicSubCommand {
// name= "test"
// description = "testing"
// action {
// respond {
// val names = getNames()
//
// content = "called `${names.joinToString(" ")}`"
// }
// }
// }
// }
// publicSlashCommand {
// name = "testsubsub"
// description = "test"
// group("sub1") {
// description = "sin1"
//
// publicSubCommand {
// name= "test"
// description = "testing"
// action {
// respond {
// val names = getNames()
//
// content = "called `${names.joinToString(" ")}`"
// }
// }
// }
// }
// }

guildChatCommand(::PresenceArgs) {
name = "presence"
Expand Down Expand Up @@ -132,9 +125,9 @@ class DevExtension : Extension() {
action {
val linkArg = arguments.messageLink.parsed
val message = if (linkArg != null) {
val parts = linkArg.split("/").takeLast(3).map { it }
val parts = linkArg.split("/").takeLast(3)
val guild = shardManager.getGuildById(parts[0])
val channel = guild?.getChannelById(MessageChannel::class.java, parts[1])
val channel = guild?.getChannel<GuildMessageChannel>(parts[1])
if (channel == null) {
this.channel.createMessage("that link is veeery stinky")
return@action
Expand Down
27 changes: 27 additions & 0 deletions bot/src/main/kotlin/me/melijn/bot/utils/JvmUsage.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package me.melijn.bot.utils

import com.sun.management.OperatingSystemMXBean
import java.lang.management.ManagementFactory

data class JvmUsage(val totalMem: Long, val usedMem: Long, val totalJVMMem: Long, val usedJVMMem: Long) {

companion object {
fun current(bean: OperatingSystemMXBean): JvmUsage {
val totalMem: Long
val usedMem: Long
if (SystemUtil.isUnix) {
totalMem = SystemUtil.getTotalMBUnixRam()
val available = SystemUtil.getAvailableMBUnixRam()
usedMem = totalMem - available
} else {
totalMem = bean.totalMemorySize shr 20
usedMem = totalMem - (bean.freeSwapSpaceSize shr 20)
}

val totalJVMMem = ManagementFactory.getMemoryMXBean().heapMemoryUsage.max shr 20
val usedJVMMem = ManagementFactory.getMemoryMXBean().heapMemoryUsage.used shr 20

return JvmUsage(totalMem, usedMem, totalJVMMem, usedJVMMem)
}
}
}
65 changes: 65 additions & 0 deletions bot/src/main/kotlin/me/melijn/bot/utils/SystemUtil.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package me.melijn.bot.utils

import java.io.File
import java.util.regex.Pattern

object SystemUtil {

val isUnix: Boolean = os == OS.UNIX

// 11105353.49 239988480.98
val linuxUptimePattern: Pattern = Pattern.compile("([0-9]+)(?:\\.[0-9]+)? [0-9]+(?:\\.[0-9]+)?")

val linuxMemTotalPattern: Pattern = Pattern.compile("MemTotal:\\s+([0-9]+) kB")
val linuxMemAvailPattern: Pattern = Pattern.compile("MemAvailable:\\s+([0-9]+) kB")

val os: OS
get() {
val s = System.getProperty("os.name").lowercase()
return when {
s.contains("mac") || s.contains("nix") || s.contains("nux") || s.contains("aix") -> OS.UNIX
else -> OS.OTHER
}
}

enum class OS {
UNIX, OTHER
}

fun getSystemUptime(): Long {
return try {
when (os) {
OS.UNIX -> getUnixUptime()
OS.OTHER -> -1
}
} catch (e: Exception) {
-1
}
}

fun getUnixUptime(): Long {
val uptimeStr = File("/proc/uptime").readText()
val matcher = linuxUptimePattern.matcher(uptimeStr)

if (!matcher.find()) return -1 // Extract ints out of groups
return matcher.group(1).toLong()
}

fun getTotalMBUnixRam(): Long = File("/proc/meminfo").readLines().firstNotNullOf { line ->
val matcher = linuxMemTotalPattern.matcher(line)

if (!matcher.find()) return@firstNotNullOf null
val group = matcher.group(1)
group.toLong() / 1024
}


fun getAvailableMBUnixRam(): Long = File("/proc/meminfo").readLines().firstNotNullOf { line ->
val matcher = linuxMemAvailPattern.matcher(line)

if (!matcher.find()) return@firstNotNullOf null
val group = matcher.group(1)
group.toLong() / 1024
}

}

0 comments on commit 74db9ca

Please sign in to comment.