Auto loader for BotFactory

This commit is contained in:
Him188 2019-12-20 10:19:36 +08:00
parent 7b9e6e532d
commit a496a93433
2 changed files with 90 additions and 1 deletions

View File

@ -11,7 +11,6 @@ import net.mamoe.mirai.data.Packet
import net.mamoe.mirai.message.data.Image
import net.mamoe.mirai.message.data.ImageId0x03
import net.mamoe.mirai.message.data.ImageId0x06
import net.mamoe.mirai.network.data.*
import net.mamoe.mirai.qqAccount
import net.mamoe.mirai.timpc.internal.RawGroupInfo
import net.mamoe.mirai.timpc.network.GroupImpl

View File

@ -0,0 +1,90 @@
@file:Suppress("FunctionName", "unused")
package net.mamoe.mirai
import kotlinx.coroutines.CoroutineScope
import net.mamoe.mirai.utils.MiraiLogger
// Do not use ServiceLoader. Probably not working on MPP
private val factory = run {
try {
Class.forName("net.mamoe.mirai.timpc.TIMPC").kotlin.objectInstance as BotFactory
} catch (ignored: Exception) {
null
}
} ?: error(
"""
No BotFactory found. Please ensure that you've added dependency of protocol modules.
Available modules:
- net.mamoe:mirai-core-timpc
You should have at lease one protocol module installed.
""".trimIndent()
)
/**
* 加载现有协议的 [BotFactory], 并调用其 [BotFactory.Bot]
*
* 在当前 CoroutineScope 下构造 Bot 实例
* Bot 实例的生命周期将会跟随这个 CoroutineScope.
* 这个 CoroutineScope 也会等待 Bot 的结束才会结束.
*
* ```kotlin
* suspend fun myProcess(){
* TIMPC.Bot(account, logger)
* }
* ```
*/
suspend fun Bot(account: BotAccount, logger: MiraiLogger? = null): Bot =
factory.Bot(account, logger)
/**
* 加载现有协议的 [BotFactory], 并调用其 [BotFactory.Bot]
*
* 在当前 CoroutineScope 下构造 Bot 实例
* Bot 实例的生命周期将会跟随这个 CoroutineScope.
* 这个 CoroutineScope 也会等待 Bot 的结束才会结束.
*
* ```kotlin
* suspend fun myProcess(){
* TIMPC.Bot(account, logger)
* }
* ```
*/
suspend fun Bot(qq: Long, password: String, logger: MiraiLogger? = null): Bot =
factory.Bot(qq, password, logger)
/**
* 加载现有协议的 [BotFactory], 并调用其 [BotFactory.Bot]
*
* 在特定的 CoroutineScope 下构造 Bot 实例
* Bot 实例的生命周期将会跟随这个 CoroutineScope.
* 这个 CoroutineScope 也会等待 Bot 的结束才会结束.
*
* ```kotlin
* fun myProcess(){
* TIMPC.run {
* GlobalScope.Bot(account, logger)
* }
* }
* ```
*/
fun CoroutineScope.Bot(qq: Long, password: String, logger: MiraiLogger? = null): Bot =
factory.run { this@Bot.Bot(qq, password, logger) }
/**
* 加载现有协议的 [BotFactory], 并调用其 [BotFactory.Bot]
*
* 在特定的 CoroutineScope 下构造 Bot 实例
* Bot 实例的生命周期将会跟随这个 CoroutineScope.
* 这个 CoroutineScope 也会等待 Bot 的结束才会结束.
*
* ```kotlin
* fun myProcess(){
* TIMPC.run {
* GlobalScope.Bot(account, logger)
* }
* }
* ```
*/
fun CoroutineScope.Bot(account: BotAccount, logger: MiraiLogger? = null): Bot =
factory.run { this@Bot.Bot(account, logger) }