Skip to content

Commit 1ad551a

Browse files
committed
separate CoroutineScopes for receiving and executing commands to improve stability
1 parent 43ddebe commit 1ad551a

1 file changed

Lines changed: 11 additions & 4 deletions

File tree

  • src/main/kotlin/com/helltar/signai/bot

src/main/kotlin/com/helltar/signai/bot/Bot.kt

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,11 @@ class Bot(private val config: Config.BotConfig) {
1818
private val chatGPT = ChatGPT(config.openaiAPIKey, config.gptModel, KtorClient)
1919

2020
private val chatDeps = ChatDeps(CommandDeps(signal), config.chatSystemPrompt, chatGPT)
21-
2221
private val commandRegistry = CommandRegistry(chatDeps)
23-
private val scope = CoroutineScope(Dispatchers.IO)
24-
private val commandExecutor = CommandExecutor(scope, userRequestsPerHour = config.userRPH)
22+
23+
private val receiveScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
24+
private val commandScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
25+
private val commandExecutor = CommandExecutor(commandScope, userRequestsPerHour = config.userRPH)
2526

2627
private companion object {
2728
val whitespaceRegex = Regex("\\s+")
@@ -41,7 +42,7 @@ class Bot(private val config: Config.BotConfig) {
4142
log.info { "🚀 start ..." }
4243
}
4344

44-
private fun run() = scope.launch {
45+
private fun run() = receiveScope.launch {
4546
while (isActive) {
4647
try {
4748
signal.receiveEach { message ->
@@ -53,6 +54,12 @@ class Bot(private val config: Config.BotConfig) {
5354
commandExecutor.execute(Chat(message.envelope, chatDeps))
5455
}
5556
}
57+
58+
log.info { "websocket connection closed, reconnecting ..." }
59+
delay(1.seconds)
60+
} catch (e: CancellationException) {
61+
log.debug { "bot loop cancelled" }
62+
throw e
5663
} catch (e: Exception) {
5764
log.error(e) { "❌ bot loop failed: ${e::class.simpleName}: ${e.message}" }
5865
log.info { "⏳ delay 10 seconds before retry ..." }

0 commit comments

Comments
 (0)