Skip to content

Commit

Permalink
Merge pull request #220 from MLGPenguin/counting
Browse files Browse the repository at this point in the history
Counting Improvements & Leaderboard
  • Loading branch information
Dawsson authored Jan 27, 2024
2 parents e1072ba + 4894ed3 commit a641bfe
Show file tree
Hide file tree
Showing 7 changed files with 137 additions and 44 deletions.
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ dependencies {
implementation("gg.flyte:neptune:2.4")
implementation("org.mongodb:mongodb-driver-sync:4.9.0")
implementation("io.github.cdimascio:dotenv-kotlin:6.4.1")
implementation(files("libs/Math-Evaluator-1.2.0.jar"))
implementation(files("libs/Math-Evaluator-1.2.2.jar"))
}

application {
Expand Down
Binary file removed libs/Math-Evaluator-1.2.0.jar
Binary file not shown.
Binary file added libs/Math-Evaluator-1.2.2.jar
Binary file not shown.
3 changes: 3 additions & 0 deletions src/main/kotlin/com/learnspigot/bot/Bot.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.learnspigot.bot

import com.learnspigot.bot.counting.CountingRegistry
import com.learnspigot.bot.help.search.HelpPostRegistry
import com.learnspigot.bot.intellijkey.IJUltimateKeyRegistry
import com.learnspigot.bot.knowledgebase.KnowledgebasePostRegistry
Expand Down Expand Up @@ -88,6 +89,8 @@ class Bot {
return HelpPostRegistry()
}

@Instantiate fun countingRegistry(): CountingRegistry = CountingRegistry(profileRegistry)

companion object {
lateinit var jda: JDA
}
Expand Down
57 changes: 57 additions & 0 deletions src/main/kotlin/com/learnspigot/bot/counting/CountingCommand.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.learnspigot.bot.counting

import com.learnspigot.bot.profile.ProfileRegistry
import com.learnspigot.bot.util.embed
import gg.flyte.neptune.annotation.Command
import gg.flyte.neptune.annotation.Description
import gg.flyte.neptune.annotation.Inject
import gg.flyte.neptune.annotation.Optional
import net.dv8tion.jda.api.entities.User
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent

class CountingCommand {

@Inject private lateinit var profileRegistry: ProfileRegistry
@Inject private lateinit var countingRegistry: CountingRegistry

@Command(name = "countingstats", description = "View counting statistics")
fun onCountingCommand(
event: SlashCommandInteractionEvent,
@Description("User's stats to view") @Optional user: User?
) {
if (user == null) { // Server stats
event.replyEmbeds(
embed()
.setTitle("Server counting statistics")
.setDescription("""
- Current Count: ${countingRegistry.currentCount}
- Total Counts: ${countingRegistry.serverTotalCounts}
- Highest Count: ${countingRegistry.topServerCount}
""".trimIndent())
.addField(
"Top 5 counters",
countingRegistry.leaderboard.take(5).joinToString("") {
val profile = profileRegistry.findById(it)!!
if (profile.tag == null || profile.totalCounts == 0) return@joinToString ""
"\n- ${profile.tag}: ${profile.totalCounts}"
},
false
)
.build()
).setEphemeral(true).queue()
} else { // Individual Stats
val profile = profileRegistry.findByUser(user)
event.replyEmbeds(
embed()
.setTitle(user.name + "'s counting statistics")
.setDescription("""
- Total Counts: ${profile.totalCounts}
- Highest Count: ${profile.highestCount}
- Mistakes: ${profile.countingFuckUps}
""".trimIndent())
.build()
).setEphemeral(true).queue()
}

}
}
60 changes: 17 additions & 43 deletions src/main/kotlin/com/learnspigot/bot/counting/CountingListener.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,70 +2,38 @@ package com.learnspigot.bot.counting

import com.learnspigot.bot.Environment
import com.learnspigot.bot.Server
import com.learnspigot.bot.profile.ProfileRegistry
import com.learnspigot.bot.util.Mongo
import com.mongodb.client.model.Filters
import gg.flyte.neptune.annotation.Inject
import me.superpenguin.mathevaluator.Evaluator
import net.dv8tion.jda.api.entities.Message
import net.dv8tion.jda.api.entities.User
import net.dv8tion.jda.api.entities.channel.Channel
import net.dv8tion.jda.api.entities.emoji.Emoji
import net.dv8tion.jda.api.events.message.MessageDeleteEvent
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
import net.dv8tion.jda.api.events.message.MessageUpdateEvent
import net.dv8tion.jda.api.hooks.ListenerAdapter
import org.bson.Document

class CountingListener: ListenerAdapter() {

@Inject private lateinit var profileRegistry: ProfileRegistry
@Inject private lateinit var countingRegistry: CountingRegistry

private val mongoCollection = Mongo.countingCollection

var topServerCount: Int = 0
var serverTotalCounts: Int = 0
var currentCount = 0
val currentCount: Int get() = countingRegistry.currentCount

var lastCount: Message? = null

init {
val document = mongoCollection.find().first()
if (document == null) {
val newDoc = Document()
newDoc["highestCount"] = 0
newDoc["currentCount"] = 0
newDoc["serverTotalCounts"] = 0
mongoCollection.insertOne(newDoc)
} else {
topServerCount = document.getInteger("highestCount", 0)
currentCount = document.getInteger("currentCount", 0)
serverTotalCounts = document.getInteger("serverTotalCounts", 0)
}
}

fun incrementCount(user: User) {
currentCount++
serverTotalCounts++
profileRegistry.findByUser(user).incrementCount(currentCount)
if (currentCount > topServerCount) topServerCount = currentCount
val newDoc = mongoCollection.find().first()!!
newDoc["highestCount"] = topServerCount
newDoc["currentCount"] = currentCount
newDoc["serverTotalCounts"] = serverTotalCounts
mongoCollection.replaceOne(Filters.eq("_id", newDoc.getObjectId("_id")), newDoc)
}

fun fuckedUp(user: User) {
currentCount = 0
lastCount = null
profileRegistry.findByUser(user).fuckedUpCounting()
countingRegistry.fuckedUp(user)
}

private fun Channel.isCounting() = id == Environment.get("COUNTING_CHANNEL_ID")
private fun Message.millisSinceLastCount() = timeCreated.toInstant().toEpochMilli() - (lastCount?.timeCreated?.toInstant()?.toEpochMilli() ?: 0)

private val thinking = Emoji.fromUnicode("🤔")

override fun onMessageReceived(event: MessageReceivedEvent) {
if (event.author.isBot || !event.isFromGuild || !event.channel.isCounting() || event.guild.id != Server.guildId) return
if (event.message.embeds.isNotEmpty()) return
if (event.message.attachments.isNotEmpty()) return

val msg = event.message.contentRaw
val userId = event.author.id
Expand All @@ -74,17 +42,23 @@ class CountingListener: ListenerAdapter() {
if (evaluated == currentCount + 1) {
if (userId.equals(lastCount?.author?.id, true)) return run {
event.message.addReaction(Server.downvoteEmoji)
event.message.reply("You can't count twice in a row, let someone else join in!").queue()
event.message.reply("You can't count twice in a row, let someone else join in! ( The count has been reset to 1 )").queue()
fuckedUp(event.author)
}
lastCount = event.message
event.message.addReaction(Server.upvoteEmoji).queue()
incrementCount(event.author)
countingRegistry.incrementCount(event.author)
} else {
if (evaluated == currentCount && event.message.millisSinceLastCount() < 600) {
// ( 600ms delay ) - Arbitrary value based on superficial testing
event.message.addReaction(thinking).queue()
event.message.reply("I'll let this one slide").queue()
return
}
val next = currentCount + 1
fuckedUp(event.author)
event.message.addReaction(Server.downvoteEmoji).queue()
event.message.reply("The next number was $next").queue()
event.message.reply("The next number was $next, not $evaluated").queue()
}
}
}
Expand Down
59 changes: 59 additions & 0 deletions src/main/kotlin/com/learnspigot/bot/counting/CountingRegistry.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.learnspigot.bot.counting

import com.learnspigot.bot.profile.ProfileRegistry
import com.learnspigot.bot.util.Mongo
import com.mongodb.client.model.Filters
import net.dv8tion.jda.api.entities.User
import org.bson.Document
import java.util.*

class CountingRegistry(private val profileRegistry: ProfileRegistry) {
private val mongoCollection = Mongo.countingCollection

var topServerCount: Int = 0
var serverTotalCounts: Int = 0
var currentCount = 0

// Queue of User Ids
val leaderboard: PriorityQueue<String> = PriorityQueue { a, b ->
profileRegistry.findById(b)!!.totalCounts.compareTo(profileRegistry.findById(a)!!.totalCounts)
}

init {
val document = mongoCollection.find().first()
if (document == null) {
val newDoc = Document()
newDoc["highestCount"] = 0
newDoc["currentCount"] = 0
newDoc["serverTotalCounts"] = 0
mongoCollection.insertOne(newDoc)
} else {
topServerCount = document.getInteger("highestCount", 0)
currentCount = document.getInteger("currentCount", 0)
serverTotalCounts = document.getInteger("serverTotalCounts", 0)
}

profileRegistry.profileCache.values.forEach { leaderboard.add(it.id) }
}

private fun <T> PriorityQueue<T>.recalculate(ele: T) = remove(ele).also { add(ele) }

fun incrementCount(user: User) {
currentCount++
serverTotalCounts++
if (currentCount > topServerCount) topServerCount = currentCount
leaderboard.recalculate(user.id)
profileRegistry.findByUser(user).incrementCount(currentCount)
val newDoc = mongoCollection.find().first()!!
newDoc["highestCount"] = topServerCount
newDoc["currentCount"] = currentCount
newDoc["serverTotalCounts"] = serverTotalCounts
mongoCollection.replaceOne(Filters.eq("_id", newDoc.getObjectId("_id")), newDoc)
}

fun fuckedUp(user: User) {
currentCount = 0
profileRegistry.findByUser(user).fuckedUpCounting()
}

}

0 comments on commit a641bfe

Please sign in to comment.