1
0
mirror of https://github.com/InsanusMokrassar/TelegramBotAPI.git synced 2025-11-15 03:20:18 +00:00

add lazy loadable bot info

This commit is contained in:
2025-08-10 18:05:48 +06:00
parent ff39271afd
commit c09d089707
8 changed files with 192 additions and 29 deletions

View File

@@ -3,6 +3,7 @@ package dev.inmo.tgbotapi.extensions.behaviour_builder
import dev.inmo.micro_utils.coroutines.ContextSafelyExceptionHandler
import dev.inmo.micro_utils.coroutines.ExceptionHandler
import dev.inmo.tgbotapi.bot.TelegramBot
import dev.inmo.tgbotapi.extensions.behaviour_builder.utils.DefaultCustomBehaviourContextAndTypeReceiver
import dev.inmo.tgbotapi.extensions.utils.updates.retrieving.longPolling
import dev.inmo.tgbotapi.extensions.utils.updates.retrieving.startGettingOfUpdatesByLongPolling
import dev.inmo.tgbotapi.extensions.utils.updates.retrieving.updateHandlerWithMediaGroupsAdaptation
@@ -31,6 +32,7 @@ suspend fun TelegramBot.buildBehaviour(
scope: CoroutineScope = defaultCoroutineScopeProvider(),
defaultExceptionsHandler: ExceptionHandler<Unit>? = null,
subcontextInitialAction: CustomBehaviourContextAndTypeReceiver<BehaviourContext, Unit, Update> = {},
useDefaultSubcontextInitialAction: Boolean = true,
block: BehaviourContextReceiver<Unit>
): BehaviourContext = BehaviourContext(
bot = this,
@@ -42,7 +44,11 @@ suspend fun TelegramBot.buildBehaviour(
}
},
flowsUpdatesFilter = flowUpdatesFilter,
subcontextInitialAction = subcontextInitialAction
subcontextInitialAction = if (useDefaultSubcontextInitialAction) {
DefaultCustomBehaviourContextAndTypeReceiver(subcontextInitialAction)
} else {
subcontextInitialAction
}
).apply {
block()
}
@@ -67,12 +73,14 @@ suspend fun TelegramBot.buildBehaviourWithLongPolling(
autoSkipTimeoutExceptions: Boolean = true,
mediaGroupsDebounceTimeMillis: Long? = 1000L,
subcontextInitialAction: CustomBehaviourContextAndTypeReceiver<BehaviourContext, Unit, Update> = {},
useDefaultSubcontextInitialAction: Boolean = true,
block: BehaviourContextReceiver<Unit>
): Job {
val behaviourContext = buildBehaviour(
scope = scope,
defaultExceptionsHandler = defaultExceptionsHandler,
subcontextInitialAction = subcontextInitialAction,
useDefaultSubcontextInitialAction = useDefaultSubcontextInitialAction,
block = block
)
return longPolling(

View File

@@ -6,6 +6,7 @@ import dev.inmo.kslog.common.KSLog
import dev.inmo.micro_utils.coroutines.*
import dev.inmo.tgbotapi.bot.TelegramBot
import dev.inmo.tgbotapi.extensions.behaviour_builder.utils.handlers_registrar.TriggersHolder
import dev.inmo.tgbotapi.extensions.behaviour_builder.utils.optionallyWithDefaultReceiver
import dev.inmo.tgbotapi.types.UpdateId
import dev.inmo.tgbotapi.types.update.abstracts.Update
import dev.inmo.tgbotapi.updateshandlers.*
@@ -24,6 +25,7 @@ typealias CustomBehaviourContextAndTwoTypesReceiver<BC, T, I1, I2> = suspend BC.
typealias BehaviourContextAndTwoTypesReceiver<T, I1, I2> = CustomBehaviourContextAndTwoTypesReceiver<BehaviourContext, T, I1, I2>
inline fun <T> BehaviourContextReceiver(noinline block: BehaviourContextReceiver<T>) = block
inline fun <BC, T> CustomBehaviourContextReceiver(noinline block: CustomBehaviourContextReceiver<BC, T>) = block
inline fun <BC, T, I> CustomBehaviourContextAndTypeReceiver(noinline block: CustomBehaviourContextAndTypeReceiver<BC, T, I>) = block
inline fun <T, I> BehaviourContextAndTypeReceiver(noinline block: BehaviourContextAndTypeReceiver<T, I>) = block
inline fun <T, I1, I2> BehaviourContextAndTwoTypesReceiver(noinline block: BehaviourContextAndTwoTypesReceiver<T, I1, I2>) = block
internal inline fun <BC, T, I1, I2> CustomBehaviourContextAndTwoTypesReceiver<BC, T, I1, I2>.toOneType(
@@ -134,8 +136,15 @@ fun BehaviourContext(
scope: CoroutineScope,
flowsUpdatesFilter: FlowsUpdatesFilter = FlowsUpdatesFilter(),
triggersHolder: TriggersHolder = TriggersHolder(),
useDefaultSubcontextInitialAction: Boolean = true,
subcontextInitialAction: CustomBehaviourContextAndTypeReceiver<BehaviourContext, Unit, Update> = {}
) = DefaultBehaviourContext(bot, scope, upstreamUpdatesFlow = flowsUpdatesFilter.allUpdatesFlow, triggersHolder = triggersHolder, subcontextInitialAction = subcontextInitialAction)
) = DefaultBehaviourContext(
bot = bot,
scope = scope,
upstreamUpdatesFlow = flowsUpdatesFilter.allUpdatesFlow,
triggersHolder = triggersHolder,
subcontextInitialAction = subcontextInitialAction.optionallyWithDefaultReceiver(useDefaultSubcontextInitialAction)
)
inline fun <T> BehaviourContext(
bot: TelegramBot,
@@ -143,8 +152,15 @@ inline fun <T> BehaviourContext(
flowsUpdatesFilter: FlowsUpdatesFilter = FlowsUpdatesFilter(),
triggersHolder: TriggersHolder = TriggersHolder(),
noinline subcontextInitialAction: CustomBehaviourContextAndTypeReceiver<BehaviourContext, Unit, Update> = {},
useDefaultSubcontextInitialAction: Boolean = true,
crossinline block: BehaviourContext.() -> T
) = DefaultBehaviourContext(bot, scope, upstreamUpdatesFlow = flowsUpdatesFilter.allUpdatesFlow, triggersHolder = triggersHolder, subcontextInitialAction = subcontextInitialAction).run(block)
) = DefaultBehaviourContext(
bot = bot,
scope = scope,
upstreamUpdatesFlow = flowsUpdatesFilter.allUpdatesFlow,
triggersHolder = triggersHolder,
subcontextInitialAction = subcontextInitialAction.optionallyWithDefaultReceiver(useDefaultSubcontextInitialAction)
).run(block)
/**
* Creates new [BehaviourContext] using its [BehaviourContext.copy] method

View File

@@ -39,6 +39,7 @@ suspend fun telegramBotWithBehaviour(
testServer: Boolean = false,
subcontextInitialAction: CustomBehaviourContextAndTypeReceiver<BehaviourContext, Unit, Update> = {},
fileLinkUrlMapper: TelegramAPIUrlsKeeper.(String) -> String = { "${fileBaseUrl}/$it" },
useDefaultSubcontextInitialAction: Boolean = true,
block: BehaviourContextReceiver<Unit>
): TelegramBot = telegramBot(
token,
@@ -52,6 +53,7 @@ suspend fun telegramBotWithBehaviour(
scope = scope ?: CoroutineScope(coroutineContext),
defaultExceptionsHandler = defaultExceptionsHandler,
subcontextInitialAction = subcontextInitialAction,
useDefaultSubcontextInitialAction = useDefaultSubcontextInitialAction,
block = block
)
}
@@ -86,6 +88,7 @@ suspend fun telegramBotWithBehaviourAndLongPolling(
mediaGroupsDebounceTimeMillis: Long? = 1000L,
subcontextInitialAction: CustomBehaviourContextAndTypeReceiver<BehaviourContext, Unit, Update> = {},
fileLinkUrlMapper: TelegramAPIUrlsKeeper.(String) -> String = { "${fileBaseUrl}/$it" },
useDefaultSubcontextInitialAction: Boolean = true,
block: BehaviourContextReceiver<Unit>
): Pair<TelegramBot, Job> {
return telegramBot(
@@ -103,6 +106,7 @@ suspend fun telegramBotWithBehaviourAndLongPolling(
autoSkipTimeoutExceptions = autoSkipTimeoutExceptions,
mediaGroupsDebounceTimeMillis = mediaGroupsDebounceTimeMillis,
subcontextInitialAction = subcontextInitialAction,
useDefaultSubcontextInitialAction = useDefaultSubcontextInitialAction,
block = block
)
}

View File

@@ -0,0 +1,102 @@
package dev.inmo.tgbotapi.extensions.behaviour_builder.utils
import dev.inmo.micro_utils.common.Warning
import dev.inmo.tgbotapi.extensions.behaviour_builder.BehaviourContext
import dev.inmo.tgbotapi.extensions.behaviour_builder.CustomBehaviourContextAndTypeReceiver
import dev.inmo.tgbotapi.extensions.behaviour_builder.utils.DefaultCustomBehaviourContextAndTypeReceiver.Companion.BOT_INFO_RECEIVER
import dev.inmo.tgbotapi.requests.bot.GetMe
import dev.inmo.tgbotapi.types.chat.ExtendedBot
import dev.inmo.tgbotapi.types.update.abstracts.Update
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
/**
* Returns bot information (result of [GetMe]) associated with this [BehaviourContext], if available.
*
* The value is lazily computed and cached by [DefaultCustomBehaviourContextAndTypeReceiver] when it is used
* to wrap behaviour handlers. If this context was not prepared by that wrapper, the function returns null.
*
* Thread-safety:
* - The underlying retrieval is protected by a mutex to ensure the info is fetched at most once per context.
*
* @return [ExtendedBot] with bot details, or null if no bot info provider is registered in this context.
*/
suspend fun BehaviourContext.botInfo(): ExtendedBot? {
return (data[BOT_INFO_RECEIVER] as? DefaultCustomBehaviourContextAndTypeReceiver.IReceiver) ?.run {
invoke()
}
}
@Warning("It is internal API and can be changed without notes")
fun <BC : BehaviourContext, R, U : Update> CustomBehaviourContextAndTypeReceiver<BC, R, U>.withDefaultReceiver() = DefaultCustomBehaviourContextAndTypeReceiver(this)
@Warning("It is internal API and can be changed without notes")
fun <BC : BehaviourContext, R, U : Update> CustomBehaviourContextAndTypeReceiver<BC, R, U>.optionallyWithDefaultReceiver(
include: Boolean
) = if (include) {
withDefaultReceiver()
} else {
this
}
/**
* Behaviour wrapper that injects a lazily-evaluated, cached provider of bot information into the [BehaviourContext].
*
* When this wrapper is used, any code executed inside it may call [BehaviourContext.botInfo] to obtain
* the current bot's [ExtendedBot] information. The info is fetched via [GetMe] only once and then cached
* for subsequent calls, with concurrent access synchronized by a mutex.
*
* @param BC Type of [BehaviourContext] used in the wrapped logic.
* @param R Result type produced by the wrapped receiver.
* @param U Type of [Update] handled by the wrapped receiver.
* @param wrapperReceiver The original receiver to be invoked after the bot info provider is registered in the context.
*/
class DefaultCustomBehaviourContextAndTypeReceiver<BC : BehaviourContext, R, U : Update>(
private val wrapperReceiver: CustomBehaviourContextAndTypeReceiver<BC, R, U>
) : CustomBehaviourContextAndTypeReceiver<BC, R, U> {
private var botInfo: ExtendedBot? = null
private val mutex = Mutex()
/**
* Lightweight provider of bot information bound to a [BehaviourContext].
*
* Implementations must return the current [ExtendedBot] instance, computing it if necessary.
*/
fun interface IReceiver {
/**
* Get or compute the bot information for the current [BehaviourContext].
*
* Implementations may cache the value and are free to apply synchronization as needed.
*/
suspend fun BehaviourContext.invoke(): ExtendedBot
}
/**
* Internal provider that performs a single, thread-safe retrieval of bot info via [GetMe] and caches it.
*/
private val internalReceiver: IReceiver = IReceiver {
botInfo ?: mutex.withLock {
botInfo ?: execute(GetMe).also {
botInfo = it
}
}
}
/**
* Registers the internal bot info provider in [BehaviourContext.data] and then delegates to [wrapperReceiver].
*
* The provider is stored under [BOT_INFO_RECEIVER] key, enabling calls to [BehaviourContext.botInfo] within
* the wrapped behaviour.
*/
override suspend fun invoke(p1: BC, p2: U): R {
p1.data[BOT_INFO_RECEIVER] = internalReceiver
return wrapperReceiver(p1, p2)
}
companion object {
/**
* Key used to store the bot info provider inside [BehaviourContext.data].
*/
const val BOT_INFO_RECEIVER = "ktgbotapi_bot_info_receiver"
}
}