Skip to content

Commit ce86718

Browse files
committed
auto create
1 parent 9fdff0f commit ce86718

File tree

2 files changed

+46
-3
lines changed

2 files changed

+46
-3
lines changed
Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
package net.lz1998.mirai.properties
22

3+
import org.springframework.beans.factory.annotation.Value
34
import org.springframework.boot.context.properties.ConfigurationProperties
5+
import org.springframework.stereotype.Component
46

57

8+
@Component
69
@ConfigurationProperties("bot.client")
7-
class ClientProperties {
10+
object ClientProperties {
11+
@Value("\${bot.client.wsUrl}")
812
var wsUrl = "ws://127.0.0.1/ws/cq/"
913
}

src/main/kotlin/net/lz1998/mirai/service/BotService.kt

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,37 @@
11
package net.lz1998.mirai.service
22

33
import dto.HttpDto
4+
import kotlinx.coroutines.GlobalScope
5+
import kotlinx.coroutines.launch
6+
import kotlinx.serialization.Serializable
7+
import kotlinx.serialization.json.Json
48
import net.lz1998.mirai.entity.WebsocketBotClient
9+
import net.lz1998.mirai.entity.json
510
import net.lz1998.mirai.properties.ClientProperties
611
import org.springframework.beans.factory.annotation.Autowired
712
import org.springframework.stereotype.Service
13+
import java.io.File
814

915
@Service
1016
class BotService {
17+
init {
18+
autoCreate("bots.json")
19+
}
20+
1121
val botMap = mutableMapOf<Long, WebsocketBotClient>()
1222

1323
@Autowired
1424
lateinit var clientProperties: ClientProperties
1525

1626
@Synchronized
17-
suspend fun createBot(botId: Long, password: String) {
27+
suspend fun createBot(botId: Long, password: String, wsUrl: String = clientProperties.wsUrl) {
1828
var bot = botMap[botId]
1929
// 如果有旧的,关掉旧的
2030
bot?.bot?.close()
2131
bot?.wsClient?.close(1001, "")
2232

2333
// 开新的
24-
bot = WebsocketBotClient(botId, password, wsUrl = clientProperties.wsUrl)
34+
bot = WebsocketBotClient(botId, password, wsUrl = wsUrl)
2535
botMap[botId] = bot
2636
bot.initBot()
2737
}
@@ -42,5 +52,34 @@ class BotService {
4252
val bot = botMap[botId]
4353
bot?.bot?.login()
4454
}
55+
56+
// 自动使用配置文件创建
57+
private final fun autoCreate(filepath: String) {
58+
File(filepath).loadAsBotInfo(json).accounts.forEach {
59+
GlobalScope.launch {
60+
println("auto create ${it.uin}")
61+
createBot(it.uin, it.password, it.wsUrl)
62+
}
63+
}
64+
}
4565
}
4666

67+
68+
fun File.loadAsBotInfo(json: Json): BotInfo {
69+
if (!this.exists() || this.length() == 0L) {
70+
return BotInfo(listOf())
71+
}
72+
return json.decodeFromString(BotInfo.serializer(), this.readText())
73+
}
74+
75+
@Serializable
76+
class BotInfo(
77+
val accounts: List<BotAccount>
78+
)
79+
80+
@Serializable
81+
class BotAccount(
82+
val uin: Long,
83+
val password: String,
84+
val wsUrl: String,
85+
)

0 commit comments

Comments
 (0)