mirror of
https://github.com/dalbodeule/chibot-chzzk-bot.git
synced 2025-08-09 22:01:13 +00:00
Compare commits
20 Commits
develop
...
945d3fd5e4
Author | SHA1 | Date | |
---|---|---|---|
|
945d3fd5e4 | ||
|
af9c3a2cf5 | ||
|
bd31039f2b | ||
|
c5c115f6e6 | ||
|
5683edaa5e | ||
|
c86f0b2ab3 | ||
|
27cfbd9087 | ||
|
9ce07a025a | ||
|
073b50b9cd | ||
|
f37dd2c59a | ||
|
864ba3748d | ||
|
593b98b7fb | ||
|
95676e9b39 | ||
|
722b5972d9 | ||
|
a88f994ccd | ||
|
49541f7289 | ||
|
ba9fb052cd | ||
|
51232ad593 | ||
|
77eecaca34 | ||
|
90230c4691 |
41
README.md
41
README.md
@@ -1,6 +1,6 @@
|
||||
# nabot_chzzk_bot
|
||||
# chibot_chzzk_bot
|
||||
|
||||
[](https://discord.gg/up8ANZegmy) [](https://teamcity.mori.space/project/NabotChzzkBot) [](https://hub.docker.com/repository/docker/dalbodeule/chzzkbot/general)
|
||||
[](https://discord.gg/up8ANZegmy) [](https://teamcity.mori.space/project/NabotChzzkBot)
|
||||
|
||||
## Chzzk Chatbot with [JDA5](https://github.com/discord-jda/JDA), [chzzk4j](https://github.com/R2turnTrue/chzzk4j)
|
||||
|
||||
@@ -17,17 +17,6 @@
|
||||
- [x] \<daily_counter:counter_name>
|
||||
- [x] \<days:yyyy-mm-dd>
|
||||
|
||||
### 관리 명령어 (on Discord)
|
||||
- [x] /hook token: \[디스코드 연동 페이지에서 받은 Token]
|
||||
- [x] /alert channel: \[디스코드 Channel ID] content: \[알림 내용]
|
||||
- [x] /add label: \[명령어] content: \[내용]
|
||||
- [ ] /list
|
||||
- [x] /update label: \[명령어] content: \[내용]
|
||||
- [x] /delete label: \[명령어]
|
||||
### 매니저 명령어 (on Discord)
|
||||
- [x] /addmanager user: \[Discord user]
|
||||
- [x] /listmanager
|
||||
- [x] /removemanager user: \[Discord user]
|
||||
### 관리 명령어 (on Chzzk chat)
|
||||
- [x] !명령어추가 \[명령어] \[내용]
|
||||
- [x] !명령어수정 \[명령어] \[내용]
|
||||
@@ -42,32 +31,6 @@
|
||||
- [ ] !노래삭제 \[번호]
|
||||
- [ ] !노래설정 \[내용] \[켜기/끄기]
|
||||
|
||||
### Envs
|
||||
- DISCORD_TOKEN
|
||||
- DB_URL
|
||||
- DB_USER
|
||||
- DB_PASS
|
||||
- RUN_AGENT = `false`
|
||||
- NID_AUT
|
||||
- NID_SES
|
||||
|
||||
### 사용 예시
|
||||
- 팔로우
|
||||
- `/add label: !팔로우 content: <name>님은 오늘로 <following>일째 팔로우네요!`
|
||||
- 출첵
|
||||
- `/add label: !출첵 content: <name>님의 <daily_counter:attendance>번째 출석! fail_content: <name>님은 오늘 이미 출석했어요! <daily_counter:attendance>번 했네요?`
|
||||
- `/add label: ? content: <name>님이 <counter:hook>개째 갈고리 수집`
|
||||
- ㄱㅇㅇ
|
||||
- `/add label: ㄱㅇㅇ content: <counter:cute>번째 ㄱㅇㅇ`
|
||||
- `/add label: ㄱㅇㅇ content: 나누 귀여움 +<counter:cute>`
|
||||
- 풉
|
||||
- `/add label: 풉 content: <counter:poop>번째 비웃음?`
|
||||
- `/add label: 풉키풉키 content: <counter:poop>번째 비웃음?`
|
||||
- 바보
|
||||
- `/add label: 바보 content: 나 바보 아니다?`
|
||||
- `/add label: 바보 content: <counter:fool> 번째 바보? 나 바보 아니다?`
|
||||
- 첫방송
|
||||
- `/add label: 첫방송 content: 24년 7월 23일부터 <days:2024-07-23>일 째 방송중!`
|
||||
|
||||
## 사용 기술스택
|
||||
- [Exposed](https://github.com/JetBrains/Exposed)
|
||||
|
@@ -1,11 +1,7 @@
|
||||
package space.mori.chzzk_bot.chatbot.chzzk
|
||||
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.DelicateCoroutinesApi
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.GlobalScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.future.await
|
||||
import org.koin.java.KoinJavaComponent.inject
|
||||
import org.slf4j.Logger
|
||||
import org.slf4j.LoggerFactory
|
||||
@@ -17,7 +13,8 @@ import space.mori.chzzk_bot.common.models.User
|
||||
import space.mori.chzzk_bot.common.services.LiveStatusService
|
||||
import space.mori.chzzk_bot.common.services.TimerConfigService
|
||||
import space.mori.chzzk_bot.common.services.UserService
|
||||
import space.mori.chzzk_bot.common.utils.*
|
||||
import space.mori.chzzk_bot.common.utils.getChzzkChannelId
|
||||
import space.mori.chzzk_bot.common.utils.getUptime
|
||||
import xyz.r2turntrue.chzzk4j.ChzzkClient
|
||||
import xyz.r2turntrue.chzzk4j.session.ChzzkSessionBuilder
|
||||
import xyz.r2turntrue.chzzk4j.session.ChzzkSessionSubscriptionType
|
||||
@@ -25,10 +22,11 @@ import xyz.r2turntrue.chzzk4j.session.ChzzkUserSession
|
||||
import xyz.r2turntrue.chzzk4j.session.event.SessionChatMessageEvent
|
||||
import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannel
|
||||
import xyz.r2turntrue.chzzk4j.types.channel.live.ChzzkLiveDetail
|
||||
import java.lang.Exception
|
||||
import java.lang.Runnable
|
||||
import java.lang.Thread
|
||||
import java.net.SocketTimeoutException
|
||||
import java.time.LocalDateTime
|
||||
import java.nio.charset.Charset
|
||||
import java.time.LocalDateTime
|
||||
|
||||
object ChzzkHandler {
|
||||
private val handlers = mutableListOf<UserHandler>()
|
||||
@@ -46,7 +44,7 @@ object ChzzkHandler {
|
||||
UserService.getAllUsers().map {
|
||||
if(!it.isDisabled)
|
||||
try {
|
||||
Connector.getChannel(it.token)?.let { token -> addUser(token, it) }
|
||||
getChannel(it.token)?.let { token -> addUser(token, it) }
|
||||
} catch(e: Exception) {
|
||||
logger.info("Exception: ${it.token}(${it.username}) not found. ${e.stackTraceToString()}")
|
||||
}
|
||||
@@ -83,8 +81,10 @@ object ChzzkHandler {
|
||||
}
|
||||
|
||||
fun disable() {
|
||||
handlers.forEach { handler ->
|
||||
handler.disable()
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
handlers.forEach { handler ->
|
||||
handler.disable()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,7 +118,7 @@ object ChzzkHandler {
|
||||
try {
|
||||
it.isActive(true, streamInfo)
|
||||
} catch(e: Exception) {
|
||||
logger.info("Exception: ${e.stackTraceToString()}")
|
||||
logger.info("Thread 1 Exception: ${e.stackTraceToString()}")
|
||||
}
|
||||
}
|
||||
if (streamInfo?.isOnline == false && it.isActive) it.isActive(false, streamInfo)
|
||||
@@ -146,14 +146,14 @@ object ChzzkHandler {
|
||||
try {
|
||||
it.isActive(true, streamInfo)
|
||||
} catch(e: Exception) {
|
||||
logger.info("Exception: ${e.stackTraceToString()}")
|
||||
logger.info("Thread 2 Exception: ${e.stackTraceToString()}")
|
||||
}
|
||||
}
|
||||
if (streamInfo?.isOnline == false && it.isActive) it.isActive(false, streamInfo)
|
||||
} catch (e: SocketTimeoutException) {
|
||||
logger.info("Thread 1 Timeout: ${it.channel.channelName} / ${e.stackTraceToString()}")
|
||||
logger.info("Thread 2 Timeout: ${it.channel.channelName} / ${e.stackTraceToString()}")
|
||||
} catch (e: Exception) {
|
||||
logger.info("Thread 1 Exception: ${it.channel.channelName} / ${e.stackTraceToString()}")
|
||||
logger.info("Thread 2 Exception: ${it.channel.channelName} / ${e.stackTraceToString()}")
|
||||
} finally {
|
||||
Thread.sleep(5000)
|
||||
}
|
||||
@@ -204,10 +204,10 @@ class UserHandler(
|
||||
private var user: User,
|
||||
var streamStartTime: LocalDateTime?,
|
||||
) {
|
||||
var messageHandler: MessageHandler
|
||||
var client: ChzzkClient
|
||||
var listener: ChzzkUserSession
|
||||
var chatChannelId: String?
|
||||
lateinit var client: ChzzkClient
|
||||
lateinit var chatChannelId: String
|
||||
lateinit var listener: ChzzkUserSession
|
||||
lateinit var messageHandler: MessageHandler
|
||||
|
||||
private val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
|
||||
private var _isActive: Boolean
|
||||
@@ -216,54 +216,57 @@ class UserHandler(
|
||||
LiveStatusService.updateOrCreate(user, value)
|
||||
}
|
||||
|
||||
init {
|
||||
private suspend fun connect() {
|
||||
val user = UserService.getUser(channel.channelId)
|
||||
|
||||
if(user?.accessToken == null || user.refreshToken == null) {
|
||||
throw RuntimeException("AccessToken or RefreshToken is not valid.")
|
||||
}
|
||||
try {
|
||||
val tokens = Connector.client.refreshAccessToken(user.refreshToken!!)
|
||||
client = Connector.getClient(tokens.first, tokens.second)
|
||||
UserService.setRefreshToken(user, tokens.first, tokens.second)
|
||||
chatChannelId = getChzzkChannelId(channel.channelId)
|
||||
|
||||
client.loginAsync().join()
|
||||
listener = ChzzkSessionBuilder(client).buildUserSession()
|
||||
listener.createAndConnectAsync().join()
|
||||
messageHandler = MessageHandler(this@UserHandler)
|
||||
|
||||
listener.on(SessionChatMessageEvent::class.java) {
|
||||
messageHandler.handle(it.message, user)
|
||||
}
|
||||
|
||||
GlobalScope.launch {
|
||||
val timer = TimerConfigService.getConfig(user)
|
||||
if (timer?.option == TimerType.UPTIME.value)
|
||||
dispatcher.post(
|
||||
TimerEvent(
|
||||
channel.channelId,
|
||||
TimerType.UPTIME,
|
||||
getUptime(streamStartTime!!)
|
||||
)
|
||||
)
|
||||
else dispatcher.post(
|
||||
TimerEvent(
|
||||
channel.channelId,
|
||||
TimerType.entries.firstOrNull { it.value == timer?.option } ?: TimerType.REMOVE,
|
||||
null
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
} catch(e: Exception) {
|
||||
logger.error("Exception(${user.username}): ${e.stackTraceToString()}")
|
||||
throw RuntimeException("Exception: ${e.stackTraceToString()}")
|
||||
val tokens = user.refreshToken?.let { token -> Connector.client.refreshAccessToken(token)}
|
||||
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) ?: throw RuntimeException("Chat Channel ID is not found.")
|
||||
|
||||
client.loginAsync().await()
|
||||
listener = ChzzkSessionBuilder(client).buildUserSession()
|
||||
listener.createAndConnectAsync().await()
|
||||
listener.subscribeAsync(ChzzkSessionSubscriptionType.CHAT)?.await()
|
||||
|
||||
delay(5000L)
|
||||
|
||||
messageHandler = MessageHandler(this@UserHandler)
|
||||
logger.info("${user.username} message handler init.")
|
||||
listener.on(SessionChatMessageEvent::class.java) {
|
||||
messageHandler.handle(it.message, user)
|
||||
}
|
||||
logger.info("${user.username} is connected.")
|
||||
|
||||
val timer = TimerConfigService.getConfig(user)
|
||||
if (timer?.option == TimerType.UPTIME.value)
|
||||
dispatcher.post(
|
||||
TimerEvent(
|
||||
channel.channelId,
|
||||
TimerType.UPTIME,
|
||||
getUptime(streamStartTime!!)
|
||||
)
|
||||
)
|
||||
else dispatcher.post(
|
||||
TimerEvent(
|
||||
channel.channelId,
|
||||
TimerType.entries.firstOrNull { it.value == timer?.option } ?: TimerType.REMOVE,
|
||||
null
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
internal fun disable() {
|
||||
listener.disconnectAsync().join()
|
||||
internal suspend fun disable() {
|
||||
listener.unsubscribeAsync(ChzzkSessionSubscriptionType.CHAT)?.await()
|
||||
listener.disconnectAsync()?.await()
|
||||
|
||||
_isActive = false
|
||||
}
|
||||
|
||||
@@ -281,13 +284,13 @@ class UserHandler(
|
||||
internal fun isActive(value: Boolean, status: ChzzkLiveDetail) {
|
||||
if(value) {
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
connect()
|
||||
|
||||
logger.info("${user.username} is live.")
|
||||
|
||||
reloadUser(UserService.getUser(user.id.value)!!)
|
||||
|
||||
logger.info("ChzzkChat connecting... ${channel.channelName} - ${channel.channelId}")
|
||||
listener.subscribeAsync(ChzzkSessionSubscriptionType.CHAT).join()
|
||||
|
||||
streamStartTime = LocalDateTime.now()
|
||||
|
||||
if(!_isActive) {
|
||||
@@ -322,7 +325,8 @@ class UserHandler(
|
||||
} else {
|
||||
logger.info("${user.username} is offline.")
|
||||
streamStartTime = null
|
||||
listener.disconnectAsync().join()
|
||||
listener.unsubscribeAsync(ChzzkSessionSubscriptionType.CHAT)?.join()
|
||||
listener.disconnectAsync()?.join()
|
||||
_isActive = false
|
||||
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
|
@@ -11,10 +11,8 @@ import space.mori.chzzk_bot.common.services.*
|
||||
import space.mori.chzzk_bot.common.utils.getFollowDate
|
||||
import space.mori.chzzk_bot.common.utils.getUptime
|
||||
import space.mori.chzzk_bot.common.utils.getYoutubeVideo
|
||||
import xyz.r2turntrue.chzzk4j.chat.ChatMessage
|
||||
import xyz.r2turntrue.chzzk4j.chat.ChzzkChat
|
||||
import xyz.r2turntrue.chzzk4j.session.ChzzkUserSession
|
||||
import xyz.r2turntrue.chzzk4j.session.message.SessionChatMessage
|
||||
import xyz.r2turntrue.chzzk4j.types.channel.live.ChzzkLiveSettings
|
||||
import java.time.LocalDateTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.time.temporal.ChronoUnit
|
||||
@@ -39,11 +37,13 @@ class MessageHandler(
|
||||
|
||||
init {
|
||||
reloadCommand()
|
||||
dispatcher.subscribe(SongEvent::class) {
|
||||
if(it.type == SongType.STREAM_OFF) {
|
||||
val user = UserService.getUser(channel.channelId)
|
||||
if(! user?.let { usr -> SongListService.getSong(usr) }.isNullOrEmpty()) {
|
||||
SongListService.deleteUser(user)
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
dispatcher.subscribe(SongEvent::class) {
|
||||
if(it.type == SongType.STREAM_OFF) {
|
||||
val user = UserService.getUser(channel.channelId)
|
||||
if(! user?.let { usr -> SongListService.getSong(usr) }.isNullOrEmpty()) {
|
||||
SongListService.deleteUser(user)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,6 +62,8 @@ class MessageHandler(
|
||||
"!신청곡" to this::songAddCommand,
|
||||
"!노래목록" to this::songListCommand,
|
||||
"!노래시작" to this::songStartCommand,
|
||||
"!카테고리" to this::categoryChangeCommand,
|
||||
"!방제" to this::titleChangeCommand,
|
||||
)
|
||||
|
||||
manageCommands.forEach { (commandName, command) ->
|
||||
@@ -84,11 +86,11 @@ class MessageHandler(
|
||||
}
|
||||
|
||||
private fun commandListCommand(msg: SessionChatMessage, user: User) {
|
||||
handler.sendChat("리스트는 여기입니다. https://nabot.mori.space/commands/${user.token}")
|
||||
handler.sendChat("리스트는 여기입니다. https://chibot.mori.space/commands/${user.token}")
|
||||
}
|
||||
|
||||
private fun manageAddCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
|
||||
if (msg.profile.badges.none { it.isModerator() }) {
|
||||
handler.sendChat("매니저만 명령어를 추가할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -109,7 +111,7 @@ class MessageHandler(
|
||||
}
|
||||
|
||||
private fun manageUpdateCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
|
||||
if (msg.profile.badges.none { it.isModerator() }) {
|
||||
handler.sendChat("매니저만 명령어를 추가할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -131,7 +133,7 @@ class MessageHandler(
|
||||
}
|
||||
|
||||
private fun manageRemoveCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
|
||||
if (msg.profile.badges.none { it.isModerator() }) {
|
||||
handler.sendChat("매니저만 명령어를 삭제할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -148,7 +150,7 @@ class MessageHandler(
|
||||
}
|
||||
|
||||
private fun timerCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
|
||||
if (msg.profile.badges.none { it.isModerator() }) {
|
||||
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -227,7 +229,7 @@ class MessageHandler(
|
||||
|
||||
val config = SongConfigService.getConfig(user)
|
||||
|
||||
if(config.streamerOnly && msg.profile.badges.none { it.imageUrl.contains("manager") }) {
|
||||
if(config.streamerOnly && msg.profile.badges.none { it.imageUrl.contains("manager") || it.imageUrl.contains("streamer") }) {
|
||||
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -294,11 +296,11 @@ class MessageHandler(
|
||||
return
|
||||
}
|
||||
|
||||
handler.sendChat("리스트는 여기입니다. https://nabot.mori.space/songs/${user.token}")
|
||||
handler.sendChat("리스트는 여기입니다. https://chibot.mori.space/songs/${user.token}")
|
||||
}
|
||||
|
||||
private fun songStartCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
|
||||
if (msg.profile.badges.none { it.isModerator() }) {
|
||||
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -307,7 +309,7 @@ class MessageHandler(
|
||||
if(user.discord != null) {
|
||||
bot.retrieveUserById(user.discord!!).queue { discordUser ->
|
||||
discordUser?.openPrivateChannel()?.queue { channel ->
|
||||
channel.sendMessage("여기로 접속해주세요! ||https://nabot.mori.space/songlist||.")
|
||||
channel.sendMessage("여기로 접속해주세요! ||https://chibot.mori.space/songlist||.")
|
||||
.queue()
|
||||
}
|
||||
}
|
||||
@@ -316,6 +318,58 @@ class MessageHandler(
|
||||
}
|
||||
}
|
||||
|
||||
private fun categoryChangeCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.none { it.isModerator() }) {
|
||||
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
|
||||
val parts = msg.content.split(" ", limit = 2)
|
||||
if(parts.size <= 1) {
|
||||
handler.sendChat("카테고리가 없습니다.")
|
||||
return
|
||||
}
|
||||
val category = parts[1].let {
|
||||
return@let when(it) {
|
||||
"저챗", "토크", "JustChatting", "Just Chatting", "" -> "talk"
|
||||
else -> it
|
||||
}
|
||||
}
|
||||
handler.sendChat("$category 카테고리로 수정을 시도해볼게요!")
|
||||
handler.client.searchCategories(category).handle { result, _ ->
|
||||
if(result.size == 0) {
|
||||
handler.sendChat("$category 카테고리는 없습니다.")
|
||||
return@handle
|
||||
}
|
||||
val settings = ChzzkLiveSettings()
|
||||
settings.category = result.first {
|
||||
it.categoryValue == category
|
||||
} ?: result[0]
|
||||
|
||||
handler.client.modifyLiveSettings(settings)
|
||||
handler.sendChat("$category 로 수정했어요!")
|
||||
}
|
||||
}
|
||||
|
||||
private fun titleChangeCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.none { it.isModerator() }) {
|
||||
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
|
||||
val parts = msg.content.split(" ", limit = 2)
|
||||
if(parts.size <= 1) {
|
||||
handler.sendChat("입력된 방송 제목이 없습니다.")
|
||||
return
|
||||
}
|
||||
val title = parts[1]
|
||||
val settings = ChzzkLiveSettings()
|
||||
settings.defaultLiveTitle = title
|
||||
|
||||
handler.client.modifyLiveSettings(settings)
|
||||
handler.sendChat("$title 로 수정했어요!")
|
||||
}
|
||||
|
||||
internal fun handle(msg: SessionChatMessage, user: User) {
|
||||
if(msg.senderChannelId == ChzzkHandler.botUid) return
|
||||
|
||||
@@ -398,3 +452,7 @@ class MessageHandler(
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
fun SessionChatMessage.Profile.Badge.isManager() = imageUrl.contains("manager")
|
||||
fun SessionChatMessage.Profile.Badge.isStreamer() = imageUrl.contains("streamer")
|
||||
fun SessionChatMessage.Profile.Badge.isModerator() = isManager() || isStreamer()
|
@@ -1,24 +1,15 @@
|
||||
package space.mori.chzzk_bot.chatbot.utils
|
||||
|
||||
import com.google.gson.Gson
|
||||
import okhttp3.OkHttpClient
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import space.mori.chzzk_bot.chatbot.chzzk.dotenv
|
||||
import space.mori.chzzk_bot.common.utils.IData
|
||||
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,
|
||||
@@ -29,25 +20,25 @@ data class RefreshTokenResponse(
|
||||
)
|
||||
|
||||
fun ChzzkClient.refreshAccessToken(refreshToken: String): Pair<String, String> {
|
||||
val url = "https://chzzk.naver.com/auth/v1/token"
|
||||
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 this.apiClientId,
|
||||
"clientSecret" to this.apiSecret
|
||||
)).toRequestBody())
|
||||
"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)
|
||||
val data = gson.fromJson(body, object: TypeToken<IData<RefreshTokenResponse>>() {})
|
||||
|
||||
return Pair(data.accessToken, data.refreshToken)
|
||||
return Pair(data.content.accessToken, data.content.refreshToken)
|
||||
} catch(e: Exception) {
|
||||
throw e
|
||||
}
|
||||
|
@@ -181,7 +181,7 @@ val server = embeddedServer(Netty, port = 8080, ) {
|
||||
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)
|
||||
setBody(tokenRequest)
|
||||
}
|
||||
@@ -228,8 +228,7 @@ val server = embeddedServer(Netty, port = 8080, ) {
|
||||
// common: logout
|
||||
get("/logout") {
|
||||
call.sessions.clear<UserSession>()
|
||||
call.response.status(HttpStatusCode.OK)
|
||||
return@get
|
||||
call.respondRedirect(getFrontendURL(""))
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user