Bot.kt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. /*
  2. * Copyright 2020 Mamoe Technologies and contributors.
  3. *
  4. * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
  5. * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
  6. *
  7. * https://github.com/mamoe/mirai/blob/master/LICENSE
  8. */
  9. @file:Suppress(
  10. "EXPERIMENTAL_API_USAGE", "unused", "FunctionName", "NOTHING_TO_INLINE", "UnusedImport",
  11. "EXPERIMENTAL_OVERRIDE"
  12. )
  13. package net.mamoe.mirai
  14. import kotlinx.coroutines.*
  15. import net.mamoe.mirai.contact.*
  16. import net.mamoe.mirai.event.events.BotInvitedJoinGroupRequestEvent
  17. import net.mamoe.mirai.event.events.MemberJoinRequestEvent
  18. import net.mamoe.mirai.event.events.NewFriendRequestEvent
  19. import net.mamoe.mirai.message.MessageReceipt
  20. import net.mamoe.mirai.message.data.*
  21. import net.mamoe.mirai.network.LoginFailedException
  22. import net.mamoe.mirai.utils.*
  23. import kotlin.coroutines.CoroutineContext
  24. import kotlin.coroutines.EmptyCoroutineContext
  25. import kotlin.jvm.JvmField
  26. import kotlin.jvm.JvmStatic
  27. import kotlin.jvm.JvmSynthetic
  28. /**
  29. * 登录, 返回 [this]
  30. */
  31. @JvmSynthetic
  32. suspend inline fun <B : Bot> B.alsoLogin(): B = also { login() }
  33. /**
  34. * 机器人对象. 一个机器人实例登录一个 QQ 账号.
  35. * Mirai 为多账号设计, 可同时维护多个机器人.
  36. *
  37. * 有关 [Bot] 生命管理, 请查看 [BotConfiguration.inheritCoroutineContext]
  38. *
  39. * @see Contact 联系人
  40. * @see kotlinx.coroutines.isActive 判断 [Bot] 是否正常运行中. (协程正常运行) (但不能判断是否在线, 需使用 [isOnline])
  41. *
  42. * @see BotFactory 构造 [Bot] 的工厂, [Bot] 唯一的构造方式.
  43. */
  44. @Suppress("INAPPLICABLE_JVM_NAME", "EXPOSED_SUPER_CLASS")
  45. abstract class Bot internal constructor(
  46. val configuration: BotConfiguration
  47. ) : CoroutineScope, LowLevelBotAPIAccessor, BotJavaFriendlyAPI, ContactOrBot {
  48. final override val coroutineContext: CoroutineContext = // for id
  49. configuration.parentCoroutineContext
  50. .plus(SupervisorJob(configuration.parentCoroutineContext[Job]))
  51. .plus(configuration.parentCoroutineContext[CoroutineExceptionHandler]
  52. ?: CoroutineExceptionHandler { _, e ->
  53. logger.error("An exception was thrown under a coroutine of Bot", e)
  54. }
  55. )
  56. .plus(CoroutineName("Mirai Bot"))
  57. companion object {
  58. @JvmField
  59. @Suppress("ObjectPropertyName")
  60. internal val _instances: LockFreeLinkedList<WeakRef<Bot>> = LockFreeLinkedList()
  61. /**
  62. * 复制一份此时的 [Bot] 实例列表.
  63. */
  64. @PlannedRemoval("1.2.0")
  65. @Deprecated(
  66. "use botInstances instead",
  67. replaceWith = ReplaceWith("botInstances"),
  68. level = DeprecationLevel.ERROR
  69. )
  70. @JvmStatic
  71. val instances: List<WeakRef<Bot>>
  72. get() = _instances.toList()
  73. /**
  74. * 复制一份此时的 [Bot] 实例列表.
  75. */
  76. @JvmStatic
  77. val botInstances: List<Bot>
  78. get() = _instances.asSequence().mapNotNull { it.get() }.toList()
  79. /**
  80. * 复制一份此时的 [Bot] 实例列表.
  81. */
  82. @MiraiExperimentalAPI
  83. @SinceMirai("1.1.0")
  84. @JvmStatic
  85. val botInstancesSequence: Sequence<Bot>
  86. get() = _instances.asSequence().mapNotNull { it.get() }
  87. /**
  88. * 遍历每一个 [Bot] 实例
  89. */
  90. @JvmSynthetic
  91. fun forEachInstance(block: (Bot) -> Unit) = _instances.forEach { it.get()?.let(block) }
  92. /**
  93. * 获取一个 [Bot] 实例, 无对应实例时抛出 [NoSuchElementException]
  94. */
  95. @JvmStatic
  96. @Throws(NoSuchElementException::class)
  97. fun getInstance(qq: Long): Bot =
  98. getInstanceOrNull(qq) ?: throw NoSuchElementException(qq.toString())
  99. /**
  100. * 获取一个 [Bot] 实例, 无对应实例时返回 `null`
  101. */
  102. @JvmStatic
  103. fun getInstanceOrNull(qq: Long): Bot? =
  104. _instances.asSequence().mapNotNull { it.get() }.firstOrNull { it.id == qq }
  105. }
  106. init {
  107. _instances.addLast(this.weakRef())
  108. supervisorJob.invokeOnCompletion {
  109. _instances.removeIf { it.get()?.id == this.id }
  110. }
  111. }
  112. /**
  113. * [Bot] 运行的 [Context].
  114. *
  115. * 在 JVM 的默认实现为 `class ContextImpl : Context`
  116. * 在 Android 实现为 `android.content.Context`
  117. */
  118. @MiraiExperimentalAPI
  119. abstract val context: Context
  120. /**
  121. * QQ 号码. 实际类型为 uint
  122. */
  123. abstract override val id: Long
  124. /**
  125. * 昵称
  126. */
  127. abstract val nick: String
  128. /**
  129. * 日志记录器
  130. */
  131. abstract val logger: MiraiLogger
  132. /**
  133. * 判断 Bot 是否在线 (可正常收发消息)
  134. */
  135. @SinceMirai("1.0.1")
  136. abstract val isOnline: Boolean
  137. // region contacts
  138. /**
  139. * [User.id] 与 [Bot.id] 相同的 [_lowLevelNewFriend] 实例
  140. */
  141. @MiraiExperimentalAPI
  142. abstract val selfQQ: Friend
  143. /**
  144. * 机器人的好友列表. 与服务器同步更新
  145. */
  146. abstract val friends: ContactList<Friend>
  147. /**
  148. * 获取一个好友对象.
  149. * @throws [NoSuchElementException] 当不存在这个好友时抛出
  150. */
  151. fun getFriend(id: Long): Friend = friends.firstOrNull { it.id == id } ?: throw NoSuchElementException("friend $id")
  152. /**
  153. * 机器人加入的群列表. 与服务器同步更新
  154. */
  155. abstract val groups: ContactList<Group>
  156. /**
  157. * 获取一个机器人加入的群.
  158. * @throws NoSuchElementException 当不存在这个群时抛出
  159. */
  160. fun getGroup(id: Long): Group = groups.firstOrNull { it.id == id } ?: throw NoSuchElementException("group $id")
  161. // endregion
  162. // region network
  163. /**
  164. * 登录, 或重新登录.
  165. * 这个函数总是关闭一切现有网路任务 (但不会关闭其他任务), 然后重新登录并重新缓存好友列表和群列表.
  166. *
  167. * 一般情况下不需要重新登录. Mirai 能够自动处理掉线情况.
  168. *
  169. * @throws LoginFailedException 正常登录失败时抛出
  170. * @see alsoLogin `.apply { login() }` 捷径
  171. */
  172. @JvmSynthetic
  173. abstract suspend fun login()
  174. // endregion
  175. // region actions
  176. /**
  177. * 撤回这条消息. 可撤回自己 2 分钟内发出的消息, 和任意时间的群成员的消息.
  178. *
  179. * [Bot] 撤回自己的消息不需要权限.
  180. * [Bot] 撤回群员的消息需要管理员权限.
  181. *
  182. * @param source 消息源. 可从 [MessageReceipt.source] 获得, 或从消息事件中的 [MessageChain] 获得, 或通过 [buildMessageSource] 构建.
  183. *
  184. * @throws PermissionDeniedException 当 [Bot] 无权限操作时抛出
  185. * @throws IllegalStateException 当这条消息已经被撤回时抛出 (仅同步主动操作)
  186. *
  187. * @see Bot.recall (扩展函数) 接受参数 [MessageChain]
  188. * @see MessageSource.recall 撤回消息扩展
  189. */
  190. @JvmSynthetic
  191. abstract suspend fun recall(source: MessageSource)
  192. /**
  193. * 获取图片下载链接
  194. *
  195. * @see Image.queryUrl [Image] 的扩展函数
  196. */
  197. @PlannedRemoval("1.2.0")
  198. @Deprecated(
  199. "use extension.",
  200. replaceWith = ReplaceWith("image.queryUrl()", imports = ["net.mamoe.mirai.message.data.queryUrl"])
  201. )
  202. @JvmSynthetic
  203. abstract suspend fun queryImageUrl(image: Image): String
  204. /**
  205. * 构造一个 [OfflineMessageSource]
  206. *
  207. * @param id 即 [MessageSource.id]
  208. * @param internalId 即 [MessageSource.internalId]
  209. *
  210. * @param fromUin 为用户时为 [Friend.id], 为群时需使用 [Group.calculateGroupUinByGroupCode] 计算
  211. * @param targetUin 为用户时为 [Friend.id], 为群时需使用 [Group.calculateGroupUinByGroupCode] 计算
  212. */
  213. @MiraiExperimentalAPI("This is very experimental and is subject to change.")
  214. abstract fun constructMessageSource(
  215. kind: OfflineMessageSource.Kind,
  216. fromUin: Long, targetUin: Long,
  217. id: Int, time: Int, internalId: Int,
  218. originalMessage: MessageChain
  219. ): OfflineMessageSource
  220. /**
  221. * 通过好友验证
  222. *
  223. * @param event 好友验证的事件对象
  224. */
  225. @PlannedRemoval("1.2.0")
  226. @Deprecated("use member function.", replaceWith = ReplaceWith("event.accept()"))
  227. @JvmSynthetic
  228. abstract suspend fun acceptNewFriendRequest(event: NewFriendRequestEvent)
  229. /**
  230. * 拒绝好友验证
  231. *
  232. * @param event 好友验证的事件对象
  233. * @param blackList 拒绝后是否拉入黑名单
  234. */
  235. @PlannedRemoval("1.2.0")
  236. @Deprecated("use member function.", replaceWith = ReplaceWith("event.reject(blackList)"))
  237. @JvmSynthetic
  238. abstract suspend fun rejectNewFriendRequest(event: NewFriendRequestEvent, blackList: Boolean = false)
  239. /**
  240. * 通过加群验证(需管理员权限)
  241. *
  242. * @param event 加群验证的事件对象
  243. */
  244. @PlannedRemoval("1.2.0")
  245. @Deprecated("use member function.", replaceWith = ReplaceWith("event.accept()"))
  246. @JvmSynthetic
  247. abstract suspend fun acceptMemberJoinRequest(event: MemberJoinRequestEvent)
  248. /**
  249. * 拒绝加群验证(需管理员权限)
  250. *
  251. * @param event 加群验证的事件对象
  252. * @param blackList 拒绝后是否拉入黑名单
  253. */
  254. @PlannedRemoval("1.2.0")
  255. @Deprecated("use member function.", replaceWith = ReplaceWith("event.reject(blackList)"))
  256. @JvmSynthetic
  257. abstract suspend fun rejectMemberJoinRequest(event: MemberJoinRequestEvent, blackList: Boolean = false)
  258. /**
  259. * 忽略加群验证(需管理员权限)
  260. *
  261. * @param event 加群验证的事件对象
  262. * @param blackList 忽略后是否拉入黑名单
  263. */
  264. @PlannedRemoval("1.2.0")
  265. @Deprecated("use member function.", replaceWith = ReplaceWith("event.ignore(blackList)"))
  266. @JvmSynthetic
  267. abstract suspend fun ignoreMemberJoinRequest(event: MemberJoinRequestEvent, blackList: Boolean = false)
  268. /**
  269. * 接收邀请入群(需管理员权限)
  270. *
  271. * @param event 邀请入群的事件对象
  272. */
  273. @PlannedRemoval("1.2.0")
  274. @Deprecated("use member function.", replaceWith = ReplaceWith("event.accept()"))
  275. @JvmSynthetic
  276. abstract suspend fun acceptInvitedJoinGroupRequest(event: BotInvitedJoinGroupRequestEvent)
  277. /**
  278. * 忽略邀请入群(需管理员权限)
  279. *
  280. * @param event 邀请入群的事件对象
  281. */
  282. @PlannedRemoval("1.2.0")
  283. @Deprecated("use member function.", replaceWith = ReplaceWith("event.ignore()"))
  284. @JvmSynthetic
  285. abstract suspend fun ignoreInvitedJoinGroupRequest(event: BotInvitedJoinGroupRequestEvent)
  286. // endregion
  287. /**
  288. * 关闭这个 [Bot], 立即取消 [Bot] 的 [kotlinx.coroutines.SupervisorJob].
  289. * 之后 [kotlinx.coroutines.isActive] 将会返回 `false`.
  290. *
  291. * **注意:** 不可重新登录. 必须重新实例化一个 [Bot].
  292. *
  293. * @param cause 原因. 为 null 时视为正常关闭, 非 null 时视为异常关闭
  294. *
  295. * @see closeAndJoin 取消并 [Bot.join], 以确保 [Bot] 相关的活动被完全关闭
  296. */
  297. abstract fun close(cause: Throwable? = null)
  298. final override fun toString(): String = "Bot($id)"
  299. }
  300. /**
  301. * 获取 [Job] 的协程 [Job]. 此 [Job] 为一个 [SupervisorJob]
  302. */
  303. @get:JvmSynthetic
  304. val Bot.supervisorJob: CompletableJob
  305. get() = this.coroutineContext[Job] as CompletableJob
  306. /**
  307. * 挂起协程直到 [Bot] 协程被关闭 ([Bot.close]).
  308. * 即使 [Bot] 离线, 也会等待直到协程关闭.
  309. */
  310. @JvmSynthetic
  311. suspend inline fun Bot.join() = this.coroutineContext[Job]!!.join()
  312. /**
  313. * 撤回这条消息.
  314. *
  315. * [Bot] 撤回自己的消息不需要权限, 但需要在发出后 2 分钟内撤回.
  316. * [Bot] 撤回群员的消息需要管理员权限, 可在任意时间撤回.
  317. *
  318. * @throws PermissionDeniedException 当 [Bot] 无权限操作时
  319. * @see Bot.recall
  320. */
  321. @JvmSynthetic
  322. suspend inline fun Bot.recall(message: MessageChain) =
  323. this.recall(message.source)
  324. /**
  325. * 在一段时间后撤回这个消息源所指代的消息.
  326. *
  327. * @param millis 延迟的时间, 单位为毫秒
  328. * @param coroutineContext 额外的 [CoroutineContext]
  329. * @see recall
  330. */
  331. @JvmSynthetic
  332. inline fun CoroutineScope.recallIn(
  333. source: MessageSource,
  334. millis: Long,
  335. coroutineContext: CoroutineContext = EmptyCoroutineContext
  336. ): Job = this.launch(coroutineContext + CoroutineName("MessageRecall")) {
  337. delay(millis)
  338. source.recall()
  339. }
  340. /**
  341. * 在一段时间后撤回这条消息.
  342. *
  343. * @param millis 延迟的时间, 单位为毫秒
  344. * @param coroutineContext 额外的 [CoroutineContext]
  345. * @see recall
  346. */
  347. @JvmSynthetic
  348. inline fun CoroutineScope.recallIn(
  349. message: MessageChain,
  350. millis: Long,
  351. coroutineContext: CoroutineContext = EmptyCoroutineContext
  352. ): Job = this.launch(coroutineContext + CoroutineName("MessageRecall")) {
  353. delay(millis)
  354. message.recall()
  355. }
  356. /**
  357. * 关闭这个 [Bot], 停止一切相关活动. 所有引用都会被释放.
  358. *
  359. * 注: 不可重新登录. 必须重新实例化一个 [Bot].
  360. *
  361. * @param cause 原因. 为 null 时视为正常关闭, 非 null 时视为异常关闭
  362. */
  363. @JvmSynthetic
  364. suspend inline fun Bot.closeAndJoin(cause: Throwable? = null) {
  365. close(cause)
  366. coroutineContext[Job]?.join()
  367. }
  368. @JvmSynthetic
  369. inline fun Bot.containsFriend(id: Long): Boolean = this.friends.contains(id)
  370. @JvmSynthetic
  371. inline fun Bot.containsGroup(id: Long): Boolean = this.groups.contains(id)
  372. @JvmSynthetic
  373. inline fun Bot.getFriendOrNull(id: Long): Friend? = this.friends.getOrNull(id)
  374. @JvmSynthetic
  375. inline fun Bot.getGroupOrNull(id: Long): Group? = this.groups.getOrNull(id)