11package net.lz1998.mirai.service
22
33import dto.HttpDto
4+ import kotlinx.coroutines.GlobalScope
5+ import kotlinx.coroutines.launch
6+ import kotlinx.serialization.Serializable
7+ import kotlinx.serialization.json.Json
48import net.lz1998.mirai.entity.WebsocketBotClient
9+ import net.lz1998.mirai.entity.json
510import net.lz1998.mirai.properties.ClientProperties
611import org.springframework.beans.factory.annotation.Autowired
712import org.springframework.stereotype.Service
13+ import java.io.File
814
915@Service
1016class 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