Skip to content

Commit

Permalink
Some slight changes
Browse files Browse the repository at this point in the history
  • Loading branch information
bombies committed Jan 11, 2024
1 parent 083899e commit a697480
Show file tree
Hide file tree
Showing 10 changed files with 78 additions and 25 deletions.
6 changes: 4 additions & 2 deletions src/main/kotlin/main/audiohandlers/GuildMusicManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@ class GuildMusicManager(val guild: Guild) {
queueHandler.clearSavedQueue()
queueHandler.clearPreviousTracks()

link.createOrUpdatePlayer()
.setFilters(Filters())
if (link.getPlayer().block() != null)
link.updatePlayer {
it.setFilters(Filters())
}.subscribe()

queueHandler.trackRepeating = false
queueHandler.queueRepeating = false
Expand Down
3 changes: 2 additions & 1 deletion src/main/kotlin/main/audiohandlers/RobertifyAudioManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,8 @@ object RobertifyAudioManager {
addToBeginning = addToBeginning,
announceMsg = announceMessage,
botMsg = botMessage,
loadPlaylistShuffled = shuffled
loadPlaylistShuffled = shuffled,
_announcementChannel = botMessage?.channel?.asGuildMessageChannel()
).loadItem()
}

Expand Down
16 changes: 9 additions & 7 deletions src/main/kotlin/main/audiohandlers/TrackScheduler.kt
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import org.slf4j.LoggerFactory
import java.io.InputStream
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
import kotlin.math.log
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
Expand All @@ -50,7 +50,7 @@ class TrackScheduler(private val guild: Guild, val link: Link) {
companion object {
private val logger = LoggerFactory.getLogger(Companion::class.java)
private val audioManager = RobertifyAudioManager
private var EVENTS_SUBSCRIBED = false
private var EVENTS_SUBSCRIBED = AtomicBoolean(false)
}

private val requesters = ArrayList<Requester>()
Expand All @@ -66,7 +66,9 @@ class TrackScheduler(private val guild: Guild, val link: Link) {
}

fun playTrack(track: Track) {
this.link.createOrUpdatePlayer().setTrack(track)
this.link
.createOrUpdatePlayer()
.setTrack(track)
.subscribe()
}

Expand Down Expand Up @@ -119,15 +121,15 @@ class TrackScheduler(private val guild: Guild, val link: Link) {
init {
logger.debug("Initializing a new TrackScheduler for ${guild.name}...")

if (!EVENTS_SUBSCRIBED) {
logger.debug("Subscribing to scheduler events...")
if (!EVENTS_SUBSCRIBED.get()) {
logger.info("Subscribing to scheduler events...")
val lavalink = Robertify.lavalink
lavalink.on<TrackStartEvent>().subscribe { event -> onTrackStart(event) }
lavalink.on<TrackEndEvent>().subscribe { event -> onTrackEnd(event) }
lavalink.on<TrackStuckEvent>().subscribe { event -> onTrackStuck(event) }
lavalink.on<TrackExceptionEvent>().subscribe { event -> onTrackException(event) }
EVENTS_SUBSCRIBED = true
logger.debug("Subscribed to scheduler events")
EVENTS_SUBSCRIBED.set(true)
logger.info("Subscribed to scheduler events")
} else logger.debug("Already subscribed scheduler to events")
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ class UpdateCommand : AbstractSlashCommand(
}
}

private suspend inline fun handleGenericUpdate(
private inline fun handleGenericUpdate(
event: SlashCommandInteractionEvent,
successMsg: String,
errorMsg: String,
Expand Down
11 changes: 8 additions & 3 deletions src/main/kotlin/main/events/VoiceChannelEvents.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main.events

import dev.minn.jda.ktx.util.SLF4J
import main.audiohandlers.GuildMusicManager
import main.audiohandlers.RobertifyAudioManager
import main.main.Robertify
import main.utils.json.guildconfig.GuildConfig
Expand All @@ -13,17 +14,21 @@ class VoiceChannelEvents : AbstractEventController() {

private val onGuildVoiceUpdate =
onEvent<GuildVoiceUpdateEvent> { event ->
val guild = event.guild
val self = guild.selfMember
if (event.member.id != self.id)
return@onEvent

try {
val guild = event.guild
val channelLeft = event.channelLeft
val channelJoined = event.channelJoined
val self = guild.selfMember
val selfVoiceState = self.voiceState!!
val guildMusicManager = RobertifyAudioManager[guild]

// If the bot has left voice channels entirely
if (event.member.id == self.id && (channelLeft != null && channelJoined == null))
if (channelLeft != null && channelJoined == null) {
return@onEvent guildMusicManager.clear()
}

if (!selfVoiceState.inAudioChannel())
return@onEvent
Expand Down
14 changes: 12 additions & 2 deletions src/main/kotlin/main/main/Robertify.kt
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,18 @@ object Robertify {
private fun ShardManager.handleGuildReady() = listener<GuildReadyEvent> { event ->
val guild = event.guild
loadNeededSlashCommands(guild)
rescheduleUnbans(guild)
RemindersConfig(guild).scheduleReminders()

try {
rescheduleUnbans(guild)
} catch (e: Exception) {
logger.error("Failed to reschedule unbans for guild ${guild.id}", e)
}

try {
RemindersConfig(guild).scheduleReminders()
} catch (e: Exception) {
logger.error("Failed to schedule reminders for guild ${guild.id}", e)
}
// GuildResumeManager(guild).loadTracks()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import main.constants.RobertifyPermission
import main.utils.GeneralUtils
import main.utils.GeneralUtils.isDiscordId
Expand Down Expand Up @@ -51,7 +52,8 @@ class GuildRedisCache private constructor() : DatabaseRedisCache("ROBERTIFY_GUIL
}

fun getGuildModel(gid: String): GuildDatabaseModel? {
if (!guildHasInfo(gid)) loadGuild(gid)
if (!guildHasInfo(gid))
loadGuild(gid)
val guildInfo = get(gid) ?: return null
val json = correctGuildObj(JSONObject(guildInfo)).toString()
return Json.decodeFromString(json)
Expand Down Expand Up @@ -90,6 +92,19 @@ class GuildRedisCache private constructor() : DatabaseRedisCache("ROBERTIFY_GUIL
.put(GuildDB.Field.RESTRICTED_CHANNELS_VOICE.toString(), rvc)
)
}

if (!obj.has(GuildDB.Field.PERMISSIONS_OBJECT.toString())) {
obj.put(GuildDB.Field.PERMISSIONS_OBJECT.toString(), PermissionsModel(
emptyList<Long>().toMutableList(),
emptyList<Long>().toMutableList(),
emptyList<Long>().toMutableList(),
emptyList<Long>().toMutableList(),
emptyList<Long>().toMutableList(),
emptyList<Long>().toMutableList(),
JsonObject(emptyMap()),
).toJsonObject())
}

val permissionsObj = obj.getJSONObject(GuildDB.Field.PERMISSIONS_OBJECT.toString())

for (code in RobertifyPermission.codes) {
Expand Down Expand Up @@ -257,20 +272,20 @@ class GuildRedisCache private constructor() : DatabaseRedisCache("ROBERTIFY_GUIL
*/
private fun loadGuild(gid: String, attempt: Int) {
var scopedAttempt = attempt
logger.info("Attempting to load guild with ID: {}", gid)
logger.debug("Attempting to load guild with ID: {}", gid)
try {
val guildJSON: String? = mongoDB.getDocument(GuildDB.Field.GUILD_ID.toString(), gid.toLong())
if (guildJSON != null) {
val guildObj = readyGuildObjForRedis(JSONObject(guildJSON))
setex(gid, 3600, guildObj)
logger.info("Loaded guild with ID: {}", gid)
logger.debug("Loaded guild with ID: {}", gid)
}
} catch (e: Exception) {
when (e) {
is NullPointerException,
is NoSuchElementException -> {
if (scopedAttempt == 2) return
logger.info(
logger.debug(
"Guild with ID {} didn't exist in the database. Attempting to add and reload.",
gid
)
Expand Down
24 changes: 21 additions & 3 deletions src/main/kotlin/main/utils/json/logs/LogUtilsKt.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@ class LogUtilsKt(private val guild: Guild) {
if (!config.channelIsSet()) return
if (!TogglesConfig(guild).getLogToggle(type)) return
val channel = config.getChannel()
channel!!.sendMessageEmbeds(

if (channel == null) {
config.removeChannel()
return;
}

channel.sendMessageEmbeds(
EmbedBuilder()
.setTitle(type.emoji.formatted + " " + type.title)
.setColor(type.color)
Expand All @@ -33,7 +39,13 @@ class LogUtilsKt(private val guild: Guild) {
if (!TogglesConfig(guild).getLogToggle(type)) return
val localeManager = LocaleManager[guild]
val channel = config.getChannel()
channel!!.sendMessageEmbeds(

if (channel == null) {
config.removeChannel()
return;
}

channel.sendMessageEmbeds(
EmbedBuilder()
.setTitle(type.emoji.formatted + " " + type.title)
.setColor(type.color)
Expand All @@ -49,8 +61,14 @@ class LogUtilsKt(private val guild: Guild) {
if (!TogglesConfig(guild).getLogToggle(type)) return
val localeManager = LocaleManager[guild]
val channel = config.getChannel()

if (channel == null) {
config.removeChannel()
return;
}

try {
channel!!.sendMessageEmbeds(
channel.sendMessageEmbeds(
EmbedBuilder()
.setTitle(type.emoji.formatted + " " + type.title)
.setColor(type.color)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ class RemindersConfig(private val guild: Guild) : AbstractGuildConfig(guild) {
getUser(uid) != null

fun scheduleReminders() {
logger.debug("Attempting to schedule guild reminders for ${guild.name}")
logger.debug("Attempting to schedule guild reminders for ${guild.name} (${guild.id})")
val scheduler = ReminderScheduler(guild)

if (!guildHasReminders()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ class RequestChannelConfig(private val guild: Guild, private val shardManager: S
val musicManager = RobertifyAudioManager[guild]

musicManager.usePlayer { audioPlayer ->
val playingTrack = audioPlayer?.track
val playingTrack = audioPlayer.track
val queueHandler = musicManager.scheduler.queueHandler
val queueAsList = ArrayList(queueHandler.contents)

Expand Down

0 comments on commit a697480

Please sign in to comment.