1
1
package net.lz1998.mirai.service
2
2
3
3
import dto.HttpDto
4
+ import kotlinx.coroutines.GlobalScope
5
+ import kotlinx.coroutines.launch
6
+ import kotlinx.serialization.Serializable
7
+ import kotlinx.serialization.json.Json
4
8
import net.lz1998.mirai.entity.WebsocketBotClient
9
+ import net.lz1998.mirai.entity.json
5
10
import net.lz1998.mirai.properties.ClientProperties
6
11
import org.springframework.beans.factory.annotation.Autowired
7
12
import org.springframework.stereotype.Service
13
+ import java.io.File
8
14
9
15
@Service
10
16
class BotService {
17
+ init {
18
+ autoCreate(" bots.json" )
19
+ }
20
+
11
21
val botMap = mutableMapOf<Long , WebsocketBotClient >()
12
22
13
23
@Autowired
14
24
lateinit var clientProperties: ClientProperties
15
25
16
26
@Synchronized
17
- suspend fun createBot (botId : Long , password : String ) {
27
+ suspend fun createBot (botId : Long , password : String , wsUrl : String = clientProperties.wsUrl ) {
18
28
var bot = botMap[botId]
19
29
// 如果有旧的,关掉旧的
20
30
bot?.bot?.close()
21
31
bot?.wsClient?.close(1001 , " " )
22
32
23
33
// 开新的
24
- bot = WebsocketBotClient (botId, password, wsUrl = clientProperties. wsUrl)
34
+ bot = WebsocketBotClient (botId, password, wsUrl = wsUrl)
25
35
botMap[botId] = bot
26
36
bot.initBot()
27
37
}
@@ -42,5 +52,34 @@ class BotService {
42
52
val bot = botMap[botId]
43
53
bot?.bot?.login()
44
54
}
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
+ }
45
65
}
46
66
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