Skip to content

Conversation

@ForliyScarlet
Copy link
Member

@ForliyScarlet ForliyScarlet commented May 17, 2025

OneBot协议中可能存在很多额外的、自定义的事件。

在配置中增加注册 CustomEventResolver 的配置项以支持对初步解析的事件进行处理,允许自定义事件解析。

假设自定义的事件是这样的:

{
  "post_type": "custom",
  "custom_type": "test",
  "value": "test1"
}

那么注册解析器:

// 事件类型定义
    @OptIn(FuzzyEventTypeImplementation::class)
    @Serializable
   data class CustomEvent(
        @SerialName("post_type")
        val postType: String,
        @SerialName("custom_type")
        val customType: String,
        val value: String
    ) : Event {
        override val id: ID = UUID.random()

        @OptIn(ExperimentalSimbotAPI::class)
        override val time: Timestamp = Timestamp.now()
    }

////

botManager.register {
  // this: OneBotBotConfiguration
  // 添加一个自定义事件解析器
  addCustomEventResolver { context ->
      val rawEventResolveResult = context.rawEventResolveResult
      if (rawEventResolveResult.postType == "custom" && rawEventResolveResult.subType == "test") {
          return@addCustomEventResolver context.json.decodeFromJsonElement(
              CustomEvent.serializer(),
              rawEventResolveResult.json
          )
      }
      
      null // null 代表跳过
  }
    
    // 可以在实现了ktx序列化的情况下使用扩展函数:
    addCustomKotlinSerializationEventResolver("custom", "test") {
        CustomEvent.serializer()
    }
}

Note

postTypesubType 要符合OneBot协议的一贯风格。即 subType 的 key 为 ${postType}_type,以上述代码示例为例,当 postType = custom 时,subType 的 key 名称为 custom_type,此时 subType 的实际值为 test

Warning

相关API和类型处于实验阶段。

Warning

自定义事件处理器优先级高于的 RawEvent 处理,因此当自定义事件处理器得到了结果,会覆盖原本默认的处理方案。

close #204

@ForteScarlet ForteScarlet requested a review from Copilot May 17, 2025 16:43
@ForteScarlet ForteScarlet added the 特性 New feature or request label May 17, 2025
@ForteScarlet ForteScarlet enabled auto-merge May 17, 2025 16:45
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR adds support for registering custom event resolvers in the OneBot protocol implementation, enabling users to plug in their own parsing logic for “custom” post types.

  • Introduces the CustomEventResolver API (and Kotlin-serialization variant) under an opt-in experimental flag
  • Extends OneBotBotConfiguration to collect custom resolvers and updates OneBotBotImpl to invoke them during event resolution
  • Adds related exception types, result interfaces, and tests for the new feature

Reviewed Changes

Copilot reviewed 16 out of 16 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
RawEventDeserializationException.kt New exception type for raw event deserialization failures
CustomEventResolverTests.kt Tests for custom resolver and KTX serialization resolver
RawEventResolveResult.kt Interface for the initial parse result of a raw event
ExperimentalCustomEventResolverApi.kt Opt-in annotation for the custom resolver API
CustomKotlinSerializationEventResolver.kt Functional interface for Kotlin-serialization-based resolvers
CustomEventResolver.kt Core functional interface for custom event resolution
CustomEventResolveException.kt Exception for errors during custom resolution
RawEventResolveResultImpl.kt Internal data class implementing RawEventResolveResult
OneBotBotImpl.kt Implements resolveEvent to apply custom resolvers and fallback logic
OneBotBotConfiguration.kt Adds addCustomEventResolver and KTX helper to configuration
OneBotBot.kt Annotates push and pushAndLaunch parameters as JSON strings
OneBotApi.kt Fixes doc comment for API result deserializer
build.gradle.kts Adjusts source-set dependency declarations
P.kt Bumps project version to 1.8.0
Comments suppressed due to low confidence (2)

simbot-component-onebot-v11/simbot-component-onebot-v11-core/src/commonTest/kotlin/love/forte/simbot/component/onebot/v11/core/event/CustomEventResolverTests.kt:150

  • [nitpick] Add tests for the fallback behavior when no custom resolver matches, verifying that default parsing or an UnknownEvent is emitted as expected.
// end of existing tests

buildSrc/src/main/kotlin/P.kt:41

  • NEXT_VERSION is identical to VERSION; consider bumping NEXT_VERSION beyond the current release (e.g. 1.9.0) to ensure snapshot/versioning semantics remain clear.
const val NEXT_VERSION = "1.8.0"

* 解析数据包为 Event。
*/
@OptIn(FragileSimbotAPI::class, ExperimentalCustomEventResolverApi::class)
internal fun OneBotBotImpl.resolveEvent(text: String): Event {
Copy link

Copilot AI May 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] The resolveEvent method is quite long and handles multiple concerns; consider refactoring into smaller helper functions (e.g., applyCustomResolvers, resolveDefaultEvent, logErrors) for improved readability and testability.

Copilot uses AI. Check for mistakes.
@ForliyScarlet
Copy link
Member Author

ForliyScarlet commented May 17, 2025

Qodana Community for JVM

2 new problems were found

Inspection name Severity Problems
Unresolved reference in KDoc 🔶 Warning 2

💡 Qodana analysis was run in the pull request mode: only the changed files were checked
☁️ View the detailed Qodana report

Contact Qodana team

Contact us at [email protected]

@ForteScarlet ForteScarlet merged commit 92752e8 into dev/main May 17, 2025
4 checks passed
@ForteScarlet ForteScarlet deleted the dev/custom-event-type branch May 17, 2025 18:15
@ForteScarlet
Copy link
Member

ForteScarlet commented May 19, 2025

simple-robot/simpler-robot#1071 结束前,使用spring boot starter需要自行注册bot来使用无法序列化的配置

start 之前,可以对 bot.configuration 继续配置。

val bot  = ...
bot.configuration.addCustomKotlinSerializationEventResolver("custom", "test") {
        CustomEvent.serializer()
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

特性 New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants