Compare commits

...

12 Commits

Author SHA1 Message Date
dalbodeule
77eecaca34
[hotfix] token claim fixed. (2x) 2025-06-04 16:27:32 +09:00
dalbodeule
90230c4691
[hotfix] token claim fixed. 2025-06-04 16:18:02 +09:00
dalbodeule
b2f449bf65
[hotfix] ChzzkClient.refreshAccessToken added. 2025-06-04 15:48:28 +09:00
dalbodeule
5e3a350e15
Merge branch 'develop'
# Conflicts:
#	chatbot/src/main/kotlin/space/mori/chzzk_bot/chatbot/chzzk/ChzzkHandler.kt
#	chatbot/src/main/kotlin/space/mori/chzzk_bot/chatbot/utils/accessTokenRefresh.kt
2025-06-04 15:46:43 +09:00
dalbodeule
8a0a507e5b
[feature] some logic fixed. 2025-06-04 15:42:31 +09:00
dalbodeule
1c4b818a85
Revert "Merge pull request #133 from dalbodeule/develop"
This reverts commit 83b5eaf34540d854382f0d0f00239529a78380a4, reversing
changes made to a99f3b342a73722d23e0b7328d08f68083b94b9e.
2025-05-27 13:18:52 +09:00
JinU Choi
83b5eaf345
Merge pull request #133 from dalbodeule/develop
[feature] accessToken refresh logic fix.
2025-05-27 13:13:24 +09:00
dalbodeule
b0be81df20
[feature] accessToken refresh logic fix. 2025-05-27 13:11:17 +09:00
JinU Choi
a99f3b342a
Merge pull request #132 from dalbodeule/develop
[feature] manager detect logic fixed.
2025-05-20 11:21:51 +09:00
dalbodeule
a9d3ad436b
[feature] manager detect logic fixed. 2025-05-20 11:17:36 +09:00
JinU Choi
53757476a7
Merge pull request #131 from dalbodeule/debug
[feature] timer debugs. (2x)
2025-05-18 09:36:27 +09:00
JinU Choi
7257100adc
Merge pull request #130 from dalbodeule/develop
[feature] timer debugs.
2025-05-18 09:27:14 +09:00
5 changed files with 113 additions and 19 deletions

View File

@ -11,6 +11,7 @@ import org.slf4j.Logger
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import space.mori.chzzk_bot.chatbot.chzzk.Connector.getChannel import space.mori.chzzk_bot.chatbot.chzzk.Connector.getChannel
import space.mori.chzzk_bot.chatbot.discord.Discord import space.mori.chzzk_bot.chatbot.discord.Discord
import space.mori.chzzk_bot.chatbot.utils.refreshAccessToken
import space.mori.chzzk_bot.common.events.* import space.mori.chzzk_bot.common.events.*
import space.mori.chzzk_bot.common.models.User import space.mori.chzzk_bot.common.models.User
import space.mori.chzzk_bot.common.services.LiveStatusService import space.mori.chzzk_bot.common.services.LiveStatusService
@ -206,6 +207,7 @@ class UserHandler(
var messageHandler: MessageHandler var messageHandler: MessageHandler
var client: ChzzkClient var client: ChzzkClient
var listener: ChzzkUserSession var listener: ChzzkUserSession
var chatChannelId: String?
private val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java) private val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
private var _isActive: Boolean private var _isActive: Boolean
@ -221,18 +223,17 @@ class UserHandler(
throw RuntimeException("AccessToken or RefreshToken is not valid.") throw RuntimeException("AccessToken or RefreshToken is not valid.")
} }
try { try {
val tokens = user.refreshToken?.let { token -> Connector.client.refreshAccessToken(token) }
client = Connector.getClient(user.accessToken!!, user.refreshToken!!) if(tokens == null) {
throw RuntimeException("AccessToken is not valid.")
}
client = Connector.getClient(tokens.first, tokens.second)
UserService.setRefreshToken(user, tokens.first, tokens.second)
chatChannelId = getChzzkChannelId(channel.channelId)
client.loginAsync().join() client.loginAsync().join()
client.refreshTokenAsync().join()
UserService.setRefreshToken(user, client.loginResult.accessToken(), client.loginResult.refreshToken())
listener = ChzzkSessionBuilder(client).buildUserSession() listener = ChzzkSessionBuilder(client).buildUserSession()
listener.createAndConnectAsync().join() listener.createAndConnectAsync().join()
messageHandler = MessageHandler(this@UserHandler) messageHandler = MessageHandler(this@UserHandler)
listener.on(SessionChatMessageEvent::class.java) { listener.on(SessionChatMessageEvent::class.java) {

View File

@ -88,7 +88,7 @@ class MessageHandler(
} }
private fun manageAddCommand(msg: SessionChatMessage, user: User) { private fun manageAddCommand(msg: SessionChatMessage, user: User) {
if (msg.profile.badges.size == 0) { if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
handler.sendChat("매니저만 명령어를 추가할 수 있습니다.") handler.sendChat("매니저만 명령어를 추가할 수 있습니다.")
return return
} }
@ -109,7 +109,7 @@ class MessageHandler(
} }
private fun manageUpdateCommand(msg: SessionChatMessage, user: User) { private fun manageUpdateCommand(msg: SessionChatMessage, user: User) {
if (msg.profile.badges.size == 0) { if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
handler.sendChat("매니저만 명령어를 추가할 수 있습니다.") handler.sendChat("매니저만 명령어를 추가할 수 있습니다.")
return return
} }
@ -131,7 +131,7 @@ class MessageHandler(
} }
private fun manageRemoveCommand(msg: SessionChatMessage, user: User) { private fun manageRemoveCommand(msg: SessionChatMessage, user: User) {
if (msg.profile.badges.size == 0) { if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
handler.sendChat("매니저만 명령어를 삭제할 수 있습니다.") handler.sendChat("매니저만 명령어를 삭제할 수 있습니다.")
return return
} }
@ -148,7 +148,7 @@ class MessageHandler(
} }
private fun timerCommand(msg: SessionChatMessage, user: User) { private fun timerCommand(msg: SessionChatMessage, user: User) {
if (msg.profile.badges.size == 0) { if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.") handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
return return
} }
@ -227,7 +227,7 @@ class MessageHandler(
val config = SongConfigService.getConfig(user) val config = SongConfigService.getConfig(user)
if(config.streamerOnly && msg.profile.badges.size == 0) { if(config.streamerOnly && msg.profile.badges.none { it.imageUrl.contains("manager") }) {
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.") handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
return return
} }
@ -298,7 +298,7 @@ class MessageHandler(
} }
private fun songStartCommand(msg: SessionChatMessage, user: User) { private fun songStartCommand(msg: SessionChatMessage, user: User) {
if (msg.profile?.badges?.size == 0) { if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.") handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
return return
} }
@ -353,15 +353,15 @@ class MessageHandler(
// Replace followPattern // Replace followPattern
result = followPattern.replace(result) { _ -> result = followPattern.replace(result) { _ ->
try { try {
val followingDate = getFollowDate(channel.channelId, msg.senderChannelId) val followingDate = handler.chatChannelId?.let { getFollowDate(it, msg.senderChannelId) }
.content?.streamingProperty?.following?.followDate ?.content?.streamingProperty?.following?.followDate ?: LocalDateTime.now().minusDays(1).toString()
val period = followingDate?.let { val period = followingDate.let {
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val pastDate = LocalDateTime.parse(it, formatter) val pastDate = LocalDateTime.parse(it, formatter)
val today = LocalDateTime.now() val today = LocalDateTime.now()
ChronoUnit.DAYS.between(pastDate, today) ChronoUnit.DAYS.between(pastDate, today)
} ?: 0 } + 1
period.toString() period.toString()
} catch (e: Exception) { } catch (e: Exception) {

View File

@ -0,0 +1,58 @@
package space.mori.chzzk_bot.chatbot.utils
import com.google.gson.Gson
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import space.mori.chzzk_bot.chatbot.chzzk.dotenv
import space.mori.chzzk_bot.common.utils.client
import xyz.r2turntrue.chzzk4j.ChzzkClient
import java.io.IOException
val client = OkHttpClient.Builder()
.addNetworkInterceptor { chain ->
chain.proceed(
chain.request()
.newBuilder()
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
.build()
)
}
.build()
val gson = Gson()
data class RefreshTokenResponse(
val accessToken: String,
val refreshToken: String,
val expiresIn: Int,
val tokenType: String = "Bearer",
val scope: String
)
fun ChzzkClient.refreshAccessToken(refreshToken: String): Pair<String, String> {
val url = "https://openapi.chzzk.naver.com/auth/v1/token"
val request = Request.Builder()
.url(url)
.header("Content-Type", "application/json")
.post(gson.toJson(mapOf(
"grantType" to "refresh_token",
"refreshToken" to refreshToken,
"clientId" to dotenv["NAVER_CLIENT_ID"],
"clientSecret" to dotenv["NAVER_CLIENT_SECRET"]
)).toRequestBody("application/json; charset=utf-8".toMediaType()))
.build()
client.newCall(request).execute().use { response ->
try {
if(!response.isSuccessful) throw IOException("Unexpected code ${response.code}")
val body = response.body?.string()
val data = gson.fromJson(body, RefreshTokenResponse::class.java)
return Pair(data.accessToken, data.refreshToken)
} catch(e: Exception) {
throw e
}
}
}

View File

@ -52,6 +52,20 @@ data class NicknameColor(
val colorCode: String = "" val colorCode: String = ""
) )
data class LiveStatus(
val liveTitle: String,
val status: String,
val concurrentUserCount: Int,
val accumulateCount: Int,
val paidPromotion: Boolean,
val adult: Boolean,
val krOnlyViewing: Boolean,
val openDate: String,
val closeDate: String?,
val clipActive: Boolean,
val chatChannelId: String
)
// OkHttpClient에 Interceptor 추가 // OkHttpClient에 Interceptor 추가
val client = OkHttpClient.Builder() val client = OkHttpClient.Builder()
.addNetworkInterceptor { chain -> .addNetworkInterceptor { chain ->
@ -84,3 +98,24 @@ fun getFollowDate(chatID: String, userId: String) : IData<IFollowContent?> {
} }
} }
} }
fun getChzzkChannelId(channelId: String): String? {
val url = "https://api.chzzk.naver.com/polling/v3/channels/$channelId/live-status?includePlayerRecommendContent=false"
val request = Request.Builder()
.url(url)
.header("Content-Type", "application/json")
.get()
.build()
client.newCall(request).execute().use { response ->
try {
if(!response.isSuccessful) throw IOException("Unexpected code ${response.code}")
val body = response.body?.string()
val data = gson.fromJson(body, object: TypeToken<IData<LiveStatus?>>() {})
return data.content?.chatChannelId
} catch(e: Exception) {
throw e
}
}
}

View File

@ -181,7 +181,7 @@ val server = embeddedServer(Netty, port = 8080, ) {
clientSecret = dotenv["NAVER_CLIENT_SECRET"] clientSecret = dotenv["NAVER_CLIENT_SECRET"]
) )
val response = applicationHttpClient.post("https://chzzk.naver.com/auth/v1/token") { val response = applicationHttpClient.post("https://openapi.chzzk.naver.com/auth/v1/token") {
contentType(ContentType.Application.Json) contentType(ContentType.Application.Json)
setBody(tokenRequest) setBody(tokenRequest)
} }