Skip to content

Commit

Permalink
Add online players in game notifications (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
imedvedko authored Oct 19, 2019
1 parent 3ae052e commit 9ba3783
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 56 deletions.
Original file line number Diff line number Diff line change
@@ -1,45 +1,51 @@
package com.imedvedev.minecraft.notification.bot.listener

import com.imedvedev.minecraft.notification.bot.messenger.Messenger
import fr.xephi.authme.api.v3.AuthMeApi
import fr.xephi.authme.events.LoginEvent
import fr.xephi.authme.events.LogoutEvent
import org.bukkit.ChatColor
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerQuitEvent
import java.util.logging.Level
import java.util.logging.Logger
import kotlin.collections.LinkedHashMap
import kotlin.math.absoluteValue

class NotificationEventListener(private val joinedMessage: String,
private val leftMessage: String,
private val onlineMessage: String,
private val chatColors: List<ChatColor>,
private val messenger: Messenger,
private val authMeApi: AuthMeApi,
private val onlinePlayers: () -> Iterable<Player>,
private val isAuthenticated: (Player) -> Boolean,
private val logger: Logger,
private val quarantineScheduler: (() -> Unit) -> Unit) : Listener {
private val onlinePlayers: MutableMap<String, Int> = LinkedHashMap()
private val quarantineScheduler: (() -> Unit) -> Unit,
private val pluginName: String,
private val pluginVersion: String) : Listener {
private val authenticatedPlayers: MutableMap<String, Int> = LinkedHashMap()

@EventHandler(priority = EventPriority.MONITOR)
fun onLogin(event: LoginEvent) {
event.player.takeIf(Player::isOnline)?.run {
if (onlinePlayers.put(name, entityId) == null) {
if (authenticatedPlayers.put(name, entityId) == null) {
sendMessage("$pluginName $pluginVersion")
logger.log(Level.INFO) { "$name joined the game. " +
"Server is sending notification" }
sendNotification(joinedMessage)
} else {
logger.log(Level.INFO) { "$name joined the game when was quarantined. " +
"Server is not sending notification" }
sendMessage(authenticatedPlayerNames())
}
}
}

@EventHandler(priority = EventPriority.MONITOR)
fun onLogout(event: LogoutEvent) {
event.player.takeIf(Player::isOnline)?.run {
onlinePlayers.remove(name)
authenticatedPlayers.remove(name)
logger.log(Level.INFO) { "$name left the game. " +
"Server is sending notification" }
sendNotification(leftMessage)
Expand All @@ -48,24 +54,35 @@ class NotificationEventListener(private val joinedMessage: String,

@EventHandler(priority = EventPriority.MONITOR)
fun onQuit(event: PlayerQuitEvent) {
event.player.takeIf(authMeApi::isAuthenticated)?.run {
event.player.takeIf(isAuthenticated)?.run {
logger.log(Level.INFO) { "$name has been quarantined" }
quarantineScheduler.invoke {
if (onlinePlayers.remove(name, entityId)) {
if (authenticatedPlayers.remove(name, entityId)) {
logger.log(Level.INFO) { "Quarantine has been finished. $name left the game. " +
"Server is sending notification" }
"Server is sending notification" }
sendNotification(leftMessage)
} else {
logger.log(Level.INFO) { "Quarantine has been finished. $name already joined the game again. " +
"Server is not sending notification" }
"Server is not sending notification" }
}
}
}
}

private fun Player.sendNotification(message: String) = messenger
.send("<b>$name $message</b>\n$onlineMessage: ${onlinePlayers.keys.map { "<i>${it}</i>" }}")
.forEach { job -> job.exceptionally { exception -> logger.log(Level.WARNING, exception) {
"Server can not send the notification: \"$message\""
} } }
private fun Player.sendNotification(message: String) {
messenger.send("<b>$name $message</b>\n$onlineMessage: ${authenticatedPlayers.keys.map { "<i>$it</i>" }}")
.forEach { job -> job.exceptionally { exception -> logger.log(Level.WARNING, exception) {
"Server can not send the notification: \"$message\""
} } }

authenticatedPlayerNames().let { authenticatedPlayerNames ->
onlinePlayers().filter(isAuthenticated)
.forEach { it.sendMessage(authenticatedPlayerNames) }
}
}

private fun authenticatedPlayerNames(): String = authenticatedPlayers.keys.map { name ->
name.toByteArray().reduce { first: Byte, second: Byte -> (first + second).toByte() }.toInt().absoluteValue
.let { "${chatColors[it % chatColors.size]}${ChatColor.stripColor(name)}${ChatColor.RESET}" }
}.let { "${ChatColor.GREEN}${ChatColor.stripColor(onlineMessage)}: ${ChatColor.RESET}$it" }
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,27 @@
package com.imedvedev.minecraft.notification.bot

import com.imedvedev.minecraft.notification.bot.injector.get
import com.imedvedev.minecraft.notification.bot.injector.module.notificationEventListenerModule
import com.imedvedev.minecraft.notification.bot.injector.module.proxyModule
import com.imedvedev.minecraft.notification.bot.injector.module.telegramMessengerModule
import com.imedvedev.minecraft.notification.bot.messenger.Messenger
import org.bukkit.plugin.Plugin
import org.bukkit.plugin.java.JavaPlugin
import org.koin.core.context.startKoin
import org.koin.dsl.module

class NotificationBotPlugin : JavaPlugin() {
override fun onEnable() = server.pluginManager.registerEvents(get(this), this)
override fun onEnable() {
val koin = startKoin { modules(listOf(
module(true) { single<Plugin> { this@NotificationBotPlugin } },
proxyModule,
telegramMessengerModule,
notificationEventListenerModule
)) }.koin

config.getConfigurationSection("message")!!.getString("started").let {
koin.get<Messenger>().send("<b>$it</b>\n${description.name}: ${description.version}")
}

server.pluginManager.registerEvents(koin.get(), this)
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,30 @@ package com.imedvedev.minecraft.notification.bot.injector.module

import com.imedvedev.minecraft.notification.bot.listener.NotificationEventListener
import fr.xephi.authme.api.v3.AuthMeApi
import org.bukkit.ChatColor
import org.bukkit.event.Listener
import org.bukkit.plugin.Plugin
import org.koin.dsl.module

val notificationEventListenerModule = module(true) {
single<Listener> {
get<Plugin>().let { plugin -> plugin.config.getConfigurationSection("message")!!.let { config ->
get<Plugin>().let { plugin -> plugin.config.let { config ->
val messageConfig = config.getConfigurationSection("message")!!
NotificationEventListener(
config.getString("joined")!!,
config.getString("left")!!,
config.getString("online")!!,
get(),
AuthMeApi.getInstance(),
plugin.logger,
config.getLong("leftMessageQuarantineInTicks").let<Long, (() -> Unit) -> Unit> { delay ->
{ task -> plugin.server.scheduler.runTaskLater(plugin, task, delay) }
}
joinedMessage = messageConfig.getString("joined")!!,
leftMessage = messageConfig.getString("left")!!,
onlineMessage = messageConfig.getString("online")!!,
chatColors = config.getStringList("nameColors").map(ChatColor::valueOf),
messenger = get(),
onlinePlayers = plugin.server::getOnlinePlayers,
isAuthenticated = AuthMeApi.getInstance()::isAuthenticated,
logger = plugin.logger,
quarantineScheduler = messageConfig.getLong("leftMessageQuarantineInTicks")
.let<Long, (() -> Unit) -> Unit> { delay ->
{ task -> plugin.server.scheduler.runTaskLater(plugin, task, delay) }
},
pluginName = plugin.description.name,
pluginVersion = plugin.description.version
)
} }
}
Expand Down
16 changes: 15 additions & 1 deletion modules/plugin/src/main/resources/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,21 @@ messenger.telegram:
token: ""
chats: [""]
message:
started: "Server has been started"
joined: "joined the game"
left: "left the game"
online: "Online players"
leftMessageQuarantineInTicks: 300
leftMessageQuarantineInTicks: 300
nameColors:
- DARK_GREEN
- DARK_AQUA
- DARK_RED
- DARK_PURPLE
- GOLD
- GRAY
- BLUE
- GREEN
- AQUA
- RED
- LIGHT_PURPLE
- YELLOW
6 changes: 0 additions & 6 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,6 @@
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.14.4-R0.1-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>net.md-5</groupId>
<artifactId>bungeecord-chat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>fr.xephi</groupId>
Expand Down

0 comments on commit 9ba3783

Please sign in to comment.