Do not kill bot on offline. Fix #838

This commit is contained in:
Him188 2021-01-11 17:59:07 +08:00
parent 1d4867d9b6
commit 190a098227

View File

@ -92,7 +92,7 @@ internal abstract class AbstractBot<N : BotNetworkHandler> constructor(
@OptIn(ExperimentalTime::class) @OptIn(ExperimentalTime::class)
@Suppress("unused") @Suppress("unused")
private val offlineListener: Listener<BotOfflineEvent> = private val offlineListener: Listener<BotOfflineEvent> =
this@AbstractBot.eventChannel.subscribeAlways( this@AbstractBot.eventChannel.parentScope(this).subscribeAlways(
priority = MONITOR, priority = MONITOR,
concurrency = ConcurrencyKind.LOCKED concurrency = ConcurrencyKind.LOCKED
) { event -> ) { event ->
@ -116,18 +116,14 @@ internal abstract class AbstractBot<N : BotNetworkHandler> constructor(
when (event) { when (event) {
is BotOfflineEvent.Active -> { is BotOfflineEvent.Active -> {
val cause = event.cause val cause = event.cause
val msg = if (cause == null) { val msg = if (cause == null) "" else " with exception: $cause"
"" bot.logger.info("Bot is closed manually $msg", cause)
} else { network.cancel(CancellationException("Bot offline manually $msg", cause))
" with exception: $cause"
}
bot.logger.info("Bot is closed manually: $msg", cause)
bot.cancel(CancellationException("Bot is closed manually: $msg", cause))
} }
is BotOfflineEvent.Force -> { is BotOfflineEvent.Force -> {
bot.logger.info { "Connection occupied by another android device: ${event.message}" } bot.logger.info { "Connection occupied by another android device: ${event.message}" }
if (!event.reconnect) { if (!event.reconnect) {
bot.cancel(ForceOfflineException("Connection occupied by another android device: ${event.message}")) network.cancel(ForceOfflineException("Connection occupied by another android device: ${event.message}"))
} }
} }
is BotOfflineEvent.MsfOffline, is BotOfflineEvent.MsfOffline,
@ -284,6 +280,7 @@ internal abstract class AbstractBot<N : BotNetworkHandler> constructor(
* [AbstractBot.relogin] && [BotNetworkHandler.init] * [AbstractBot.relogin] && [BotNetworkHandler.init]
*/ */
final override suspend fun login() { final override suspend fun login() {
if (!isActive) error("Bot is already closed and cannot relogin. Please create a new Bot instance then do login.")
Login().doLogin() Login().doLogin()
} }
@ -316,11 +313,16 @@ internal abstract class AbstractBot<N : BotNetworkHandler> constructor(
// already cancelled // already cancelled
return return
} }
GlobalScope.launch {
runCatching { BotOfflineEvent.Active(this@AbstractBot, cause).broadcast() }.exceptionOrNull() if (this.network.areYouOk()) {
?.let { logger.error(it) } GlobalScope.launch {
runCatching { BotOfflineEvent.Active(this@AbstractBot, cause).broadcast() }.exceptionOrNull()
?.let { logger.error(it) }
}
} }
this.network.close(cause)
if (supervisorJob.isActive) { if (supervisorJob.isActive) {
if (cause == null) { if (cause == null) {
supervisorJob.cancel() supervisorJob.cancel()