1
0
mirror of https://github.com/InsanusMokrassar/TelegramBotAPI.git synced 2024-06-02 16:05:28 +00:00
tgbotapi/tgbotapi.behaviour_builder/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/behaviour_builder/BehaviourBuilders.kt

71 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 dev.inmo.tgbotapi.utils.PreviewFeature
2021-01-06 17:06:48 +00:00
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.plus
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(
this,
scope.let {
if (defaultExceptionsHandler == null) {
it
} else {
it + ContextSafelyExceptionHandler(defaultExceptionsHandler)
}
},
flowUpdatesFilter
).block()
}
/**
* 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>
) = FlowsUpdatesFilter().let {
2021-01-07 12:11:01 +00:00
buildBehaviour(
2021-01-06 17:21:33 +00:00
it,
2021-10-01 10:40:04 +00:00
scope,
defaultExceptionsHandler,
2021-01-06 17:21:33 +00:00
block
)
2021-01-09 16:10:38 +00:00
longPolling(
it,
2021-01-06 17:21:33 +00:00
scope = scope
)
}