tgbotapi/tgbotapi.behaviour_builder/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/behaviour_builder/BehaviourBuilders.kt

68 lines
2.4 KiB
Kotlin
Raw Normal View History

package dev.inmo.tgbotapi.extensions.behaviour_builder
2021-01-06 17:06:48 +00:00
import dev.inmo.micro_utils.coroutines.ContextSafelyExceptionHandler
import dev.inmo.micro_utils.coroutines.ExceptionHandler
2021-01-06 17:06:48 +00:00
import dev.inmo.tgbotapi.bot.TelegramBot
2021-01-09 16:10:38 +00:00
import dev.inmo.tgbotapi.extensions.utils.updates.retrieving.longPolling
2021-01-06 17:21:33 +00:00
import dev.inmo.tgbotapi.extensions.utils.updates.retrieving.startGettingOfUpdatesByLongPolling
2021-01-06 17:06:48 +00:00
import dev.inmo.tgbotapi.updateshandlers.FlowsUpdatesFilter
import kotlinx.coroutines.*
2021-01-06 17:06:48 +00:00
2021-08-03 05:27:39 +00:00
/**
* This function is used in [buildBehaviour] extensions to provide default [CoroutineScope] and allow to avoid all
* unnecessary parameters except of block
*/
expect var defaultCoroutineScopeProvider: () -> CoroutineScope
/**
* Use this method in case you wish to make some additional actions with [flowUpdatesFilter].
*
* **WARNING** This method WILL NOT launch any listening of updates. Use something like
* [startGettingOfUpdatesByLongPolling] or tools for work with webhooks
*
* @see [BehaviourContext]
* @see startGettingOfUpdatesByLongPolling
*/
suspend fun TelegramBot.buildBehaviour(
2021-11-08 11:33:02 +00:00
flowUpdatesFilter: FlowsUpdatesFilter = FlowsUpdatesFilter(),
2021-08-03 05:27:39 +00:00
scope: CoroutineScope = defaultCoroutineScopeProvider(),
defaultExceptionsHandler: ExceptionHandler<Unit>? = null,
block: BehaviourContextReceiver<Unit>
): BehaviourContext = BehaviourContext(
this,
scope.let {
if (defaultExceptionsHandler == null) {
it
} else {
it + ContextSafelyExceptionHandler(defaultExceptionsHandler)
}
},
flowUpdatesFilter
).apply {
block()
2021-08-03 05:27:39 +00:00
}
/**
* Use this method to build bot behaviour and run it via long polling. In case you wish to get [FlowsUpdatesFilter] for
* additional manipulations, you must provide external [FlowsUpdatesFilter] in other [buildBehaviour] function.
*
* @see buildBehaviour
* @see BehaviourContext
* @see startGettingOfUpdatesByLongPolling
*/
suspend fun TelegramBot.buildBehaviourWithLongPolling(
2021-08-03 05:27:39 +00:00
scope: CoroutineScope = defaultCoroutineScopeProvider(),
defaultExceptionsHandler: ExceptionHandler<Unit>? = null,
2021-01-07 12:11:01 +00:00
block: BehaviourContextReceiver<Unit>
): Job {
val behaviourContext = buildBehaviour(
scope = scope,
defaultExceptionsHandler = defaultExceptionsHandler,
block = block
2021-01-06 17:21:33 +00:00
)
return longPolling(
behaviourContext,
scope = behaviourContext
2021-01-06 17:21:33 +00:00
)
}