@@ -12,6 +12,8 @@ import discord4j.core.event.domain.VoiceStateUpdateEvent
1212import reactor.core.Disposable
1313import reactor.core.Disposables
1414import reactor.core.publisher.Mono
15+ import java.util.concurrent.ConcurrentHashMap
16+ import java.util.concurrent.atomic.AtomicReference
1517import kotlin.jvm.optionals.getOrNull
1618
1719/* *
@@ -24,12 +26,21 @@ import kotlin.jvm.optionals.getOrNull
2426 */
2527@JvmName(" install" )
2628fun GatewayDiscordClient.installVoiceHandler (lavalink : LavalinkClient ): Disposable .Composite {
29+ // guild_id -> channel_id
30+ val channelIdCache = ConcurrentHashMap <Long , String >()
31+
2732 val voiceStateUpdate = on(VoiceStateUpdateEvent ::class .java) { event ->
2833 val update = event.current
2934 if (update.userId != update.client.selfId) return @on Mono .empty()
3035 val channel = update.channelId.getOrNull()
31- val link = lavalink.getLinkIfCached(update.guildId.asLong()) ? : return @on Mono .empty()
32- val player = link.node.playerCache[update.guildId.asLong()] ? : return @on Mono .empty()
36+ val guildId = update.guildId.asLong()
37+
38+ channel?.let { channelSnowflake ->
39+ channelIdCache[guildId] = channelSnowflake.asString()
40+ }
41+
42+ val link = lavalink.getLinkIfCached(guildId) ? : return @on Mono .empty()
43+ val player = link.node.playerCache[guildId] ? : return @on Mono .empty()
3344 val playerState = player.state
3445
3546 if (channel == null && playerState.connected) {
@@ -42,15 +53,16 @@ fun GatewayDiscordClient.installVoiceHandler(lavalink: LavalinkClient): Disposab
4253 }.subscribe()
4354
4455 val voiceServerUpdate = on(VoiceServerUpdateEvent ::class .java) { update ->
56+ val guildId = update.guildId.asLong()
4557 val state = VoiceState (
4658 update.token,
4759 update.endpoint!! ,
4860 getGatewayClient(update.shardInfo.index).get().sessionId,
49- null // TODO: find where to get the channel id from
61+ channelIdCache.remove(guildId) // TODO: Test if this works, is the order of events correct?
5062 )
5163
5264 val region = VoiceRegion .fromEndpoint(update.endpoint!! )
53- val link = lavalink.getOrCreateLink(update. guildId.asLong() , region)
65+ val link = lavalink.getOrCreateLink(guildId, region)
5466
5567 link.onVoiceServerUpdate(state)
5668 Mono .empty<Unit >()
0 commit comments