From 3ecc323d06016c0e4b35fa0be56c7c2ff2bece6b Mon Sep 17 00:00:00 2001 From: MrXiaoM Date: Tue, 27 Feb 2024 00:40:03 +0800 Subject: [PATCH] EventBus should be object for multi bot support --- .../onebot/client/connection/IAdapter.kt | 52 +++++++++ .../onebot/client/connection/WSClient.kt | 108 ++++++------------ .../onebot/client/connection/WSServer.kt | 50 +------- .../onebot/client/handler/EventBus.kt | 19 ++- .../top/mrxiaom/overflow/internal/Overflow.kt | 22 ++-- .../overflow/internal/listener/friend.kt | 26 ++--- .../overflow/internal/listener/group.kt | 49 ++++---- .../overflow/internal/listener/guild.kt | 12 +- .../overflow/internal/utils/BotUtils.kt | 6 + 9 files changed, 158 insertions(+), 186 deletions(-) create mode 100644 onebot/src/main/kotlin/cn/evolvefield/onebot/client/connection/IAdapter.kt diff --git a/onebot/src/main/kotlin/cn/evolvefield/onebot/client/connection/IAdapter.kt b/onebot/src/main/kotlin/cn/evolvefield/onebot/client/connection/IAdapter.kt new file mode 100644 index 00000000..5ac15201 --- /dev/null +++ b/onebot/src/main/kotlin/cn/evolvefield/onebot/client/connection/IAdapter.kt @@ -0,0 +1,52 @@ +package cn.evolvefield.onebot.client.connection + +import cn.evole.onebot.sdk.util.json.JsonsObject +import cn.evolvefield.onebot.client.handler.ActionHandler +import cn.evolvefield.onebot.client.handler.EventBus +import cn.evolvefield.onebot.client.util.ActionSendUtils +import com.google.gson.JsonSyntaxException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import org.slf4j.Logger + +interface IAdapter { + val scope: CoroutineScope + val actionHandler: ActionHandler + val logger: Logger + + fun onReceiveMessage(message: String) { + try { + val json = JsonsObject(message) + if (json.optString(META_EVENT) != HEART_BEAT) { // 过滤心跳 + logger.debug("Client received <-- {}", json.toString()) + + if (json.has(API_RESULT_KEY)) { // 接口回调 + actionHandler.onReceiveActionResp(json) + } else scope.launch { // 处理事件 + mutex.withLock { + EventBus.onReceive(message) + } + } + } + } catch (e: JsonSyntaxException) { + logger.error("Json语法错误: {}", message) + } + } + + fun unlockMutex() { + runCatching { + if (mutex.isLocked) mutex.unlock() + if (ActionSendUtils.mutex.isLocked) ActionSendUtils.mutex.unlock() + } + } + + companion object { + private const val META_EVENT = "meta_event_type" + private const val API_RESULT_KEY = "echo" + private const val HEART_BEAT = "heartbeat" + + val mutex = Mutex() + } +} diff --git a/onebot/src/main/kotlin/cn/evolvefield/onebot/client/connection/WSClient.kt b/onebot/src/main/kotlin/cn/evolvefield/onebot/client/connection/WSClient.kt index 2631e956..f789ea33 100644 --- a/onebot/src/main/kotlin/cn/evolvefield/onebot/client/connection/WSClient.kt +++ b/onebot/src/main/kotlin/cn/evolvefield/onebot/client/connection/WSClient.kt @@ -1,20 +1,13 @@ package cn.evolvefield.onebot.client.connection -import cn.evole.onebot.sdk.util.json.JsonsObject import cn.evolvefield.onebot.client.core.Bot import cn.evolvefield.onebot.client.handler.ActionHandler -import cn.evolvefield.onebot.client.handler.EventBus -import cn.evolvefield.onebot.client.util.ActionSendUtils -import com.google.gson.JsonSyntaxException import kotlinx.coroutines.* -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock import org.java_websocket.client.WebSocketClient import org.java_websocket.framing.CloseFrame import org.java_websocket.handshake.ServerHandshake import org.slf4j.Logger import java.net.URI -import kotlin.math.log /** * Project: onebot-client @@ -23,26 +16,21 @@ import kotlin.math.log * Description: */ class WSClient( - private val scope: CoroutineScope, + override val scope: CoroutineScope, uri: URI, - private val logger: Logger, - private val actionHandler: ActionHandler, - val retryTimes: Int = 5, - val retryWaitMills: Long = 5000L, - val retryRestMills: Long = 60000L, + override val logger: Logger, + override val actionHandler: ActionHandler, + private val retryTimes: Int = 5, + private val retryWaitMills: Long = 5000L, + private val retryRestMills: Long = 60000L, header: Map = mapOf(), -) : WebSocketClient(uri, header) { +) : WebSocketClient(uri, header), IAdapter { private var retryCount = 0 - private var eventBus: EventBus? = null - val connectDef = CompletableDeferred() + private val connectDef = CompletableDeferred() fun createBot(): Bot { return Bot(this, actionHandler) } - fun createEventBus(): EventBus { - return if (eventBus != null) eventBus!! else EventBus().also { eventBus = it } - } - suspend fun connectSuspend(): Boolean { if (super.connectBlocking()) return true return connectDef.await() @@ -52,25 +40,7 @@ class WSClient( logger.info("▌ 已连接到服务器 ┈━═☆") } - override fun onMessage(message: String) { - try { - val jsonObject = JsonsObject(message) - if (HEART_BEAT != jsonObject.optString(META_EVENT)) { //过滤心跳 - logger.debug("Client received <-- {}", jsonObject.toString()) - if (jsonObject.has(API_RESULT_KEY)) { - actionHandler.onReceiveActionResp(jsonObject) //请求执行 - } else { - scope.launch { - mutex.withLock { - eventBus?.onReceive(message) - } - } - } - } - } catch (e: JsonSyntaxException) { - logger.error("Json语法错误:{}", message) - } - } + override fun onMessage(message: String) = onReceiveMessage(message) override fun onClose(code: Int, reason: String, remote: Boolean) { logger.info( @@ -78,35 +48,36 @@ class WSClient( reason.ifEmpty { "未知原因" }, CloseCode.valueOf(code) ?: code ) - runCatching { - if (mutex.isLocked) mutex.unlock() - if (ActionSendUtils.mutex.isLocked) ActionSendUtils.mutex.unlock() + unlockMutex() + + // 自动重连 + if (code != CloseFrame.NORMAL) retry() + } + + private fun retry() { + if (retryTimes < 1 || retryWaitMills < 0) { + logger.warn("连接失败,未开启自动重连,放弃连接") + connectDef.complete(false) + return } - if (code != CloseFrame.NORMAL) { // TODO: 测试确认异常关闭码 - if (retryTimes < 1 || retryWaitMills < 0) { - logger.warn("连接失败,未开启自动重连,放弃连接") - connectDef.complete(false) - return - } - scope.launch { - if (retryCount < retryTimes) { - retryCount++ - logger.warn("等待 ${String.format("%.1f", retryWaitMills / 1000.0F)} 秒后重连 (第 $retryCount/$retryTimes 次)") - delay(retryWaitMills) - } else { - retryCount = 0 - if (retryRestMills < 0) { - logger.warn("重连次数耗尽... 放弃重试") - return@launch - } - logger.warn("重连次数耗尽... 休息 ${String.format("%.1f", retryRestMills / 1000.0F)} 秒后重试") - delay(retryRestMills) - } - logger.info("正在重连...") - if (reconnectBlocking()) { - retryCount = 0 - connectDef.complete(true) + scope.launch { + if (retryCount < retryTimes) { + retryCount++ + logger.warn("等待 ${String.format("%.1f", retryWaitMills / 1000.0F)} 秒后重连 (第 $retryCount/$retryTimes 次)") + delay(retryWaitMills) + } else { + retryCount = 0 + if (retryRestMills < 0) { + logger.warn("重连次数耗尽... 放弃重试") + return@launch } + logger.warn("重连次数耗尽... 休息 ${String.format("%.1f", retryRestMills / 1000.0F)} 秒后重试") + delay(retryRestMills) + } + logger.info("正在重连...") + if (reconnectBlocking()) { + retryCount = 0 + connectDef.complete(true) } } } @@ -116,11 +87,6 @@ class WSClient( } companion object { - private const val META_EVENT = "meta_event_type" - private const val API_RESULT_KEY = "echo" - private const val HEART_BEAT = "heartbeat" - - val mutex = Mutex() fun createAndConnect(scope: CoroutineScope, uri: URI, logger: Logger, actionHandler: ActionHandler, retryTimes: Int, retryWaitMills: Long, retryRestMills: Long, header: Map = mapOf()): WSClient? { val ws = WSClient(scope, uri, logger, actionHandler, retryTimes, retryWaitMills, retryRestMills, header) return ws.takeIf { runBlocking { ws.connectSuspend() } } diff --git a/onebot/src/main/kotlin/cn/evolvefield/onebot/client/connection/WSServer.kt b/onebot/src/main/kotlin/cn/evolvefield/onebot/client/connection/WSServer.kt index 6948217b..e468d6be 100644 --- a/onebot/src/main/kotlin/cn/evolvefield/onebot/client/connection/WSServer.kt +++ b/onebot/src/main/kotlin/cn/evolvefield/onebot/client/connection/WSServer.kt @@ -1,16 +1,9 @@ package cn.evolvefield.onebot.client.connection -import cn.evole.onebot.sdk.util.json.JsonsObject import cn.evolvefield.onebot.client.core.Bot import cn.evolvefield.onebot.client.handler.ActionHandler -import cn.evolvefield.onebot.client.handler.EventBus -import cn.evolvefield.onebot.client.util.ActionSendUtils -import com.google.gson.JsonSyntaxException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.launch -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock import org.java_websocket.WebSocket import org.java_websocket.framing.CloseFrame import org.java_websocket.handshake.ClientHandshake @@ -25,20 +18,15 @@ import java.net.InetSocketAddress * Description: */ class WSServer( - private val scope: CoroutineScope, + override val scope: CoroutineScope, address: InetSocketAddress, - private val logger: Logger, - private val actionHandler: ActionHandler, + override val logger: Logger, + override val actionHandler: ActionHandler, private val token: String -) : WebSocketServer(address) { - private var eventBus: EventBus? = null +) : WebSocketServer(address), IAdapter { private var bot: Bot? = null val def = CompletableDeferred() - fun createEventBus(): EventBus { - return if (eventBus != null) eventBus!! else EventBus().also { eventBus = it } - } - override fun onStart() { logger.info("▌ 反向 WebSocket 服务端已在 $address 启动") logger.info("▌ 正在等待客户端连接...") @@ -76,25 +64,7 @@ class WSServer( }).conn = conn } - override fun onMessage(conn: WebSocket, message: String) { - try { - val jsonObject = JsonsObject(message) - if (HEART_BEAT != jsonObject.optString(META_EVENT)) { //过滤心跳 - logger.debug("Client received <-- {}", jsonObject.toString()) - if (jsonObject.has(API_RESULT_KEY)) { - actionHandler.onReceiveActionResp(jsonObject) //请求执行 - } else { - scope.launch { - mutex.withLock { - eventBus?.onReceive(message) - } - } - } - } - } catch (e: JsonSyntaxException) { - logger.error("Json语法错误: {}", message) - } - } + override fun onMessage(conn: WebSocket, message: String) = onReceiveMessage(message) override fun onClose(conn: WebSocket, code: Int, reason: String, remote: Boolean) { logger.info( @@ -102,10 +72,7 @@ class WSServer( reason.ifEmpty { "未知原因" }, CloseCode.valueOf(code) ?: code ) - runCatching { - if (mutex.isLocked) mutex.unlock() - if (ActionSendUtils.mutex.isLocked) ActionSendUtils.mutex.unlock() - } + unlockMutex() } override fun onError(conn: WebSocket, ex: Exception) { @@ -113,11 +80,6 @@ class WSServer( } companion object { - private const val META_EVENT = "meta_event_type" - private const val API_RESULT_KEY = "echo" - private const val HEART_BEAT = "heartbeat" - - val mutex = Mutex() suspend fun createAndWaitConnect(scope: CoroutineScope, address: InetSocketAddress, logger: Logger, actionHandler: ActionHandler, token: String): Pair { val ws = WSServer(scope, address, logger, actionHandler, token) ws.start() diff --git a/onebot/src/main/kotlin/cn/evolvefield/onebot/client/handler/EventBus.kt b/onebot/src/main/kotlin/cn/evolvefield/onebot/client/handler/EventBus.kt index e4cddef2..7e3bef4a 100644 --- a/onebot/src/main/kotlin/cn/evolvefield/onebot/client/handler/EventBus.kt +++ b/onebot/src/main/kotlin/cn/evolvefield/onebot/client/handler/EventBus.kt @@ -15,21 +15,20 @@ import java.util.concurrent.ConcurrentHashMap * Description: */ @Suppress("unused") -class EventBus { - +object EventBus { + private val log = LoggerFactory.getLogger(EventBus::class.java) //存储监听器对象 - private val eventlistenerlist: MutableList> = ArrayList() - + private val listeners: MutableList> = ArrayList() //缓存类型与监听器的关系 private val cache: MutableMap, List>> = ConcurrentHashMap() fun addListener(listener: EventListener) { - eventlistenerlist.add(listener) + listeners.add(listener) } fun stop() { cache.clear() - eventlistenerlist.clear() + listeners.clear() } /** @@ -63,7 +62,7 @@ class EventBus { */ private fun getMethod(messageType: Class): List> { val eventListeners: MutableList> = ArrayList() - for (eventListener in eventlistenerlist) { + for (eventListener in listeners) { try { if (eventListener.javaClass.declaredMethods.none { it.name == "onMessage" && it.parameterTypes.any { par -> messageType == par } @@ -78,7 +77,7 @@ class EventBus { } val listenerList: List> - get() = eventlistenerlist + get() = listeners /** * 清除类型缓存 @@ -86,8 +85,4 @@ class EventBus { fun cleanCache() { cache.clear() } - - companion object { - private val log = LoggerFactory.getLogger(EventBus::class.java) - } } diff --git a/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/Overflow.kt b/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/Overflow.kt index 08cc3734..41e072ff 100644 --- a/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/Overflow.kt +++ b/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/Overflow.kt @@ -64,9 +64,9 @@ class Overflow : IMirai, CoroutineScope, LowLevelApiAccessor, OverflowAPI { override val BotFactory: BotFactory get() = BotFactoryImpl override var FileCacheStrategy: FileCacheStrategy = net.mamoe.mirai.utils.FileCacheStrategy.PlatformDefault - internal val newFriendRequestFlagMap = mutableMapOf() - internal val newMemberJoinRequestFlagMap = mutableMapOf() - internal val newInviteJoinGroupRequestFlagMap = mutableMapOf() + private val newFriendRequestFlagMap = mutableMapOf() + private val newMemberJoinRequestFlagMap = mutableMapOf() + private val newInviteJoinGroupRequestFlagMap = mutableMapOf() private var miraiConsoleFlag: Boolean = false val startupTime = System.currentTimeMillis() val miraiConsole: Boolean @@ -132,6 +132,11 @@ class Overflow : IMirai, CoroutineScope, LowLevelApiAccessor, OverflowAPI { injectMiraiConsole() } catch (ignored: ClassNotFoundException) { } + EventBus.apply { + addGroupListeners() + addFriendListeners() + addGuildListeners() + } } @Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE") @@ -180,7 +185,6 @@ class Overflow : IMirai, CoroutineScope, LowLevelApiAccessor, OverflowAPI { } val service = ConnectFactory.create(botConfig, logger) - val dispatchers: EventBus val botImpl: cn.evolvefield.onebot.client.core.Bot if (reversed) { val ws = service.createWebsocketServerAndWaitConnect(this) @@ -191,7 +195,6 @@ class Overflow : IMirai, CoroutineScope, LowLevelApiAccessor, OverflowAPI { } return null } - dispatchers = ws.first.createEventBus() botImpl = ws.second } else { val ws = service.createWebsocketClient(this) @@ -203,7 +206,6 @@ class Overflow : IMirai, CoroutineScope, LowLevelApiAccessor, OverflowAPI { } return null } - dispatchers = ws.createEventBus() botImpl = ws.createBot().also { BotFactoryImpl.internalBot = it } } val versionInfo = botImpl.getVersionInfo() @@ -222,11 +224,9 @@ class Overflow : IMirai, CoroutineScope, LowLevelApiAccessor, OverflowAPI { } val bot = botImpl.wrap() - dispatchers.addGroupListeners(bot) - dispatchers.addFriendListeners(bot) - dispatchers.addGuildListeners(bot) - - return bot.also { it.eventDispatcher.broadcastAsync(BotOnlineEvent(bot)) } + return bot.also { + it.eventDispatcher.broadcastAsync(BotOnlineEvent(bot)) + } } override val botStarter: IBotStarter = object : IBotStarter { diff --git a/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/listener/friend.kt b/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/listener/friend.kt index 69dc1ce1..cfec5af2 100644 --- a/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/listener/friend.kt +++ b/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/listener/friend.kt @@ -13,25 +13,25 @@ import net.mamoe.mirai.event.events.NewFriendRequestEvent import net.mamoe.mirai.event.events.StrangerMessageEvent import net.mamoe.mirai.utils.MiraiInternalApi import top.mrxiaom.overflow.internal.Overflow -import top.mrxiaom.overflow.internal.contact.BotWrapper import top.mrxiaom.overflow.internal.message.OnebotMessages import top.mrxiaom.overflow.internal.message.data.IncomingSource +import top.mrxiaom.overflow.internal.utils.bot import top.mrxiaom.overflow.internal.utils.queryProfile import top.mrxiaom.overflow.internal.utils.wrapAsFriend import top.mrxiaom.overflow.internal.utils.wrapAsStranger -internal fun EventBus.addFriendListeners(bot: BotWrapper) { +internal fun EventBus.addFriendListeners() { listOf( - FriendMessageListener(bot), - FriendAddRequestListener(bot), - FriendMessageRecallListener(bot), + FriendMessageListener(), + FriendAddRequestListener(), + FriendMessageRecallListener(), + ).forEach(::addListener) } -internal class FriendMessageListener( - val bot: BotWrapper -) : EventListener { +internal class FriendMessageListener : EventListener { override suspend fun onMessage(e: PrivateMessageEvent) { + val bot = e.bot ?: return when (e.subType) { "friend" -> { val friend = e.privateSender.wrapAsFriend(bot) @@ -89,10 +89,9 @@ internal class FriendMessageListener( } } -internal class FriendAddRequestListener( - val bot: BotWrapper -): EventListener { +internal class FriendAddRequestListener : EventListener { override suspend fun onMessage(e: FriendAddRequestEvent) { + val bot = e.bot ?: return bot.eventDispatcher.broadcastAsync(NewFriendRequestEvent( bot = bot, eventId = Overflow.instance.putNewFriendRequestFlag(e.flag), @@ -104,10 +103,9 @@ internal class FriendAddRequestListener( } } -internal class FriendMessageRecallListener( - val bot: BotWrapper -): EventListener { +internal class FriendMessageRecallListener : EventListener { override suspend fun onMessage(e: PrivateMsgDeleteNoticeEvent) { + val bot = e.bot ?: return val operatorId = e.operatorId.takeIf { it > 0 } ?: e.userId val friend = bot.getFriend(e.userId) ?: throw IllegalStateException("无法找到好友 ${e.userId}") bot.eventDispatcher.broadcastAsync( diff --git a/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/listener/group.kt b/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/listener/group.kt index 5e5959bd..b706d9b2 100644 --- a/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/listener/group.kt +++ b/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/listener/group.kt @@ -13,29 +13,28 @@ import net.mamoe.mirai.contact.nameCardOrNick import net.mamoe.mirai.event.events.* import net.mamoe.mirai.utils.MiraiInternalApi import top.mrxiaom.overflow.internal.Overflow -import top.mrxiaom.overflow.internal.contact.BotWrapper import top.mrxiaom.overflow.internal.message.OnebotMessages import top.mrxiaom.overflow.internal.message.data.IncomingSource +import top.mrxiaom.overflow.internal.utils.bot import top.mrxiaom.overflow.internal.utils.group import top.mrxiaom.overflow.internal.utils.queryProfile import top.mrxiaom.overflow.internal.utils.wrapAsMember -internal fun EventBus.addGroupListeners(bot: BotWrapper) { +internal fun EventBus.addGroupListeners() { listOf( - GroupMessageListener(bot), - GroupNotifyListener(bot), - GroupMessageRecallListener(bot), - GroupAddRequestListener(bot), - GroupTitleChangeNoticeListener(bot), - GroupBanNoticeListener(bot), + GroupMessageListener(), + GroupNotifyListener(), + GroupMessageRecallListener(), + GroupAddRequestListener(), + GroupTitleChangeNoticeListener(), + GroupBanNoticeListener(), ).forEach(::addListener) } -internal class GroupMessageListener( - val bot: BotWrapper -) : EventListener { +internal class GroupMessageListener : EventListener { override suspend fun onMessage(e: GroupMessageEvent) { + val bot = e.bot ?: return when(e.subType) { "normal" -> { val group = bot.group(e.groupId) @@ -93,10 +92,9 @@ internal class GroupMessageListener( } } -internal class GroupNotifyListener( - val bot: BotWrapper -) : EventListener { +internal class GroupNotifyListener : EventListener { override suspend fun onMessage(e: GroupNotifyNoticeEvent) { + val bot = e.bot ?: return val group = bot.group(e.groupId) when (e.subType) { "poke" -> { @@ -109,10 +107,9 @@ internal class GroupNotifyListener( } } -internal class GroupMessageRecallListener( - val bot: BotWrapper -): EventListener { +internal class GroupMessageRecallListener : EventListener { override suspend fun onMessage(e: GroupMsgDeleteNoticeEvent) { + val bot = e.bot ?: return val group = bot.group(e.groupId) val operator = group.queryMember(e.operatorId) val target = group.queryMember(e.userId) ?: throw IllegalStateException("无法找到群 ${e.groupId} 的成员 ${e.userId}") @@ -127,10 +124,9 @@ internal class GroupMessageRecallListener( } } -internal class GroupAddRequestListener( - val bot: BotWrapper -): EventListener { +internal class GroupAddRequestListener : EventListener { override suspend fun onMessage(e: GroupAddRequestEvent) { + val bot = e.bot ?: return when (e.subType) { "add" -> { // 某人申请入群 bot.eventDispatcher.broadcastAsync(MemberJoinRequestEvent( @@ -158,10 +154,9 @@ internal class GroupAddRequestListener( } } -internal class GroupTitleChangeNoticeListener( - val bot: BotWrapper -): EventListener { +internal class GroupTitleChangeNoticeListener : EventListener { override suspend fun onMessage(e: GroupTitleChangeNoticeEvent) { + val bot = e.bot ?: return val group = bot.group(e.groupId) val member = group.queryMember(e.userId) ?: throw IllegalStateException("无法找到群 ${e.groupId} 的成员 ${e.userId}") MemberSpecialTitleChangeEvent( @@ -173,10 +168,9 @@ internal class GroupTitleChangeNoticeListener( } } -internal class GroupBanNoticeListener( - val bot: BotWrapper -): EventListener { +internal class GroupBanNoticeListener : EventListener { override suspend fun onMessage(e: GroupBanNoticeEvent) { + val bot = e.bot ?: return val mute = when(e.subType) { "ban" -> true "lift_ban" -> false @@ -229,5 +223,4 @@ internal class GroupBanNoticeListener( } } } - -} \ No newline at end of file +} diff --git a/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/listener/guild.kt b/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/listener/guild.kt index c95eabc1..7af2bb50 100644 --- a/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/listener/guild.kt +++ b/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/listener/guild.kt @@ -8,18 +8,18 @@ import net.mamoe.mirai.contact.MemberPermission import top.mrxiaom.overflow.event.LegacyGuildMessageEvent import top.mrxiaom.overflow.internal.contact.BotWrapper import top.mrxiaom.overflow.internal.message.OnebotMessages +import top.mrxiaom.overflow.internal.utils.bot -internal fun EventBus.addGuildListeners(bot: BotWrapper) { +internal fun EventBus.addGuildListeners() { listOf( - GuildMessageListener(bot), + GuildMessageListener(), - ).forEach(::addListener) + ).forEach(::addListener) } -internal class GuildMessageListener( - val bot: BotWrapper -) : EventListener { +internal class GuildMessageListener : EventListener { override suspend fun onMessage(e: GuildMessageEvent) { + val bot = e.bot ?: return when (e.subType) { "channel" -> { val miraiMessage = OnebotMessages.deserializeFromOneBot(bot, e.message) diff --git a/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/utils/BotUtils.kt b/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/utils/BotUtils.kt index d6cc1b31..d9d225ae 100644 --- a/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/utils/BotUtils.kt +++ b/overflow-core/src/main/kotlin/top/mrxiaom/overflow/internal/utils/BotUtils.kt @@ -1,5 +1,6 @@ package top.mrxiaom.overflow.internal.utils +import cn.evole.onebot.sdk.event.Event import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.KSerializer @@ -8,11 +9,13 @@ import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull +import net.mamoe.mirai.Bot import net.mamoe.mirai.data.UserProfile import net.mamoe.mirai.utils.CheckableResponseA import net.mamoe.mirai.utils.JsonStruct import net.mamoe.mirai.utils.loadAs import top.mrxiaom.overflow.internal.Overflow +import top.mrxiaom.overflow.internal.asOnebot import top.mrxiaom.overflow.internal.contact.BotWrapper import java.net.HttpURLConnection import java.net.URL @@ -96,3 +99,6 @@ internal suspend inline fun BotWrapper.queryProfile( Overflow.logger.warning("获取用户 $targetId 的资料卡时出现一个异常", it) }.getOrNull() } + +internal val Event.bot: BotWrapper? + get() = Bot.getInstanceOrNull(selfId)?.asOnebot