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

Compare commits

...

23 Commits

Author SHA1 Message Date
b873898100 wrap client request exception into exception handling 2022-08-25 13:35:15 +06:00
61ac9df5e3 BotException 2022-08-25 13:32:12 +06:00
b1931900e7 Update BotCommandTextSource.kt 2022-08-25 02:11:04 +06:00
fab3af48d6 Update WaitCommandsMessages.kt 2022-08-25 02:04:19 +06:00
8d7563b6e4 Update WaitCommandsMessages.kt 2022-08-25 02:02:45 +06:00
05112afe0c add deeplinks triggers 2022-08-24 15:32:34 +06:00
9ea06de27c add waitCommands* expectations 2022-08-24 15:03:54 +06:00
fff05a40d9 revert adding of mention waiters 2022-08-24 13:29:57 +06:00
5c6428f220 update microutils 2022-08-23 13:13:06 +06:00
766b7ca205 add waiters for mentions 2022-08-23 13:12:22 +06:00
41e6c52369 allowedUpdates is ALL_UPDATES_LIST by default everywhere 2022-08-23 11:55:28 +06:00
06013f624f update dependencies 2022-08-23 11:48:55 +06:00
d8bba89f3f start 3.1.2 2022-08-23 11:47:31 +06:00
141281f96d Merge pull request #643 from InsanusMokrassar/3.1.1
3.1.1
2022-08-15 01:31:59 +06:00
be7aaa7845 fixes and improvements in webapps 2022-08-15 01:29:24 +06:00
78c224ffa8 fix on asUser fun 2022-08-15 01:21:10 +06:00
a08d07f7b3 fixes in popup params and buttons 2022-08-15 01:20:29 +06:00
69dde19543 Update CHANGELOG.md 2022-08-14 22:13:03 +06:00
e8a3b93831 Update Extended.kt 2022-08-14 22:11:55 +06:00
e10caa3171 add support of has_restricted_voice_and_video_messages 2022-08-14 21:56:25 +06:00
d4fe4e09fc add support of Bot API 6.2 in webapp parts 2022-08-14 21:52:26 +06:00
ad453afba2 start 3.1.1 2022-08-14 18:55:08 +06:00
a0daca28b1 Merge pull request #642 from InsanusMokrassar/3.1.0
3.1.0
2022-08-13 14:44:00 +06:00
27 changed files with 510 additions and 70 deletions

View File

@@ -1,5 +1,23 @@
# TelegramBotAPI changelog # TelegramBotAPI changelog
## 3.1.2
* `Versions`:
* `Serialization`: `1.4.0-RC` -> `1.4.0`
* `MicroUtils`: `0.12.1` -> `0.12.4`
* `Core`:
* `SetWebhook#allowedUpdates` now is `ALL_UPDATES_LIST` by default instead of `null`
* `KtorRequestsExecutor#execute` now will __always__ throw `BotException` if something went wrong inside
* `API`:
* Extension `TelegramBot#setWebhook` parameter `allowedUpdates` now is `ALL_UPDATES_LIST` by default instead of `null`
* `Utils`:
* All related to long polling extensions parameters `allowedUpdates` now are `ALL_UPDATES_LIST` by default instead of `null`
## 3.1.1
* `Common`:
* Complete Bot API 6.2 implementation
## 3.1.0 ## 3.1.0
**This update contains including of Bot API 6.2** **This update contains including of Bot API 6.2**

View File

@@ -6,4 +6,4 @@ kotlin.incremental=true
kotlin.incremental.js=true kotlin.incremental.js=true
library_group=dev.inmo library_group=dev.inmo
library_version=3.1.0 library_version=3.1.2

View File

@@ -1,7 +1,7 @@
[versions] [versions]
kotlin = "1.7.10" kotlin = "1.7.10"
kotlin-serialization = "1.4.0-RC" kotlin-serialization = "1.4.0"
kotlin-coroutines = "1.6.4" kotlin-coroutines = "1.6.4"
javax-activation = "1.1.1" javax-activation = "1.1.1"
@@ -13,7 +13,7 @@ ktor = "2.1.0"
ksp = "1.7.10-1.0.6" ksp = "1.7.10-1.0.6"
kotlin-poet = "1.12.0" kotlin-poet = "1.12.0"
microutils = "0.12.1" microutils = "0.12.4"
github-release-plugin = "2.4.1" github-release-plugin = "2.4.1"

View File

@@ -4,6 +4,7 @@ import dev.inmo.tgbotapi.bot.TelegramBot
import dev.inmo.tgbotapi.requests.abstracts.FileId import dev.inmo.tgbotapi.requests.abstracts.FileId
import dev.inmo.tgbotapi.requests.abstracts.MultipartFile import dev.inmo.tgbotapi.requests.abstracts.MultipartFile
import dev.inmo.tgbotapi.requests.webhook.SetWebhook import dev.inmo.tgbotapi.requests.webhook.SetWebhook
import dev.inmo.tgbotapi.types.ALL_UPDATES_LIST
/** /**
* Use this method to send information about webhook (like [url]) * Use this method to send information about webhook (like [url])
@@ -12,7 +13,7 @@ suspend fun TelegramBot.setWebhookInfo(
url: String, url: String,
ipAddress: String? = null, ipAddress: String? = null,
maxAllowedConnections: Int? = null, maxAllowedConnections: Int? = null,
allowedUpdates: List<String>? = null, allowedUpdates: List<String>? = ALL_UPDATES_LIST,
dropPendingUpdates: Boolean? = null, dropPendingUpdates: Boolean? = null,
secretToken: String? = null secretToken: String? = null
) = execute( ) = execute(
@@ -29,7 +30,7 @@ suspend fun TelegramBot.setWebhookInfo(
certificate: FileId, certificate: FileId,
ipAddress: String? = null, ipAddress: String? = null,
maxAllowedConnections: Int? = null, maxAllowedConnections: Int? = null,
allowedUpdates: List<String>? = null, allowedUpdates: List<String>? = ALL_UPDATES_LIST,
dropPendingUpdates: Boolean? = null, dropPendingUpdates: Boolean? = null,
secretToken: String? = null secretToken: String? = null
) = execute( ) = execute(
@@ -46,7 +47,7 @@ suspend fun TelegramBot.setWebhookInfo(
certificate: MultipartFile, certificate: MultipartFile,
ipAddress: String? = null, ipAddress: String? = null,
maxAllowedConnections: Int? = null, maxAllowedConnections: Int? = null,
allowedUpdates: List<String>? = null, allowedUpdates: List<String>? = ALL_UPDATES_LIST,
dropPendingUpdates: Boolean? = null, dropPendingUpdates: Boolean? = null,
secretToken: String? = null secretToken: String? = null
) = execute( ) = execute(

View File

@@ -0,0 +1,119 @@
package dev.inmo.tgbotapi.extensions.behaviour_builder.expectations
import dev.inmo.tgbotapi.extensions.behaviour_builder.BehaviourContext
import dev.inmo.tgbotapi.extensions.behaviour_builder.utils.handlers_registrar.doWithRegistration
import dev.inmo.tgbotapi.extensions.utils.*
import dev.inmo.tgbotapi.requests.abstracts.Request
import dev.inmo.tgbotapi.types.message.abstracts.CommonMessage
import dev.inmo.tgbotapi.types.message.content.TextContent
import dev.inmo.tgbotapi.types.message.textsources.BotCommandTextSource
import dev.inmo.tgbotapi.types.message.textsources.TextSource
import kotlinx.coroutines.flow.*
/**
* Will filter all the messages and include required commands with [commandRegex].
*
* * In case you wish to get only the commands at the start of message, use [requireCommandAtStart]
* * In case you wish to exclude messages with more than one command, you may use [requireSingleCommand]
* * In case you wish to exclude messages with commands params, you may use [requireCommandsWithoutParams]
*/
suspend fun BehaviourContext.waitCommandMessage(
commandRegex: Regex,
initRequest: Request<*>? = null,
errorFactory: NullableRequestBuilder<*> = { null }
) = channelFlow {
triggersHolder.handleableCommandsHolder.doWithRegistration(
commandRegex
) {
waitTextMessage(initRequest, errorFactory).filter {
it.content.textSources.any { it.botCommandTextSourceOrNull() ?.command ?.matches(commandRegex) == true }
}.collect {
send(it)
}
}
}
suspend fun BehaviourContext.waitCommandMessage(
command: String,
initRequest: Request<*>? = null,
errorFactory: NullableRequestBuilder<*> = { null }
) = waitCommandMessage(Regex(command), initRequest, errorFactory)
fun Flow<CommonMessage<TextContent>>.requireCommandAtStart() = filter {
it.content.textSources.firstOrNull() is BotCommandTextSource
}
/**
* Subsequent [Flow] will retrieve only messages with ONE [BotCommandTextSource]. It does not guarantee that this
* [BotCommandTextSource] will be at the start of the message
*
* @see requireCommandAtStart
*/
fun Flow<CommonMessage<TextContent>>.requireSingleCommand() = filter {
var count = 0
it.content.textSources.forEach {
if (it is BotCommandTextSource) {
count++
if (count > 1) {
return@filter false
}
}
}
count == 1
}
/**
* Subsequent [Flow] will retrieve only messages without [TextContent.textSources] which are not [BotCommandTextSource]
*/
fun Flow<CommonMessage<TextContent>>.requireCommandsWithoutParams() = filter {
it.content.textSources.none { it !is BotCommandTextSource }
}
/**
* Map the commands with their arguments and source messages
*/
fun Flow<CommonMessage<TextContent>>.commandsWithParams(): Flow<Pair<CommonMessage<TextContent>, List<Pair<BotCommandTextSource, Array<TextSource>>>>> = mapNotNull {
var currentCommandTextSource: BotCommandTextSource? = null
val currentArgs = mutableListOf<TextSource>()
val result = mutableListOf<Pair<BotCommandTextSource, Array<TextSource>>>()
fun addCurrentCommandToResult() {
currentCommandTextSource ?.let {
result.add(it to currentArgs.toTypedArray())
currentArgs.clear()
}
}
it.content.textSources.forEach {
it.ifBotCommandTextSource {
addCurrentCommandToResult()
currentCommandTextSource = it
return@forEach
}
currentArgs.add(it)
}
addCurrentCommandToResult()
result.toList().takeIf { it.isNotEmpty() } ?.let { result ->
it to result
}
}
/**
* Flat [commandsWithParams]. Each [Pair] of [BotCommandTextSource] and its [Array] of arg text sources will
* be associated with its source message
*/
fun Flow<CommonMessage<TextContent>>.flattenCommandsWithParams() = commandsWithParams().flatMapConcat { (message, commandsWithParams) ->
commandsWithParams.map {
message to it
}.asFlow()
}
/**
* Use [flattenCommandsWithParams] and filter out the commands which do not [matches] to [commandRegex]
*/
fun Flow<CommonMessage<TextContent>>.commandParams(commandRegex: Regex) = flattenCommandsWithParams().filter { (_, commandWithParams) ->
commandWithParams.first.command.matches(commandRegex)
}

View File

@@ -0,0 +1,23 @@
package dev.inmo.tgbotapi.extensions.behaviour_builder.expectations
import dev.inmo.tgbotapi.extensions.behaviour_builder.BehaviourContext
import dev.inmo.tgbotapi.extensions.utils.regularTextSourceOrNull
import dev.inmo.tgbotapi.requests.abstracts.Request
import dev.inmo.tgbotapi.types.message.abstracts.CommonMessage
import dev.inmo.tgbotapi.types.message.content.TextContent
import dev.inmo.tgbotapi.types.message.textsources.RegularTextSource
import kotlinx.coroutines.flow.*
suspend fun BehaviourContext.waitDeepLinks(
initRequest: Request<*>? = null,
errorFactory: NullableRequestBuilder<*> = { null },
): Flow<Pair<CommonMessage<TextContent>, String>> = waitCommandMessage(
"start",
initRequest,
errorFactory
)
.requireSingleCommand()
.requireCommandAtStart()
.flattenCommandsWithParams().mapNotNull {
it.first to (it.second.second.singleOrNull() ?.regularTextSourceOrNull() ?.source ?: return@mapNotNull null)
}

View File

@@ -0,0 +1,41 @@
@file:Suppress("unused")
package dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling
import dev.inmo.micro_utils.coroutines.*
import dev.inmo.tgbotapi.extensions.behaviour_builder.*
import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitDeepLinks
import dev.inmo.tgbotapi.extensions.behaviour_builder.filters.CommonMessageFilterExcludeMediaGroups
import dev.inmo.tgbotapi.extensions.behaviour_builder.filters.MessageFilterByChat
import dev.inmo.tgbotapi.extensions.behaviour_builder.utils.SimpleFilter
import dev.inmo.tgbotapi.extensions.behaviour_builder.utils.marker_factories.ByChatMessageMarkerFactory
import dev.inmo.tgbotapi.extensions.behaviour_builder.utils.marker_factories.MarkerFactory
import dev.inmo.tgbotapi.extensions.behaviour_builder.utils.times
import dev.inmo.tgbotapi.extensions.utils.*
import dev.inmo.tgbotapi.extensions.utils.extensions.parseCommandsWithParams
import dev.inmo.tgbotapi.types.message.content.TextContent
import dev.inmo.tgbotapi.types.message.content.TextMessage
import dev.inmo.tgbotapi.types.message.textsources.RegularTextSource
import dev.inmo.tgbotapi.types.update.abstracts.Update
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.filter
suspend fun <BC : BehaviourContext> BC.onDeepLink(
initialFilter: SimpleFilter<Pair<TextMessage, String>>? = null,
subcontextUpdatesFilter: CustomBehaviourContextAndTwoTypesReceiver<BC, Boolean, Pair<TextMessage, String>, Update> = { (message, _), update -> MessageFilterByChat(this, message, update) },
markerFactory: MarkerFactory<Pair<TextMessage, String>, Any> = MarkerFactory { (message, _) -> ByChatMessageMarkerFactory(message) },
scenarioReceiver: CustomBehaviourContextAndTypeReceiver<BC, Unit, Pair<TextMessage, String>>
): Job = on(
markerFactory,
SimpleFilter<Pair<TextMessage, String>> { (message, _) ->
message.content.textSources.size == 2
&& message.content.textSources.firstOrNull() ?.asBotCommandTextSource() ?.command == "start"
&& message.content.textSources.getOrNull(1) is RegularTextSource
} * initialFilter,
subcontextUpdatesFilter,
scenarioReceiver,
) {
(it.messageUpdateOrNull()) ?.data ?.commonMessageOrNull() ?.withContentOrNull<TextContent>() ?.let { message ->
message to message.content.textSources[1].source
} ?.let(::listOfNotNull)
}

View File

@@ -4,6 +4,7 @@ fun interface SimpleFilter<in T> {
suspend operator fun invoke(o: T): Boolean suspend operator fun invoke(o: T): Boolean
} }
val TrueSimpleFilter = SimpleFilter<Any?> { true } val TrueSimpleFilter = SimpleFilter<Any?> { true }
val FalseSimpleFilter = SimpleFilter<Any?> { false }
/** /**
* @return [SimpleFilter] which will return true in case when all the items in incoming data passed [this] filter * @return [SimpleFilter] which will return true in case when all the items in incoming data passed [this] filter
@@ -28,21 +29,29 @@ fun <T> SimpleFilter<T>.listNone() = SimpleFilter<Iterable<T>> {
/** /**
* Makes an AND (&&) operation between [this] and [other] * Makes an AND (&&) operation between [this] and [other]
*
* * When both arguments are null, [TrueSimpleFilter] will be returned
*/ */
operator fun <T> SimpleFilter<T>?.times(other: SimpleFilter<T>): SimpleFilter<T> = this ?.let { infix operator fun <T> SimpleFilter<T>?.times(other: SimpleFilter<T>?): SimpleFilter<T> = this ?.let {
SimpleFilter { other ?.let {
this(it) && other(it) SimpleFilter {
} this(it) && other(it)
} ?: other }
} ?: it
} ?: other ?: TrueSimpleFilter
/** /**
* Makes an OR (||) operation between [this] and [other] * Makes an OR (||) operation between [this] and [other]
*
* * When both arguments are null, [TrueSimpleFilter] will be returned
*/ */
operator fun <T> SimpleFilter<T>?.plus(other: SimpleFilter<T>): SimpleFilter<T> = this ?.let { infix operator fun <T> SimpleFilter<T>?.plus(other: SimpleFilter<T>?): SimpleFilter<T> = this ?.let {
SimpleFilter { other ?.let {
this(it) || other(it) SimpleFilter {
} this(it) || other(it)
} ?: other }
} ?: it
} ?: other ?: TrueSimpleFilter
/** /**
* Reverse results of [this] * Reverse results of [this]

View File

@@ -1,5 +1,6 @@
package dev.inmo.tgbotapi.extensions.behaviour_builder.utils.handlers_registrar package dev.inmo.tgbotapi.extensions.behaviour_builder.utils.handlers_registrar
import dev.inmo.micro_utils.coroutines.runCatchingSafely
import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.sync.withLock
@@ -7,6 +8,7 @@ open class HandleableTriggersHolder<T>(
preset: List<T> = emptyList() preset: List<T> = emptyList()
) { ) {
protected val commandsMutex = Mutex() protected val commandsMutex = Mutex()
protected val handleableCounts = mutableMapOf<T, Int>()
protected val _handleable = mutableListOf<T>().also { protected val _handleable = mutableListOf<T>().also {
it.addAll(preset) it.addAll(preset)
} }
@@ -16,12 +18,31 @@ open class HandleableTriggersHolder<T>(
suspend fun registerHandleable(data: T) { suspend fun registerHandleable(data: T) {
commandsMutex.withLock { commandsMutex.withLock {
_handleable.add(data) _handleable.add(data)
handleableCounts[data] = (handleableCounts[data] ?: 0) + 1
} }
} }
suspend fun unregisterHandleable(data: T) { suspend fun unregisterHandleable(data: T) {
commandsMutex.withLock { commandsMutex.withLock {
_handleable.remove(data) val newHandleableCount = (handleableCounts[data] ?: 0) - 1
if (newHandleableCount > 0) {
handleableCounts[data] = newHandleableCount
} else {
handleableCounts.remove(data)
_handleable.remove(data)
}
} }
} }
} }
suspend fun <T, R> HandleableTriggersHolder<T>.doWithRegistration(
data: T,
block: suspend () -> R
): R {
registerHandleable(data)
val result = runCatchingSafely {
block()
}
unregisterHandleable(data)
return result.getOrThrow()
}

View File

@@ -35,13 +35,18 @@ fun newRequestException(
} }
} ?: CommonRequestException(response, plainAnswer, message, cause) } ?: CommonRequestException(response, plainAnswer, message, cause)
sealed class BotException(message: String = "Something went wrong", cause: Throwable? = null) : IOException(message, cause)
class CommonBotException(message: String = "Something went wrong", cause: Throwable? = null) : BotException(message, cause)
sealed class RequestException constructor( sealed class RequestException constructor(
val response: Response, val response: Response,
val plainAnswer: String, val plainAnswer: String,
message: String? = null, message: String? = null,
override val cause: Throwable? = null cause: Throwable? = null
) : IOException( ) : BotException(
message ?: "Something went wrong" message ?: "Something went wrong",
cause
) )
class CommonRequestException(response: Response, plainAnswer: String, message: String?, cause: Throwable?) : class CommonRequestException(response: Response, plainAnswer: String, message: String?, cause: Throwable?) :

View File

@@ -1,9 +1,10 @@
package dev.inmo.tgbotapi.bot.ktor package dev.inmo.tgbotapi.bot.ktor
import dev.inmo.micro_utils.coroutines.runCatchingSafely
import dev.inmo.micro_utils.coroutines.safely import dev.inmo.micro_utils.coroutines.safely
import dev.inmo.tgbotapi.bot.BaseRequestsExecutor import dev.inmo.tgbotapi.bot.BaseRequestsExecutor
import dev.inmo.tgbotapi.bot.TelegramBot import dev.inmo.tgbotapi.bot.TelegramBot
import dev.inmo.tgbotapi.bot.exceptions.newRequestException import dev.inmo.tgbotapi.bot.exceptions.*
import dev.inmo.tgbotapi.bot.ktor.base.* import dev.inmo.tgbotapi.bot.ktor.base.*
import dev.inmo.tgbotapi.bot.settings.limiters.ExceptionsOnlyLimiter import dev.inmo.tgbotapi.bot.settings.limiters.ExceptionsOnlyLimiter
import dev.inmo.tgbotapi.bot.settings.limiters.RequestLimiter import dev.inmo.tgbotapi.bot.settings.limiters.RequestLimiter
@@ -48,12 +49,36 @@ class KtorRequestsExecutor(
} }
override suspend fun <T : Any> execute(request: Request<T>): T { override suspend fun <T : Any> execute(request: Request<T>): T {
return runCatching { return runCatchingSafely {
safely( pipelineStepsHolder.onBeforeSearchCallFactory(request, callsFactories)
{ e -> requestsLimiter.limit {
pipelineStepsHolder.onRequestException(request, e) ?.let { return@safely it } var result: T? = null
lateinit var factoryHandledRequest: KtorCallFactory
for (potentialFactory in callsFactories) {
pipelineStepsHolder.onBeforeCallFactoryMakeCall(request, potentialFactory)
result = potentialFactory.makeCall(
client,
telegramAPIUrlsKeeper,
request,
jsonFormatter
)
result = pipelineStepsHolder.onAfterCallFactoryMakeCall(result, request, potentialFactory)
if (result != null) {
factoryHandledRequest = potentialFactory
break
}
}
throw if (e is ClientRequestException) { result ?.let {
pipelineStepsHolder.onRequestResultPresented(it, request, factoryHandledRequest, callsFactories)
} ?: pipelineStepsHolder.onRequestResultAbsent(request, callsFactories) ?: error("Can't execute request: $request")
}
}.let {
val result = it.exceptionOrNull() ?.let { e ->
pipelineStepsHolder.onRequestException(request, e) ?.let { return@let it }
if (e is ClientRequestException) {
val exceptionResult = runCatchingSafely {
val content = e.response.bodyAsText() val content = e.response.bodyAsText()
val responseObject = jsonFormatter.decodeFromString(Response.serializer(), content) val responseObject = jsonFormatter.decodeFromString(Response.serializer(), content)
newRequestException( newRequestException(
@@ -61,38 +86,15 @@ class KtorRequestsExecutor(
content, content,
"Can't get result object from $content" "Can't get result object from $content"
) )
} else {
e
} }
exceptionResult.exceptionOrNull() ?.let {
CommonBotException(cause = e)
} ?: exceptionResult.getOrThrow()
} else {
CommonBotException(cause = e)
} }
) { } ?.let { Result.failure(it) } ?: it
pipelineStepsHolder.onBeforeSearchCallFactory(request, callsFactories) pipelineStepsHolder.onRequestReturnResult(result, request, callsFactories)
requestsLimiter.limit {
var result: T? = null
lateinit var factoryHandledRequest: KtorCallFactory
for (potentialFactory in callsFactories) {
pipelineStepsHolder.onBeforeCallFactoryMakeCall(request, potentialFactory)
result = potentialFactory.makeCall(
client,
telegramAPIUrlsKeeper,
request,
jsonFormatter
)
result = pipelineStepsHolder.onAfterCallFactoryMakeCall(result, request, potentialFactory)
if (result != null) {
factoryHandledRequest = potentialFactory
break
}
}
result ?.let {
pipelineStepsHolder.onRequestResultPresented(it, request, factoryHandledRequest, callsFactories)
} ?: pipelineStepsHolder.onRequestResultAbsent(request, callsFactories) ?: error("Can't execute request: $request")
}
}
}.let {
pipelineStepsHolder.onRequestReturnResult(it, request, callsFactories)
} }
} }

View File

@@ -19,7 +19,7 @@ class MultipartSetWebhookRequest(
certificate: MultipartFile, certificate: MultipartFile,
ipAddress: String? = null, ipAddress: String? = null,
maxAllowedConnections: Int? = null, maxAllowedConnections: Int? = null,
allowedUpdates: List<String>? = null, allowedUpdates: List<String>? = ALL_UPDATES_LIST,
dropPendingUpdates: Boolean? = null, dropPendingUpdates: Boolean? = null,
secretToken: String? = null secretToken: String? = null
) : SetWebhookRequest(), MultipartRequest<Boolean> by MultipartRequestImpl( ) : SetWebhookRequest(), MultipartRequest<Boolean> by MultipartRequestImpl(
@@ -40,7 +40,7 @@ fun SetWebhook(
certificate: MultipartFile, certificate: MultipartFile,
ipAddress: String? = null, ipAddress: String? = null,
maxAllowedConnections: Int? = null, maxAllowedConnections: Int? = null,
allowedUpdates: List<String>? = null, allowedUpdates: List<String>? = ALL_UPDATES_LIST,
dropPendingUpdates: Boolean? = null, dropPendingUpdates: Boolean? = null,
secretToken: String? = null secretToken: String? = null
): MultipartSetWebhookRequest = MultipartSetWebhookRequest( ): MultipartSetWebhookRequest = MultipartSetWebhookRequest(
@@ -58,7 +58,7 @@ fun SetWebhook(
certificate: FileId, certificate: FileId,
ipAddress: String? = null, ipAddress: String? = null,
maxAllowedConnections: Int? = null, maxAllowedConnections: Int? = null,
allowedUpdates: List<String>? = null, allowedUpdates: List<String>? = ALL_UPDATES_LIST,
dropPendingUpdates: Boolean? = null, dropPendingUpdates: Boolean? = null,
secretToken: String? = null secretToken: String? = null
): SetWebhook = SetWebhook( ): SetWebhook = SetWebhook(
@@ -84,7 +84,7 @@ fun SetWebhook(
certificate: InputFile, certificate: InputFile,
ipAddress: String? = null, ipAddress: String? = null,
maxAllowedConnections: Int? = null, maxAllowedConnections: Int? = null,
allowedUpdates: List<String>? = null, allowedUpdates: List<String>? = ALL_UPDATES_LIST,
dropPendingUpdates: Boolean? = null, dropPendingUpdates: Boolean? = null,
secretToken: String? = null secretToken: String? = null
) = when (certificate) { ) = when (certificate) {
@@ -104,7 +104,7 @@ fun SetWebhook(
url: String, url: String,
ipAddress: String? = null, ipAddress: String? = null,
maxAllowedConnections: Int? = null, maxAllowedConnections: Int? = null,
allowedUpdates: List<String>? = null, allowedUpdates: List<String>? = ALL_UPDATES_LIST,
dropPendingUpdates: Boolean? = null, dropPendingUpdates: Boolean? = null,
secretToken: String? = null secretToken: String? = null
) = SetWebhook( ) = SetWebhook(
@@ -135,7 +135,7 @@ data class SetWebhook internal constructor(
@SerialName(maxAllowedConnectionsField) @SerialName(maxAllowedConnectionsField)
val maxAllowedConnections: Int? = null, val maxAllowedConnections: Int? = null,
@SerialName(allowedUpdatesField) @SerialName(allowedUpdatesField)
val allowedUpdates: List<String>? = null, val allowedUpdates: List<String>? = ALL_UPDATES_LIST,
@SerialName(dropPendingUpdatesField) @SerialName(dropPendingUpdatesField)
val dropPendingUpdates: Boolean? = null, val dropPendingUpdates: Boolean? = null,
@SerialName(secretTokenField) @SerialName(secretTokenField)

View File

@@ -81,6 +81,8 @@ sealed interface StickerType {
} }
} }
val usernameRegex = Regex("@[\\w\\d_]+")
val degreesLimit = 1 .. 360 val degreesLimit = 1 .. 360
val horizontalAccuracyLimit = 0F .. 1500F val horizontalAccuracyLimit = 0F .. 1500F
@@ -164,6 +166,7 @@ const val languageCodeField = "language_code"
const val addedToAttachmentMenuField = "added_to_attachment_menu" const val addedToAttachmentMenuField = "added_to_attachment_menu"
const val isPremiumField = "is_premium" const val isPremiumField = "is_premium"
const val hasPrivateForwardsField = "has_private_forwards" const val hasPrivateForwardsField = "has_private_forwards"
const val hasRestrictedVoiceAndVideoMessagesField = "has_restricted_voice_and_video_messages"
const val canJoinGroupsField = "can_join_groups" const val canJoinGroupsField = "can_join_groups"
const val canReadAllGroupMessagesField = "can_read_all_group_messages" const val canReadAllGroupMessagesField = "can_read_all_group_messages"
const val supportInlineQueriesField = "supports_inline_queries" const val supportInlineQueriesField = "supports_inline_queries"

View File

@@ -62,7 +62,9 @@ data class ExtendedPrivateChatImpl(
@SerialName(bioField) @SerialName(bioField)
override val bio: String = "", override val bio: String = "",
@SerialName(hasPrivateForwardsField) @SerialName(hasPrivateForwardsField)
override val hasPrivateForwards: Boolean = false override val hasPrivateForwards: Boolean = false,
@SerialName(hasRestrictedVoiceAndVideoMessagesField)
override val hasRestrictedVoiceAndVideoMessages: Boolean = false
) : ExtendedPrivateChat ) : ExtendedPrivateChat
typealias ExtendedUser = ExtendedPrivateChatImpl typealias ExtendedUser = ExtendedPrivateChatImpl

View File

@@ -19,6 +19,7 @@ sealed interface ExtendedGroupChat : GroupChat, ExtendedPublicChat {
sealed interface ExtendedPrivateChat : PrivateChat, ExtendedChat { sealed interface ExtendedPrivateChat : PrivateChat, ExtendedChat {
val bio: String val bio: String
val hasPrivateForwards: Boolean val hasPrivateForwards: Boolean
val hasRestrictedVoiceAndVideoMessages: Boolean
val allowCreateUserIdLink: Boolean val allowCreateUserIdLink: Boolean
get() = hasPrivateForwards get() = hasPrivateForwards

View File

@@ -1,5 +1,7 @@
package dev.inmo.tgbotapi.types.message.textsources package dev.inmo.tgbotapi.types.message.textsources
import dev.inmo.tgbotapi.types.usernameRegex
import dev.inmo.tgbotapi.types.Username
import dev.inmo.tgbotapi.utils.RiskFeature import dev.inmo.tgbotapi.utils.RiskFeature
import dev.inmo.tgbotapi.utils.internal.* import dev.inmo.tgbotapi.utils.internal.*
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
@@ -16,6 +18,9 @@ data class BotCommandTextSource @RiskFeature(DirectInvocationOfTextSourceConstru
val command: String by lazy { val command: String by lazy {
commandRegex.find(source) ?.value ?.substring(1) ?: source.substring(1)// skip first symbol like "/" or "!" commandRegex.find(source) ?.value ?.substring(1) ?: source.substring(1)// skip first symbol like "/" or "!"
} }
val username: Username? by lazy {
Username(usernameRegex.find(source) ?.value ?: return@lazy null)
}
override val markdown: String by lazy { source.commandMarkdown() } override val markdown: String by lazy { source.commandMarkdown() }
override val markdownV2: String by lazy { source.commandMarkdownV2() } override val markdownV2: String by lazy { source.commandMarkdownV2() }

View File

@@ -30,7 +30,7 @@ fun <T> Flow<Iterable<T>>.flatten(): Flow<T> = flow {
} }
} }
fun <T, R> Flow<T>.flatMap(mapper: (T) -> Iterable<R>): Flow<R> = flow { fun <T, R> Flow<T>.flatMap(mapper: suspend (T) -> Iterable<R>): Flow<R> = flow {
collect { collect {
mapper(it).forEach { mapper(it).forEach {
emit(it) emit(it)

View File

@@ -21,7 +21,7 @@ import kotlinx.coroutines.flow.*
fun TelegramBot.longPollingFlow( fun TelegramBot.longPollingFlow(
timeoutSeconds: Seconds = 30, timeoutSeconds: Seconds = 30,
exceptionsHandler: (ExceptionHandler<Unit>)? = null, exceptionsHandler: (ExceptionHandler<Unit>)? = null,
allowedUpdates: List<String>? = null, allowedUpdates: List<String>? = ALL_UPDATES_LIST,
): Flow<Update> = channelFlow { ): Flow<Update> = channelFlow {
var lastUpdateIdentifier: UpdateIdentifier? = null var lastUpdateIdentifier: UpdateIdentifier? = null
@@ -81,7 +81,7 @@ fun TelegramBot.startGettingOfUpdatesByLongPolling(
timeoutSeconds: Seconds = 30, timeoutSeconds: Seconds = 30,
scope: CoroutineScope = CoroutineScope(Dispatchers.Default), scope: CoroutineScope = CoroutineScope(Dispatchers.Default),
exceptionsHandler: (ExceptionHandler<Unit>)? = null, exceptionsHandler: (ExceptionHandler<Unit>)? = null,
allowedUpdates: List<String>? = null, allowedUpdates: List<String>? = ALL_UPDATES_LIST,
updatesReceiver: UpdateReceiver<Update> updatesReceiver: UpdateReceiver<Update>
): Job = longPollingFlow(timeoutSeconds, exceptionsHandler, allowedUpdates).subscribeSafely( ): Job = longPollingFlow(timeoutSeconds, exceptionsHandler, allowedUpdates).subscribeSafely(
scope, scope,
@@ -97,7 +97,7 @@ fun TelegramBot.createAccumulatedUpdatesRetrieverFlow(
avoidInlineQueries: Boolean = false, avoidInlineQueries: Boolean = false,
avoidCallbackQueries: Boolean = false, avoidCallbackQueries: Boolean = false,
exceptionsHandler: ExceptionHandler<Unit>? = null, exceptionsHandler: ExceptionHandler<Unit>? = null,
allowedUpdates: List<String>? = null allowedUpdates: List<String>? = ALL_UPDATES_LIST
): Flow<Update> = longPollingFlow( ): Flow<Update> = longPollingFlow(
timeoutSeconds = 0, timeoutSeconds = 0,
exceptionsHandler = { exceptionsHandler = {
@@ -117,7 +117,7 @@ fun TelegramBot.retrieveAccumulatedUpdates(
avoidCallbackQueries: Boolean = false, avoidCallbackQueries: Boolean = false,
scope: CoroutineScope = CoroutineScope(Dispatchers.Default), scope: CoroutineScope = CoroutineScope(Dispatchers.Default),
exceptionsHandler: (ExceptionHandler<Unit>)? = null, exceptionsHandler: (ExceptionHandler<Unit>)? = null,
allowedUpdates: List<String>? = null, allowedUpdates: List<String>? = ALL_UPDATES_LIST,
updatesReceiver: UpdateReceiver<Update> updatesReceiver: UpdateReceiver<Update>
): Job = createAccumulatedUpdatesRetrieverFlow( ): Job = createAccumulatedUpdatesRetrieverFlow(
avoidInlineQueries, avoidInlineQueries,
@@ -149,7 +149,7 @@ suspend fun TelegramBot.flushAccumulatedUpdates(
avoidInlineQueries: Boolean = false, avoidInlineQueries: Boolean = false,
avoidCallbackQueries: Boolean = false, avoidCallbackQueries: Boolean = false,
scope: CoroutineScope = CoroutineScope(Dispatchers.Default), scope: CoroutineScope = CoroutineScope(Dispatchers.Default),
allowedUpdates: List<String>? = null, allowedUpdates: List<String>? = ALL_UPDATES_LIST,
exceptionsHandler: ExceptionHandler<Unit>? = null, exceptionsHandler: ExceptionHandler<Unit>? = null,
updatesReceiver: UpdateReceiver<Update> = {} updatesReceiver: UpdateReceiver<Update> = {}
) = retrieveAccumulatedUpdates( ) = retrieveAccumulatedUpdates(

View File

@@ -0,0 +1,3 @@
package dev.inmo.tgbotapi.webapps
typealias AlertCallback = () -> Unit

View File

@@ -0,0 +1,3 @@
package dev.inmo.tgbotapi.webapps
typealias ConfirmCallback = (confirmed: Boolean) -> Unit

View File

@@ -5,3 +5,4 @@ import dev.inmo.tgbotapi.webapps.invoice.InvoiceClosedInfo
typealias EventHandler = WebApp.() -> Unit typealias EventHandler = WebApp.() -> Unit
typealias ViewportChangedEventHandler = WebApp.(ViewportChangedData) -> Unit typealias ViewportChangedEventHandler = WebApp.(ViewportChangedData) -> Unit
typealias InvoiceClosedEventHandler = WebApp.(InvoiceClosedInfo) -> Unit typealias InvoiceClosedEventHandler = WebApp.(InvoiceClosedInfo) -> Unit
typealias PopupClosedEventHandler = WebApp.(String?) -> Unit

View File

@@ -7,4 +7,5 @@ sealed class EventType(val typeName: String) {
object BackButtonClicked : EventType("backButtonClicked") object BackButtonClicked : EventType("backButtonClicked")
object SettingsButtonClicked : EventType("settingsButtonClicked") object SettingsButtonClicked : EventType("settingsButtonClicked")
object InvoiceClosed : EventType("invoiceClosed") object InvoiceClosed : EventType("invoiceClosed")
object PopupClosed : EventType("popupClosed")
} }

View File

@@ -3,6 +3,7 @@ package dev.inmo.tgbotapi.webapps
import dev.inmo.tgbotapi.utils.TelegramAPIUrlsKeeper import dev.inmo.tgbotapi.utils.TelegramAPIUrlsKeeper
import dev.inmo.tgbotapi.webapps.haptic.HapticFeedback import dev.inmo.tgbotapi.webapps.haptic.HapticFeedback
import dev.inmo.tgbotapi.webapps.invoice.InvoiceClosedInfo import dev.inmo.tgbotapi.webapps.invoice.InvoiceClosedInfo
import dev.inmo.tgbotapi.webapps.popup.*
external class WebApp { external class WebApp {
val version: String val version: String
@@ -24,6 +25,15 @@ external class WebApp {
val viewportHeight: Float val viewportHeight: Float
val viewportStableHeight: Float val viewportStableHeight: Float
val isClosingConfirmationEnabled: Boolean
fun enableClosingConfirmation()
fun disableClosingConfirmation()
fun showPopup(params: PopupParams, callback: ClosePopupCallback? = definedExternally)
fun showAlert(message: String, callback: AlertCallback? = definedExternally)
fun showConfirm(message: String, callback: ConfirmCallback? = definedExternally)
@JsName("MainButton") @JsName("MainButton")
val mainButton: MainButton val mainButton: MainButton
@@ -38,6 +48,8 @@ external class WebApp {
internal fun onEventWithViewportChangedData(type: String, callback: (ViewportChangedData) -> Unit) internal fun onEventWithViewportChangedData(type: String, callback: (ViewportChangedData) -> Unit)
@JsName("onEvent") @JsName("onEvent")
internal fun onEventWithInvoiceClosedInfo(type: String, callback: (InvoiceClosedInfo) -> Unit) internal fun onEventWithInvoiceClosedInfo(type: String, callback: (InvoiceClosedInfo) -> Unit)
@JsName("onEvent")
internal fun onEventWithPopupClosedInfo(type: String, callback: (String?) -> Unit)
fun offEvent(type: String, callback: () -> Unit) fun offEvent(type: String, callback: () -> Unit)
@JsName("offEvent") @JsName("offEvent")
@@ -100,6 +112,18 @@ fun WebApp.onEvent(type: EventType.InvoiceClosed, eventHandler: InvoiceClosedEve
) )
} }
/**
* @return The callback which should be used in case you want to turn off events handling
*/
fun WebApp.onEvent(type: EventType.PopupClosed, eventHandler: PopupClosedEventHandler) = { it: String? ->
eventHandler(js("this").unsafeCast<WebApp>(), it)
}.also {
onEventWithPopupClosedInfo(
type.typeName,
callback = it
)
}
/** /**
* @return The callback which should be used in case you want to turn off events handling * @return The callback which should be used in case you want to turn off events handling
*/ */
@@ -124,8 +148,55 @@ fun WebApp.onSettingsButtonClicked(eventHandler: EventHandler) = onEvent(EventTy
* @return The callback which should be used in case you want to turn off events handling * @return The callback which should be used in case you want to turn off events handling
*/ */
fun WebApp.onInvoiceClosed(eventHandler: InvoiceClosedEventHandler) = onEvent(EventType.InvoiceClosed, eventHandler) fun WebApp.onInvoiceClosed(eventHandler: InvoiceClosedEventHandler) = onEvent(EventType.InvoiceClosed, eventHandler)
/**
* @return The callback which should be used in case you want to turn off events handling
*/
fun WebApp.onPopupClosed(eventHandler: PopupClosedEventHandler) = onEvent(EventType.PopupClosed, eventHandler)
fun WebApp.isInitDataSafe(botToken: String) = TelegramAPIUrlsKeeper(botToken).checkWebAppData( fun WebApp.isInitDataSafe(botToken: String) = TelegramAPIUrlsKeeper(botToken).checkWebAppData(
initData, initData,
initDataUnsafe.hash initDataUnsafe.hash
) )
fun WebApp.showPopup(
message: String,
title: String?,
buttons: Array<PopupButton>,
callback: ClosePopupCallback? = null
) = showPopup(
PopupParams(
message,
title,
buttons
),
callback
)
fun WebApp.showPopup(
message: String,
title: String?,
firstButton: PopupButton,
vararg otherButtons: PopupButton,
callback: ClosePopupCallback? = null
) = showPopup(
PopupParams(
message,
title,
arrayOf(firstButton, *otherButtons)
),
callback
)
var WebApp.requireClosingConfirmation
get() = isClosingConfirmationEnabled
set(value) {
if (value) {
enableClosingConfirmation()
} else {
disableClosingConfirmation()
}
}
fun WebApp.toggleClosingConfirmation() {
requireClosingConfirmation = !requireClosingConfirmation
}

View File

@@ -17,10 +17,14 @@ external interface WebAppUser {
val username: String? val username: String?
@JsName(languageCodeField) @JsName(languageCodeField)
val languageCode: String? val languageCode: String?
val is_premium: Boolean?
@JsName(photoUrlField) @JsName(photoUrlField)
val photoUrl: String? val photoUrl: String?
} }
val WebAppUser.isPremium
get() = is_premium == true
fun WebAppUser.asUser() = if (isBot == true) { fun WebAppUser.asUser() = if (isBot == true) {
CommonBot( CommonBot(
UserId(id), UserId(id),
@@ -34,6 +38,7 @@ fun WebAppUser.asUser() = if (isBot == true) {
firstName, firstName,
lastName ?: "", lastName ?: "",
username ?.let(::Username), username ?.let(::Username),
languageCode ?.let(::IetfLanguageCode) languageCode ?.let(::IetfLanguageCode),
isPremium = isPremium
) )
} }

View File

@@ -0,0 +1,3 @@
package dev.inmo.tgbotapi.webapps.popup
typealias ClosePopupCallback = (id: String) -> Unit

View File

@@ -0,0 +1,55 @@
package dev.inmo.tgbotapi.webapps.popup
import kotlin.js.json
external interface PopupButton {
val id: String
val type: PopupButtonType
val text: String?
}
fun PopupButton(
id: String,
type: PopupButtonType,
text: String? = null
) = json(
*listOfNotNull(
"id" to id,
"type" to type.typeName,
("text" to text).takeIf { text != null }
).toTypedArray()
).unsafeCast<PopupButton>()
value class PopupButtonType(
val typeName: String
) {
companion object {
val Default = PopupButtonType("default")
val Ok = PopupButtonType("ok")
val Close = PopupButtonType("close")
val Cancel = PopupButtonType("cancel")
val Destructive = PopupButtonType("destructive")
}
}
fun DefaultPopupButton(
id: String,
text: String
) = PopupButton(id, PopupButtonType.Default, text)
fun OkPopupButton(
id: String
) = PopupButton(id, PopupButtonType.Ok)
fun ClosePopupButton(
id: String
) = PopupButton(id, PopupButtonType.Close)
fun CancelPopupButton(
id: String
) = PopupButton(id, PopupButtonType.Cancel)
fun DestructivePopupButton(
id: String,
text: String
) = PopupButton(id, PopupButtonType.Destructive, text)

View File

@@ -0,0 +1,48 @@
package dev.inmo.tgbotapi.webapps.popup
import kotlin.js.json
external interface PopupParams {
val message: String
val title: String?
val buttons: Array<PopupButton>
}
fun PopupParams(
message: String,
title: String?,
buttons: Array<PopupButton>
) = json(
*listOfNotNull(
"message" to message,
"buttons" to buttons,
("title" to title).takeIf { title != null }
).toTypedArray()
).unsafeCast<PopupParams>()
fun PopupParams(
message: String,
firstButton: PopupButton,
vararg otherButtons: PopupButton
) = PopupParams(
message,
null,
arrayOf(
firstButton,
*otherButtons
)
)
fun PopupParams(
title: String,
message: String,
firstButton: PopupButton,
vararg otherButtons: PopupButton
) = PopupParams(
message,
title,
arrayOf(
firstButton,
*otherButtons
)
)